学习目标:
学习pytorch搭建神经网络
学习内容:
MNIST数据集有60000张图片作为训练集,10000张图片作为测试集,每张图片像素是28*28,单通道灰度图片;
一、pytorch搭建神经网络
1、加载必要的库
2、定义超参数
3、构建pipeline,对图像做处理
4、下载、加载数据
5、构建网络模型
6、定义优化器
7、定义训练的方法
8、定义测试方法
9、调用方法7/8
二、完整代码和运行结果
# 1 加载必要的库
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
# 2 定义超参数
BATCH_SIZE = 16 # 每批处理的数据
DEVICE = torch.device("cpu")
# DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") # 是否用GPU还是CPU训练
EPOCHS = 10 # 训练数据集的轮次
# 3 构建pipeline,对图像做处理
pipeline = transforms.Compose([
transforms.ToTensor(), # 将图片转换成tensor
transforms.N