Function Approximator
) Neural networks are function approximators that stack affine transformations followed by nonlinear transformations.
Eval
과정은 with torch.no_grad():
설정해줘야 함iterator
통해, 돌면서 Batch Size
만큼 뽑아내며 eval
과정 처리.to(device)
이용해 Batch Size
만큼의 X 데이터/y 데이터로부터 예측 값/정답 값 정의view()
함수 : 필요 시, reshapedef func_eval(model,data_iter,device):
with torch.no_grad():
model.eval() # evaluate (affects DropOut and BN)
n_total,n_correct = 0,0
for batch_in,batch_out in data_iter:
y_trgt = batch_out.to(device)
model_pred = model(batch_in.view(-1, 28*28).to(device))
_,y_pred = torch.max(model_pred.data,1)
n_correct += (y_pred == y_trgt).sum().item()
n_total += batch_in.size(0)
val_accr = (n_correct/n_total)
model.train() # back to train mode
return val_accr
print ("Done")
전체 Dataset에서 정의한 iterator
통해, 돌면서 Batch Size
만큼 뽑아내며 train
과정 처리
[1] 포워드 과정
- (1)위에서 정의한
CustomModel
의forward(self, x)
함수와 (2)선택한loss
함수(크로스엔트로피 등)에 배치를 돌면서피드포워드
[2] 옵티마이저 및 로스 업데이트 과정 (backpropagation
)
- (1)
옵티마이저.zero_grad()
로 값 리셋, (2)출력로스.backward()
로 미분값 백워드, (3)옵티마이저.step()
로 값 업데이트
- code
print ("Start training.")
M.init_param() # initialize parameters
M.train()
EPOCHS,print_every = 10,1
for epoch in range(EPOCHS):
loss_val_sum = 0
for batch_in,batch_out in train_iter:
# Forward path
y_pred = M.forward(batch_in.view(-1, 28*28).to(device))
loss_out = loss(y_pred,batch_out.to(device))
# Update
optm.zero_grad() # reset gradient
loss_out.backward() # backpropagate
optm.step() # optimizer update
loss_val_sum += loss_out
loss_val_avg = loss_val_sum/len(train_iter)
# Print
if ((epoch%print_every)==0) or (epoch==(EPOCHS-1)):
train_accr = func_eval(M,train_iter,device)
test_accr = func_eval(M,test_iter,device)
print ("epoch:[%d] loss:[%.3f] train_accr:[%.3f] test_accr:[%.3f]."%
(epoch,loss_val_avg,train_accr,test_accr))
print ("Done")
Generalization
Cross-validations
Bias와 Variance
torch.optim
라이브러리 활용해 선언momentum
옵티마이저는 momentum=(확률값)
옵션 추가- code
### 임포트 : import torch.optim as optim
LEARNING_RATE = 1e-2
# Instantiate models
model_sgd = Model(name='mlp_sgd',xdim=1,hdims=[64,64],ydim=1).to(device)
model_momentum = Model(name='mlp_momentum',xdim=1,hdims=[64,64],ydim=1).to(device)
model_adam = Model(name='mlp_adam',xdim=1,hdims=[64,64],ydim=1).to(device)
# Optimizers
loss = nn.MSELoss()
optm_sgd = optim.SGD(model_sgd.parameters(), lr=LEARNING_RATE)
optm_momentum = optim.SGD(model_momentum.parameters(), lr=LEARNING_RATE, momentum=0.9)
optm_adam = optim.Adam(model_adam.parameters(), lr=LEARNING_RATE)
print ("Done.")
Adam
Adam
은 짧은 학습 시간부터 성능(정확도)이 확보됨Adam
에는adaptive learning
개념이 반영된 접근법. (adaptive learning
: 어떠한 파라미터에 대해서는 lr을 높이고, 다른 어떠한 파라미터에 대해서는 lr을 줄여나감)- 따라서, 똑같은 lr을 선언해주어도 더 빠르게 성능이 확보될 수 있다..! ✨
Momentum
은 학습 시간이 조금 길어지면 성능 확보됨. 반면, SGD는 같은 시간까지도 성능이 확보되지 않음Momentum
은 이전 배치의gradient
정보를 활용해 현재 배치 턴에서 사용하겠다는 접근법- 이러한 점에서 미니배치일 때,
SGD
보다 좋다..! ✨
SGD
는 데이터에서 큰 특징이 되는 파트 위주로 학습이 잘되고, 세부적으로는 잘 놓치는 모양새를 보임- 하지만,
SGD
는 오랜 학습 시간이 흘렀을 때에는 더 좋은 성능을 보일 순 있다.
Adam
/rAdam
을 초기에 사용하면 어느정도의 성능을 짧은 시간에 효율적으로 확보할 수 있다..! ✨Wonderful Content, Now i'm a massive believer for offer suggestions relating to internet websites to make sure you let the web page creators understandthat they’ve incorporated an issue good to make sure you just a couple of! ufamobile
This is cool post and i quite like to see this post. your site is fantastic and you have good staff in your blog. nice sharing thanks. łóżko dla chłopca
Fine Posting, We're an important believer around writing commentary for web pages so that you can allow the site freelancers realise that they’ve increased a little something valuable so that you can the ether!tennis scholarships USA