deep_learing_lec/day2

view 는 나중에 설명 = 구조적인 문제가 있음.
reshape 랑 똑같다고 올라오지만 내부적으로는 다르다.
ptEx4
import torch
t1 = torch.tensor([1,2,3,4,5,6])
print(t1)
#tensor([1, 2, 3, 4, 5, 6])
print()
t2 = t1.view(2,3)
print(t2)
#tensor([[1, 2, 3],
# [4, 5, 6]])
print()
print(t1.reshape(2,3))
#tensor([[1, 2, 3],
# [4, 5, 6]])
print()
t3 = torch.tensor([[1,2],[3,4],[5,6]])
print(t3)
print(t3.size())
#torch.Size([3, 2])
print()
print(t3.view(-1)) #-1 = 만들어놓은걸 다 풀어버리겠다. 1차원으로 만듦
#tensor([1, 2, 3, 4, 5, 6])
print()
print(t3.view(1, -1))
print()
print(t3.view(2, -1))
print()
print(t3.view(3, -1))
print()
#===================3차원=========================
t4 = torch.tensor([[[1,2],[4,5]],[[5,6],[7,8]]])
print(t4)
print(t4.size())
#torch.Size([2, 2, 2])
print()
print(t4.view(-1))
print()
print(t4.view(1,-1))
print()
print(t4.view(2,-1))
print()
print(t4.view(4,-1))
print()
print(t4.view(2, 2, -1))
print()
#================합칠때 쓰는 함수===================
t5 = torch.tensor([[1,2,3],[4,5,6]])
t6 = torch.tensor([[10,20,30],[40,50,60]])
print(t5)
print()
print(t6)
print()
print(torch.cat([t5,t6], dim=0))
#행을 붙이는것
print()
print(torch.cat([t5,t6], dim=1))
#열을 붙이는것
ptEx5
import torch
t1 = torch.tensor([1,2,3,4,5,6]).view(3,2)
t2 = torch.tensor([7,8,9,10,11,12]).view(2,3)
print(t1)
print()
print(t2)
print()
t3= torch.mm(t1, t2)
print(t3)
# ( 3, 2 ) * ( 2, 3 ) => 3, 3 으로 된다. 대신 2랑 2가 같은 숫자여야 한다.
print()
print(torch.matmul(t1,t2))
# 내적을 구하든 곱을 구하든 matmul 사용하여 구할 수 있다.
# 공통으로 바라보는 곳의 수치값 / 원하는 목적지의 크기(상관성), 바라보는 목표가 같을수록 수치가 크다.

ptEx6
import torch
t1 = torch.tensor([[1,2,3],[4,5,6]])
print(t1)
print()
print(t1[:,:2])
print()
print(t1 >4)
#불 값을 리턴하지만 tensor / 인덱싱을 하기위해 하는것
print()
print(t1[t1>4])
print()
t1[:,:2] = 40
print(t1)
print()
t1[t1>4] = 100
print(t1)
print()
t2 = torch.tensor([[1,2,3],[4,5,6]])
t3 = torch.tensor([[8,9,10],[11,22,33]])
print(t2)
print()
print(t3)
print()
t4 = torch.cat([t2, t3], dim=0)
print(t4)
print()
for c in torch.chunk(t4, 4, dim=0):
print(c, end='\n\n')
for c in torch.chunk(t4, 3, dim=1):
print(c, end='\n\n')
for c in torch.chunk(t4, 2, dim=0):
print(c)
for c in torch.chunk(t4, 2, dim=1):
print(c)
# 먼저 2개를 나누고 나머지를 가져온다.
ptEx7
import torch
import torch.nn.init as init
t1 = init.uniform_(torch.FloatTensor(3,4))
print(t1)
print()
t2 = init.normal_(torch.FloatTensor(3,4), mean=10, std=3)
print(t2)
print()
t3 = torch.FloatTensor(torch.randn(3,4))
print(t3)
print()
t4 = init.constant_(torch.FloatTensor(3,4), 100)
print(t4)
print()


