任务6 Pytorch理解更多神经网络优化方法

本文深入探讨了Pytorch中常用的神经网络优化算法,包括SGD的梯度下降法,Momentum的动量优化,RMSprop的均方根propagation,以及Adam的自适应矩估计优化。这些优化技术对于提升模型训练效率和性能至关重要。
摘要由CSDN通过智能技术生成
  • SGD
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms

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

# 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.Sequential(nn.Linear(input_size, hidden_size),
                                 nn.ReLU())
        self.fc2 = nn.Linear(hidden_size, num_classes)  
    
    def forward(self, x):
        out = self.fc1(x)
        out = self.fc2(out)
        return out

model = NeuralNet(input_size, hidden_size, num_classes)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(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):  
        images = images.reshape(-1, 28 * 28)
        
        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)
        SGD_loss.append(loss)
        
        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        
        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)
        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))
Epoch [1/5], Step [100/600], Loss: 2.2769
Epoch [1/5], Step [200/600], Loss: 2.2770
Epoch [1/5], Step [300/600], Loss: 2.2553
Epoch [1/5], Step [400/600], Loss: 2.2327
Epoch [1/5], Step [500/600], Loss: 2.2199
Epoch [1/5], Step [600/600], Loss: 2.1841
Epoch [2/5], Step [100/600], Loss: 2.1550
Epoch [2/5], Step [200/600], Loss: 2.1324
Epoch [2/5], Step [300/600], Loss: 2.0896
Epoch [2/5], Step [400/600], Loss: 2.0818
Epoch [2/5], Step [500/600], Loss: 2.0478
Epoch [2/5], Step [600/600], Loss: 2.0630
Epoch [3/5], Step [100/600], Loss: 2.0151
Epoch [3/5], Step [200/600], Loss: 2.0137
Epoch [3/5], Step [300/600], Loss: 1.9326
Epoch [3/5], Step [400/600], Loss: 1.8756
Epoch [3/5], Step [500/600], Loss: 1.8812
Epoch [3/5], Step [600/600], Loss: 1.8286
Epoch [4/5], Step [100/600], Loss: 1.7895
Epoch [4/5], Step [200/600], Loss: 1.7809
Epoch [4/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值