题外话
用MNIST数据集来进行模型学习的通用代码:
import torch
from torchvision import transforms #图像
from torchvision import datasets
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.optim as optim
#Dataset&Dataloader必备
batch_size = 64
#pillow(PIL)读的原图像格式为W*H*C,原值较大
# 转为格式为C*W*H值为0-1的Tensor
transform = transforms.Compose([
#变为格式为C*W*H的Tensor
transforms.ToTensor(),
#第一个是均值,第二个是标准差,变值为0-1
transforms.Normalize((0.1307, ), (0.3081, ))
])
train_dataset = datasets.MNIST(root='../dataset/mnist/',
train=True,
download=True,
transform = transform)
train_loader = DataLoader(train_dataset,shuffle=True,batch_size=batch_size)
test_dataset = datasets.MNIST(root='../dataset/mnist/',
train=False,
download=True,
transform = transform)
test_loader = DataLoader(test_dataset, shuffle=False, batch_size=bacth_size)
class Net(torch.nn.Module):
def __init__(self):
#根据实际情况自己写
def forward(self, x):
##根据初试函数写
model = Net()
#交叉熵损失
criterion = torch.nn.CrossEntropyLoss()
#随机梯度下降,momentum表冲量,在更新时一定程度上保留原方向
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
#这里还可以选择是否要用GPU跑模型
#用显卡来算,就是把模型迁移到GPU上去
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
#通过这句话改跑模型的设备
model.to(device)
def train(epoch):
running_loss = 0.0
#提取数据
for batch_idx, data in enumerate(train_loader, 0):
inputs, target = data
#用GPU要加这句:inputs, target = inputs.to(device), target.to(device)
#优化器清零
optimizer.zero_grad()
#前馈+反馈+更新
outputs = model(inputs)
loss = criterion(outputs, target)
loss.backward()
optimizer.step()
#累计loss
running_loss += loss.item()
if batch_idx % 300 == 299:
print('[%d, %5d] loss: %.3f' % (epoch+1, batch_idx+1, running_loss/300))
running_loss = 0.0
def test():
correct = 0
total = 0
#避免计算梯度
with torch.no_grad():
for data in test_loader:
images, labels = data
#GPU就加:images, labels = images.to(device), labels.to(device)
outputs = model(images)
#取每一行(dim=1表第一个维度)最大值(max)的下标(predicted)及最大值(_)
_, predicted = torch.max(outputs.data, dim=1)
#加上这一个批量的总数(batch_size),label的形式为[N,1]
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy on test set: %d %%' % (100 * correct/total))
if __name__=='__main__':
for epoch in range(10):
train(epoch)
test()