Loading...
墨滴

希仔

2021/04/06  阅读:30  主题:默认主题

Model training

import torch
import torchvision
import torch.nn as nn
from model import LeNet
import torch.optim as optim
import torchvision.transforms as transforms
def main():
    transform = transforms.Compose(
        [transforms.ToTensor(), # Convert a "PIL Image or "numpy.ndarpay to tensor
         transforms.Normalize((0.50.50.5), (0.50.50.5))]) #normalize a tensor image with mean and standard deviation

    # 50000张训练图片
    # 第一次使用时要将download设置为True才会自动去下载数据集
    train_set = torchvision.datasets.CIFAR10(root='./data', train=True,
                                             download=True, transform=transform)
    
    # 加载数据集,并分成一批一批的, 还有打乱数据集顺序
    train_loader = torch.utils.data.DataLoader(train_set, batch_size=36,
                                               shuffle=True, num_workers=0)

    # 10000张验证图片
    # 第一次使用时要将download设置为True才会自动去下载数据集
    val_set = torchvision.datasets.CIFAR10(root='./data', train=False,
                                           download=True, transform=transform)
    val_loader = torch.utils.data.DataLoader(val_set, batch_size=5000,
                                             shuffle=True, num_workers=0)
    
    # 将val_loader转换为一个可迭代的对象
    # next()会返回下一张图片和该图片的label
    val_data_iter = iter(val_loader)
    val_image, val_label = val_data_iter.next()
    
    # classes = ('plane', 'car', 'bird', 'cat',
    #            'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

    
    
    net = LeNet()
    loss_function = nn.CrossEntropyLoss()
    # Adam()的第一个参数是model的所有可训练参数, 即 net.parameters()
    # lr: learning rate
    optimizer = optim.Adam(net.parameters(), lr=0.001)
    
    
    
    # training model in 5 epochs
    for epoch in range(5):  # loop over the dataset multiple times

        running_loss = 0.0 # 用来累加在每一轮训练过程中的损失
        
        # 对batch进行迭代
        for step, data in enumerate(train_loader, start=0):
            # get the inputs; data is a list of [inputs, labels]
            inputs, labels = data

            # zero the parameter gradients
            # 将历史损失梯度清零
            # 每计算一个batch, 就需要调用一次optimizer.zero_grad()
            optimizer.zero_grad() 
            
            
            # forward + backward + optimize
            outputs = net(inputs) # 将input images输入到网络进行正向传播
            loss = loss_function(outputs, labels) # 计算(预测值与真实值的)损失
            loss.backward() # 将loss反向传播
            optimizer.step() # 进行参数的更新

            # print statistics
            running_loss += loss.item()
            if step % 500 == 499:    # print every 500 mini-batches
                with torch.no_grad():
                    outputs = net(val_image)  # [batch, 10]
                    predict_y = torch.max(outputs, dim=1)[1# argmax
                    accuracy = torch.eq(predict_y, val_label).sum().item() / val_label.size(0)

                    print('[%d, %5d] train_loss: %.3f  test_accuracy: %.3f' %
                          (epoch + 1, step + 1, running_loss / 500, accuracy))
                    running_loss = 0.0

    print('Finished Training')

    save_path = './Lenet.pth'
    torch.save(net.state_dict(), save_path)
if __name__ == '__main__':
    main()
Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./data/cifar-10-python.tar.gz



  0%|          | 0/170498071 [00:00<?, ?it/s]


Extracting ./data/cifar-10-python.tar.gz to ./data
Files already downloaded and verified
[1,   500] train_loss: 1.735  test_accuracy: 0.449
[1,  1000] train_loss: 1.454  test_accuracy: 0.456
[2,   500] train_loss: 1.255  test_accuracy: 0.547
[2,  1000] train_loss: 1.191  test_accuracy: 0.567
[3,   500] train_loss: 1.072  test_accuracy: 0.601
[3,  1000] train_loss: 1.042  test_accuracy: 0.621
[4,   500] train_loss: 0.956  test_accuracy: 0.626
[4,  1000] train_loss: 0.938  test_accuracy: 0.638
[5,   500] train_loss: 0.851  test_accuracy: 0.648
[5,  1000] train_loss: 0.885  test_accuracy: 0.652
Finished Training

希仔

2021/04/06  阅读:30  主题:默认主题

作者介绍

希仔