4-6-1-11. Training a Network Solution

stochastic gradient descent and pass in our parameters.

Then, here is our training pass.

So, for each image in labels in trainloader,

we’re going to flatten it and then zero out the gradients using optimizer. zero_ grad.

Pass our images forward through the model and the output and then from that,

we can calculate our loss and then do

a backward pass and then finally with the gradients,

we can do this optimizer step.

So, if I run this and we wait a little bit for to train,

we can actually see the loss dropping over time, right?

So, after five epochs,

we see that the first one,

it starts out fairly high at 1.9 but after five epochs,

continuous drop as we’re training and we see it much lower after five epochs.

So, if we kept training then our network would learn the data

better and better and the training loss would be even smaller.

So, now with our training network,

we can actually see what our network thinks it’s seen in these images.

So, for here, we can pass in an image.

In this case, it’s the image of a number two and

then this is what our network is predicting now.

So, you can see pretty easily that it’s putting most of the probability,

most of its prediction into the class for the digit two.

So we try it again and put in passes in number eight and again, it’s predicting eight.

So, we’ve managed to actually train

our network to make accurate predictions for our digits.

So next step, you’ll write the code for training

a neutral network on a more complex dataset and you’ll be doing the whole thing,

defining the model, running the training loop, all that. Cheers.

다시 안녕. 자, 여기 제가 구현한 기차 패스에 대한 제 솔루션이 있습니다.

그래서 여기에서 우리는 우리의 모델을 정상과 같이 정의하고 있습니다.

다음을 사용하여 음의 로그 가능성 손실

확률적 경사 하강법을 사용하고 매개변수를 전달합니다.

다음은 교육 패스입니다.

따라서 trainloader의 레이블에 있는 각 이미지에 대해

평면화한 다음 옵티마이저를 사용하여 그라디언트를 0으로 만듭니다. 제로_ 대학원.

모델과 출력을 통해 이미지를 전달한 다음,

손실을 계산한 다음

역방향 패스를 사용한 다음 마지막으로 그라디언트를 사용하여

이 최적화 단계를 수행할 수 있습니다.

그래서 이것을 실행하고 우리가 훈련할 때까지 조금 기다리면,

실제로 시간이 지남에 따라 손실이 감소하는 것을 볼 수 있습니다. 그렇죠?

그래서 5개의 에포크 후에,

우리는 첫 번째 것을 봅니다.

1.9에서 상당히 높게 시작하지만 5개의 ​​에포크 후에,

우리가 훈련하는 동안 지속적으로 하락하고 5개의 에포크 후에 훨씬 더 낮은 것을 볼 수 있습니다.

따라서 계속 훈련하면 네트워크에서 데이터를 학습하게 됩니다.

점점 더 좋아지고 훈련 손실은 더 작아질 것입니다.

이제 교육 네트워크를 통해

우리는 실제로 우리 네트워크가 이 이미지에서 본 것이 무엇이라고 생각하는지 볼 수 있습니다.

여기에서는 이미지를 전달할 수 있습니다.

이 경우 숫자 2의 이미지이며

이것이 우리 네트워크가 지금 예측하는 것입니다.

그래서, 당신은 그것이 대부분의 가능성을 둔다는 것을 아주 쉽게 볼 수 있습니다.

대부분의 예측은 숫자 2에 대한 클래스에 포함됩니다.

그래서 우리는 그것을 다시 시도하고 숫자 8에 패스를 넣고 다시 8을 예측합니다.

그래서 우리는 실제로 훈련에 성공했습니다.

우리의 숫자에 대한 정확한 예측을 하기 위해 네트워크를 사용합니다.

따라서 다음 단계에서는 학습용 코드를 작성합니다.

더 복잡한 데이터 세트에 대한 중립 네트워크를 사용하면 모든 작업을 수행하게 됩니다.

모델 정의, 훈련 루프 실행, 그 모든 것. 건배.

# The MNIST datasets are hosted on yann.lecun.com that has moved under CloudFlare protection
# Run this script to enable the datasets download
# Reference: https://github.com/pytorch/vision/issues/1938

from six.moves import urllib
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
urllib.request.install_opener(opener)

import torch
from torch import nn
import torch.nn.functional as F
from torchvision import datasets, transforms

# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
                                transforms.Normalize((0.5,), (0.5,)),
                              ])
