Pytorch torch.autograd 与torch.optim的区别//一个求模型里面的梯度,一个通过再梯度来更新模型参数权重

Pytorch torch.autograd torch.optim的区别//一个求模型里面的梯度,一个通过再梯度来更新模型参数权重

#更新权重值,更新过程使用下面的公式:

weight = weight + learning_rate * gradient

1.Pytorch autograd,backward详解//这两个函数都是求参数梯度的

Pytorch autograd,backward详解 - 知乎

2.Pytorch学习记录|torch.autogradtorch.optim//纯手写的理论笔记也很好

Pytorch学习记录|torch.autograd和torch.optim_Zhengzhenghe的博客-CSDN博客

3.PyTorch——torch.autogradVariabletorch.nntorch.optim//通过代码来讲解,真心不错

PyTorch——torch.autograd和Variable,torch.nn,torch.optim_Albert的博客-CSDN博客

         一般每次epoch要将计算得到的各个参数节点的梯度值通过grad.data.zero_()全部置零,如果不置零,则计算的梯度值会被一直累加,这样就会影响到后续的计算,只不过optimizer优化器会自动执行这一步在链接3里面可以看到使用优化器和不使用的对比。

这里给一份feedforward代码供大家理论结合实践:

import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms


# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# Hyper-parameters 
input_size = 784
hidden_size = 500
num_classes = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001

# MNIST dataset 
train_dataset = torchvision.datasets.MNIST(root='../../data', 
                                           train=True, 
                                           transform=transforms.ToTensor(),  
                                           download=True)

test_dataset = torchvision.datasets.MNIST(root='../../data', 
                                          train=False, 
                                          transform=transforms.ToTensor())

# Data loader
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, 
                                           batch_size=batch_size, 
                                           shuffle=True)

test_loader = torch.utils.data.DataLoader(dataset=test_dataset, 
                                          batch_size=batch_size, 
                                          shuffle=False)

# Fully connected neural network with one hidden layer
class NeuralNet(nn.Module):
    def __init__(self, input_size, hidden_size, num_classes):
        super(NeuralNet, self).__init__()
        self.fc1 = nn.Linear(input_size, hidden_size) 
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(hidden_size, num_classes)  
    
    def forward(self, x):
        out = self.fc1(x)
        out = self.relu(out)
        out = self.fc2(out)
        return out

model = NeuralNet(input_size, hidden_size, num_classes).to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)  

# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):  
        # Move tensors to the configured device
        images = images.reshape(-1, 28*28).to(device)
        labels = labels.to(device)
        
        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)
        
        # Backward and optimize
        optimizer.zero_grad()
        loss.backward() 
        optimizer.step()

        #打印每个epoch的训练情况        
        if (i+1) % 100 == 0:
            print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' 
                   .format(epoch+1, num_epochs, i+1, total_step, loss.item()))

# Test the model
# In test phase, we don't need to compute gradients (for memory efficiency)
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.reshape(-1, 28*28).to(device)#因为第一次是784的全连接层,需要改变一下数据的shape
        labels = labels.to(device)#store data on relative hardware,generally cpu or gpu.
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print('Accuracy of the network on the 10000 test images: {} %'.format(100 * correct / total))

# Save the model checkpoint
torch.save(model.state_dict(), 'model.ckpt')

        '''
        optimizer.zero_grad()
        # 要将本次计算得到的各个参数节点的梯度值通过grad.data.zero_()全部置零,如果不置零,
        # 则计算的梯度值会被一直累加,这样就会影响到后续的计算
        loss.backward() 
        # 误差反向传播
        autograd,backward
        #详解//这两个函数都是求参数梯度的
        loss.backward()
        #这个函数的功能在于让模 型根据计算图自动计算每个节点的梯度值并根据需求进行保留
        optimzer.step
        #功能是使用计算得到的梯度值对各个节点的参数进行梯度更新
        ''' 

        若有疑问,欢迎讨论。

你可能感兴趣的:(#,深度学习Pytorch框架,pytorch,深度学习,python)