Pytorch学习
Posted 采蘑菇的csz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Pytorch学习相关的知识,希望对你有一定的参考价值。
Pytorch1_手写字识别
下面将构造一个三层全连接层的神经网络来对手写数字进行识别。
数据集的载入
import torch
from torch import nn
from torch.nn import functional as F
from torch import optim
import torchvision
from matplotlib import pyplot as plt
batch_size=512
train_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST('mnist_data/',train=True, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor()])),
batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST('mnist_data/', train=False, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor()])),
batch_size=batch_size, shuffle=False)
数据集展示
def plot_image(img, label, name):
fig = plt.figure()
for i in range(6):
plt.subplot(2, 3, i + 1)
plt.tight_layout()
plt.imshow(img[i][0], cmap='gray', interpolation='none')
plt.title(": ".format(name, label[i].item()))
plt.xticks([])
plt.yticks([])
plt.show()
x, y = next(iter(train_loader))
print(x.shape, y.shape, x.min(), x.max())
plot_image(x, y, 'image sample')
输出图片如下:
网络搭建
#定义网络
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
#xw+b
self.fc1 = nn.Linear(28*28,256)
self.fc2 = nn.Linear(256,64)
self.fc3 = nn.Linear(64,10)
def forward(self,x):
#x:[b,1,28,28]
#h1 = relu(xw1+b1)
x = F.relu(self.fc1(x))
#h2 = relu(h1w2+b2)
x = F.relu(self.fc2(x))
#h3 = h2w3+b3
x = self.fc3(x)
return x
模型训练
net = Net()
# [w1, b1, w2, b2, w3, b3]
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)
criterion = nn.CrossEntropyLoss()
train_loss = []
for epoch in range(4):
for batch_idx,(x,y) in enumerate(train_loader):
#x:[b,1,28,28],y:[512]
#[b,1,28,28]==>[b,784]
x = x.view(x.size(0),28*28)
#=>[b,10]
out = net(x)
loss = criterion(out,y)
optimizer.zero_grad()
loss.backward()
#w'=w - lr*grad
optimizer.step()
train_loss.append(loss.item())
if batch_idx %10 == 0:
print(epoch,batch_idx,loss.item())
torch.nn.CrossEntropyLoss()使用注意
CrossEntropyLoss(将 nn.LogSoftmax() 和 nn.NLLLoss() 结合在一个类中)一般用于计算分类问题的损失值,可以计算出不同分布之间的差距。
训练损失函数图
def plot_curve(data):
fig = plt.figure()
plt.plot(range(len(data)), data, color='blue')
plt.legend(['value'], loc='upper right')
plt.xlabel('step')
plt.ylabel('value')
plt.show()
plot_curve(train_loss)
模型预测
#test
total_correct = 0
for x,y in test_loader:
x = x.view(x.size(0),28*28)
out = net(x)
pred = out.argmax(dim=1)
correct = pred.eq(y).sum().float().item()
total_correct += correct
total_num = len(test_loader.dataset)
acc = total_correct/total_num
print("Teas ACC:",acc)
以上是关于Pytorch学习的主要内容,如果未能解决你的问题,请参考以下文章