빅데이터 분석 (3주차) 9월28일
파이토치를 이용하여 회귀모형 학습하기 (2)
import torch
import numpy as np
-
model: $y_i= w_0+w_1 x_i +\epsilon_i = 2.5 + 4x_i +\epsilon_i, \quad i=1,2,\dots,n$
-
model: ${\bf y}={\bf X}{\bf W} +\boldsymbol{\epsilon}$
${\bf y}=\begin{bmatrix} y_1 \\ y_2 \\ \dots \\ y_n\end{bmatrix}, \quad {\bf X}=\begin{bmatrix} 1 & x_1 \\ 1 & x_2 \\ \dots \\ 1 & x_n\end{bmatrix}, \quad {\bf W}=\begin{bmatrix} 2.5 \\ 4 \end{bmatrix}, \quad \boldsymbol{\epsilon}= \begin{bmatrix} \epsilon_1 \\ \dots \\ \epsilon_n\end{bmatrix}$
torch.manual_seed(202150754)
n=100
ones=torch.ones(n)
x,_=torch.randn(n).sort()
X=torch.vstack([ones,x]).T
W=torch.tensor([2.5,4])
ϵ=torch.randn(n)*0.4
y=X@W+ϵ
ytrue = X@W
-
지난 시간에 했던 for문을 보고 step 찾기
What= torch.tensor([-5.0,10.0],requires_grad=True)
for epoc in range(30):
Whats=Whats+[What.data.tolist()]
What.grad=None
yhat=X@What # yhat을 계산하는 공식을 알고 있거나, 과정이 필요
yhats=yhats+[yhat.data.tolist()]
loss=torch.sum((y-yhat)**2) # loss정의하는 과정이 필요!
losses = losses + [loss.item()]
loss.backward() # 미분을 하는 과정이 필요
What.data = What.data-alpha * What.grad.data # 미분한 값을 가지고 업데이트를 하는 과정
-
step1: yhat
-
step2: loss
-
step3: derivation
-
step4: update
-
feedforward 신경망을 설계하는 과정(딥러닝 용어!)
- 입력층으로 데이터가 입력되고, 1개 이상으로 구성되는 은닉 층을 거쳐서 마지막에 있는 출력 층으로 출력 값을 내보내는 과정.
- 이전 틍에서 나온 출력 값이, 층과 층 사이에 적용되는 가중치 영향을 받은 다음 다음 층의 입력 값으로 들어가는 것
-
이 단계가 잘 완료되었다면, 임의의 ${\bf\hat{W}}$을 넣었을 때 $\bf\hat{y}$를 계산할 수 있어야 함
-
model: ${\bf y}={\bf X}{\bf W} +\boldsymbol{\epsilon}$
What=torch.tensor([-5.0,10.0],requires_grad=True)
yhat1=X@What
yhat1
? 두 번 입력하면 코드까지 다나온다~~
torch.nn.Linear??
- ${\bf y}=\begin{bmatrix} y_1 \\ y_2 \\ \dots \\ y_n\end{bmatrix}, \quad {\bf X}=\begin{bmatrix} 1 & x_1 \\ 1 & x_2 \\ \dots \\ 1 & x_n\end{bmatrix}, \quad {\bf W}=\begin{bmatrix} 2.5 \\ 4 \end{bmatrix}, \quad \boldsymbol{\epsilon}= \begin{bmatrix} \epsilon_1 \\ \dots \\ \epsilon_n\end{bmatrix}$
net=torch.nn.Linear(in_features=2,out_features=1,bias=False)
- in_features – size of each input sample
- out_features – size of each output sample
- bias – If set to False, the layer will not learn an additive bias. Default: True
- Linear라는 클래스를 사용하여, in_features입력차원이자 $X(1,x_i)$라서 2, outfeatures출력차원이자 $y{hat}$라서 1
- bias가 False 인 이유는 $X(1,x_i)$에서 1이 bias의 역할을 하고 있기 때문에 필요가 없어서
net.weight.data # 우리가 원하는 입력값이 아니야
net.weight.data=torch.tensor([[-5.0,10.0]])
net.weight.data
net(X)
yhat2=net(X)
- 네트워크에 X를 입력으로 넣음으로써 y를 구하는 법
-
model: $y_i= w_0+w_1 x_i +\epsilon_i = 2.5 + 4x_i +\epsilon_i, \quad i=1,2,\dots,n$
net=torch.nn.Linear(in_features=1,out_features=1,bias=True)
- Linear라는 클래스를 사용하여, in_features입력차원이자 $x_i$라서 1, outfeatures출력차원이자 $y{hat}$라서 1
- bias가 True 인 이유는 bias term상수항이 존재하는 네트워크라 정의했기 때문
net.weight.data # 입력차원을 1로 했기 때문에 출력차원 1개만 값이 나온 것.
net.weight.data=torch.tensor([[10.0]]) # tensor 괄호 수 따라가..
net.bias.data=torch.tensor([-5.0])
net.weight,net.bias
- $X$가 아니라 $x(즉, x_i)$를 넣어야 함
- net(x.reshape(100,1)) x.reshape은 100값이 나오지만, (100,1)로 차원 명시 해주기
net(x.reshape(100,1))
- 방법 2와 3의 결과가 같아서 방법 3의 yhat은 따로 변수화하지 않음
loss=torch.mean((y-yhat1)**2)
loss
loss=torch.mean((y-yhat2)**2)
loss
- 두 값이 다르기도 하고, 187.0950는 잘못된 결과
- grad_fn=
주의깊게 보기</li> </ul> </div> </div> </div> (y-yhat2).shape
y.shape
yhat2.shape
- 차원에 대한 개념 파악 너무 중요$\star$
torch.mean((y-yhat2.flatten())**2) # yhat2를 벡터화시키는 방법 1
loss=torch.mean((y.reshape(100,1)-yhat2)**2) # y의 dhape을 바꿔주는 방법 2 loss
torch.nn.MSELoss는 class함수
torch.nn.MSELoss??
definition of torch.nn.MSELoss
- Creates a criterion that measures the mean squared error (squared L2 norm) between each element in the input $xx$ and target $yy$.
lossfn=torch.nn.MSELoss() # 단지 입력만하면 loss function이 만들어짐
loss=lossfn(y,yhat1) loss
loss=lossfn(y.reshape(100,1),yhat2) loss
- 미분 꼬리표 붙은 모습! grad_fn=
</li> </ul> </div> </div> </div> - 총 6가지 조합으로 loss를 구할 수 있다.
-
model: $y_i= w_0+w_1 x_{i1}+w_2 x_{i2} +\epsilon_i = 2.5 + 4x_{1i} + -2x_{2i}+\epsilon_i, \quad i=1,2,\dots,n$torch.manual_seed(202150754) n=100 ones=torch.ones(n) x1,_=torch.randn(n).sort() x2,_=torch.randn(n).sort() X=torch.vstack([ones,x1,x2]).T W=torch.tensor([2.5,4.0,-2.0]) ϵ=torch.randn(n)*0.5 y=X@W+ϵ ytrue=X@W
net=torch.nn.Linear(in_features=3,out_features=1,bias=False)
net.weight.data
net.weight.data=torch.tensor([[2.5,5.0,-2.0]])
net.weight.data
net(X)
yhat=net(X)
lossfn=torch.nn.MSELoss()
loss=lossfn(y,yhat)
loss