PyTorch CNN – 训练模型

把训练数据喂给模型,多次迭代对模型进行优化。

for epoch in range(2):  # 对数据集进行多次循环

    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # 获取输入; 数据格式是 [inputs, labels] 列表
        inputs, labels = data

        # 梯度清零
        optimizer.zero_grad()

        # 前向计算输出,反向传播,优化
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        # 输出统计数据
        running_loss += loss.item()
        if i % 2000 == 1999:    # 每2000个小批量打印一次
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')

输出

[1,  2000] loss: 2.179
[1,  4000] loss: 1.837
[1,  6000] loss: 1.651
[1,  8000] loss: 1.583
[1, 10000] loss: 1.537
[1, 12000] loss: 1.476
[2,  2000] loss: 1.423
[2,  4000] loss: 1.377
[2,  6000] loss: 1.384
[2,  8000] loss: 1.348
[2, 10000] loss: 1.328
[2, 12000] loss: 1.290
Finished Training


浙ICP备17015664号 浙公网安备 33011002012336号 联系我们 网站地图  
@2019 qikegu.com 版权所有,禁止转载