이제 심층 신경망에 데이터를 적용하여 모델을 학습시킵니다.
코드 5-8 심층 신경망을 이용한 모델 학습
num_epochs = 5
count = 0
loss_list = [] ------ ①
iteration_list = []
accuracy_list = []
predictions_list = []
labels_list = []
for epoch in range(num_epochs):
for images, labels in train_loader: ------ ②
images, labels = images.to(device), labels.to(device) ------ ③
train = Variable(images.view(100, 1, 28, 28)) ------ ④
labels = Variable(labels)
outputs = model(train) ------ 학습 데이터를 모델에 적용
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
count += 1
if not (count % 50): ------ count를 50으로 나누었을 때 나머지가 0이 아니라면 실행
total = 0
correct = 0
for images, labels in test_loader:
images, labels = images.to(device), labels.to(device)
labels_list.append(labels)
test = Variable(images.view(100, 1, 28, 28))
outputs = model(test)
predictions = torch.max(outputs, 1)[1].to(device)
predictions_list.append(predictions)
correct += (predictions == labels).sum()
total += len(labels)
accuracy = correct * 100 / total ------ ⑤
loss_list.append(loss.data) ------ ①′
iteration_list.append(count)
accuracy_list.append(accuracy)
if not (count % 500):
print("Iteration: {}, Loss: {}, Accuracy: {}%".format(count, loss.data, accuracy))