# Download and load the training data
trainset = datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

# Note If you haven't seen nn.Sequential yet, please finish the end of the Part 2 notebook.

# Build a feed-forward network
model = nn.Sequential(nn.Linear(784, 128),
                      nn.ReLU(),
                      nn.Linear(128, 64),
                      nn.ReLU(),
                      nn.Linear(64, 10))

# Define the loss
criterion = nn.CrossEntropyLoss()

# Get our data
dataiter = iter(trainloader)

images, labels = next(dataiter)

# Flatten images
images = images.view(images.shape[0], -1)

# Forward pass, get our logits
logits = model(images)
# Calculate the loss with the logits and the labels
loss = criterion(logits, labels)

print(loss)
# tensor(2.2922, grad_fn=<NllLossBackward>)


## Solution ##################################
# TODO: Build a feed-forward network
# Build a feed-forward network
model = nn.Sequential(nn.Linear(784, 128),
                      nn.ReLU(),
                      nn.Linear(128, 64),
                      nn.ReLU(),
                      nn.Linear(64, 10),
                      nn.LogSoftmax(dim=1))


# TODO: Define the loss
# Define the loss
criterion = nn.NLLLoss()

# Get our data
images, labels = next(iter(trainloader))
# Flatten images
images = images.view(images.shape[0], -1)

# Forward pass, get our log-probabilities
logps = model(images)
# Calculate the loss with the logps and the labels
loss = criterion(logps, labels)

print(loss)
################################################


### Run this to check your work
# Get our data
dataiter = iter(trainloader)

images, labels = next(dataiter)

# Flatten images
images = images.view(images.shape[0], -1)

# Forward pass, get our logits
logits = model(images)
# Calculate the loss with the logits and the labels
loss = criterion(logits, labels)

print(loss)

# Build a feed-forward network
model = nn.Sequential(nn.Linear(784, 128),
                      nn.ReLU(),
                      nn.Linear(128, 64),
                      nn.ReLU(),
                      nn.Linear(64, 10),
                      nn.LogSoftmax(dim=1))

criterion = nn.NLLLoss()
dataiter = iter(trainloader)
images, labels = next(dataiter)
images = images.view(images.shape[0], -1)

logits = model(images)
loss = criterion(logits, labels)

print('Before backward pass: \n', model[0].weight.grad)

loss.backward()

print('After backward pass: \n', model[0].weight.grad)


from torch import optim

# Optimizers require the parameters to optimize and a learning rate
optimizer = optim.SGD(model.parameters(), lr=0.01)

print('Initial weights - ', model[0].weight)

dataiter = iter(trainloader)
images, labels = next(dataiter)
images.resize_(64, 784)

# Clear the gradients, do this because gradients are accumulated
optimizer.zero_grad()

# Forward pass, then backward pass, then update weights
output = model(images)
loss = criterion(output, labels)
loss.backward()
print('Gradient -', model[0].weight.grad)

# Take an update step and view the new weights
optimizer.step()
print('Updated weights - ', model[0].weight)




## Your solution here

model = nn.Sequential(nn.Linear(784, 128),
                      nn.ReLU(),
                      nn.Linear(128, 64),
                      nn.ReLU(),
                      nn.Linear(64, 10),
                      nn.LogSoftmax(dim=1))

criterion = nn.NLLLoss()
optimizer = optim.SGD(model.parameters(), lr=0.003)

epochs = 5
for e in range(epochs):
    running_loss = 0
    for images, labels in trainloader:
        # Flatten MNIST images into a 784 long vector
        images = images.view(images.shape[0], -1)
    
        # TODO: Training pass
        optimizer.zero_grad()
        
        output = model(images)
        loss = criterion(output, labels)
        loss.backward()
        optimizer.step()
        #####################
        
        running_loss += loss.item()
    else:
        print(f"Training loss: {running_loss/len(trainloader)}")
        

# With the network trained, we can check out it's predictions.

import helper

dataiter = iter(trainloader)
images, labels = next(dataiter)

img = images[0].view(1, 784)
# Turn off gradients to speed up this part
with torch.no_grad():
    logps = model(img)

# Output of the network are log-probabilities, need to take exponential for probabilities
ps = torch.exp(logps)
helper.view_classify(img.view(1, 28, 28), ps)
%d