ptEx8
import torch
t1 = torch.zeros(1,4)
t2 = torch.zeros(4,1)
print(t1)
print()
print(t2)
print()
#====압축하기=====
print(torch.squeeze(t1))
#tensor([0., 0., 0., 0.])
print(torch.squeeze(t2))
#tensor([0., 0., 0., 0.])
print()
t2 = torch.zeros(2,1,3,1,4)
print(t2.size())
#torch.Size([2, 1, 3, 1, 4])
print(torch.squeeze(t2).size())
#torch.Size([2, 3, 4])
print(torch.squeeze(t2, dim=3).size())
# 3번만 압축을 시키겠다.
#torch.Size([2, 1, 3, 4])
print()
#=====압축풀기? 같이 1을 넣기=======
t3 = torch.zeros(2,3)
print(t3.size())
print(torch.unsqueeze(t3, dim=0).size())
print(torch.unsqueeze(t3, dim=1).size())
print(torch.unsqueeze(t3, dim=2).size())






고정된 값(상수)을 알면 구할 수 있다.
머신러닝으로 상수값을 구할 때 => 오차를 근거로 해서 (참고해서) 바꿈.
1. 임의의 값을 넣는다.
2. 예측값 뽑기
3. 에러(오차) 가 생긴다.
4. 오차값을 근거로 수정하기
계속 진행
미분 = 기울기 구하기 라고 일단은 생각하기
그라디언트 디센트


ptEx9
import torch
w = torch.tensor(2. , requires_grad=True)
y = 7 * w
y.backward()
#미분을 해준다. backward
#각 미분한 객체한테 미분한 값을 준다.
print('w로 미분한 값:', w.grad)
w2 = torch.tensor(3., requires_grad=True)
for epoch in range(20):
y2 = 5 * w2
y2.backward()
print('w2로 미분한값:', w2.grad)
#미분값을 계속해서 누적시키기 때문에 늘어난다.
#사용하고 나서 초기화를 시켜놔야 에러가 안난다.
w2.grad.zero_()()
linearEx1
import torch
x1_train = torch.FloatTensor([[73],[93],[89],[96],[73]])
x2_train = torch.FloatTensor([[80],[88],[91],[98],[65]])
x3_train = torch.FloatTensor([[75],[92],[90],[100],[70]])
y_train = torch.FloatTensor([[152],[185],[180],[196],[142]])
w1 = torch.zeros((1,1), requires_grad=True)
w2 = torch.zeros((1,1), requires_grad=True)
w3 = torch.zeros((1,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
import torch.optim as optim
optimizer = optim.SGD([w1, w2, w3, b], lr=1e-5)# 10의 -5승
for epoch in range(1000): #반복해준다.
optimizer.zero_grad() #값들을 참조해서 초기화해준다.
#예측값 얻어내기
hypothesis = torch.mm(x1_train, w1) + torch.mm(x2_train, w2) + torch.mm(x3_train, w3) + b
loss = torch.mean((hypothesis - y_train) ** 2)
loss.backward()
optimizer.step()
#step 은 w의 원래값을 가져오고 그라이던트 값을 가져오고 러닝메이트를 곱하고 빼는 과정을 해주는것
if epoch % 100 == 0 :
print('epoch:{}, w1:{:.4f}, w2:{:.4f}, w3:{:.4f}, b:{:.4f}, loss:{:.3f}'.format(
epoch+1, w1.item(), w2.item(), w3.item(), b.item(), loss.item()
))
#배열로 가져올때 넘파이, 스칼라값 하나만 가져올때 item으로
좀더 압축버전
import torch
x_train = torch.FloatTensor([[73,80,75],
[93,88,93],
[89,91,80],
[96,98,100],
[73,65,70]])
y_train = torch.FloatTensor([[152],[185],[180],[196],[142]])
W = torch.zeros((3,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
import torch.optim as optim
optimizer = optim.SGD([W, b], lr=1e-5)# 10의 -5승
for epoch in range(1000): #반복해준다.
optimizer.zero_grad() #값들을 참조해서 초기화해준다.
#예측값 얻어내기
hypothesis = x_train.matmul(W) + b
loss = torch.mean((hypothesis - y_train) ** 2)
loss.backward()
optimizer.step()
if epoch % 100 == 0:
print('epoch:{}, w1:{:.4f}, w2:{:.4f}, w3:{:.4f}, b:{:.4f}, loss:{:.3f}'.format(
epoch + 1, W[0].item(), W[1].item(), W[2].item(), b.item(), loss.item()
))
'AI' 카테고리의 다른 글
| Day70_Ai(6)_Pm (0) | 2025.11.03 |
|---|---|
| Day67_Ai(5)_Pm (0) | 2025.10.31 |
| Day66_Ai(4)_Pm (0) | 2025.10.30 |
| Day66_Ai(4)_Pm / 딥러닝전 설치 (0) | 2025.10.30 |
| Day66_Ai(4)_Am (0) | 2025.10.30 |