optm.zero_grad()
미니배치마다 기울기를 0으로 초기화
안하면 누적합을 해버려서 이상한 값이 됨 (RNN 계산용)
cost.backward()
기울기 계산
optm.step()
파라미터 업데이트
for i in range(21):
y_hat = X_train.matmul(W) + b # X @ W
loss = torch.mean((y_hat - y_train)**2)
optm.zero_grad()
loss.backward() # 기울기 계산
optm.step()
print(y_hat.squeeze().detach(), loss.item())
배치 적용
ds = TensorDataset(X_train, y_train)
dataloader = DataLoader(ds, batch_size=2, shuffle=True)
list(ds)
model = nn.Linear(X_train.shape[1], y_train.shape[1])
optm = torch.optim.SGD(model.parameters(), lr=1e-5)
for epoch in range(2000):
for batch_idx, sample in enumerate(dataloader):
X_train, y_train = sample
pred = model(X_train)
cost = F.mse_loss(pred, y_train)
optm.zero_grad()
cost.backward()
optm.step()
if epoch % 200 == 0:
print('Batch : {}/{}, Loss : {}'.format(batch_idx+1, len(dataloader), cost.item()))
X_test = torch.FloatTensor([[73,80,75]])
model(X_test)
Class 구현
data와 optm은 그대로 사용
class myLinear(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(3, 1)
def forward(self, x):
return self.linear(x)
model = myLinear()
for epoch in range(2000):
pred = model(X_train)
cost = F.mse_loss(pred, y_train)
sgd.zero_grad()
cost.backward()
sgd.step()
if epoch % 200 == 0:
print(cost.item(), pred.squeeze().detach())
업데이트 될 때마다 값이 변경되는 옵션
optm.zero_grad()
미니배치마다 기울기를 0으로 초기화
안하면 누적합을 해버려서 이상한 값이 됨 (RNN 계산용)
cost.backward()
기울기 계산
optm.step()
파라미터 업데이트
배치 적용
Class 구현
data와 optm은 그대로 사용