介绍
这篇文章给大家分享的是有关pytorch如何实现手写数字图片识别的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
具体内容如下
数据集:MNIST数据集,代码中会自动下载,不用自己手动下载。数据集很小,不需要GPU设备,可以很好的体会到pytorch的魅力。
模型+训练+预测程序:
import 火炬 得到torch import 神经网络 得到torch.nn import  functional as F 得到torch import  optim import torchvision 得到matplotlib import  pyplot as  plt 得到utils import  plot_image, plot_curve, one_hot #,step1 load 数据集 batch_size =512 时间=train_loader torch.utils.data.DataLoader ( ,,,torchvision.datasets.MNIST (& # 39; mnist_data& # 39;,,火车=True,,下载=True, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,变换=torchvision.transforms.Compose ([ ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,torchvision.transforms.ToTensor (), ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,torchvision.transforms.Normalize ( ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,(0.1307),(0.3081) ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,))), ,,,batch_size=batch_size,洗牌=True) 时间=test_loader torch.utils.data.DataLoader ( ,,,torchvision.datasets.MNIST (& # 39; mnist_data/& # 39;,,火车=False,,下载=True, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,变换=torchvision.transforms.Compose ([ ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,torchvision.transforms.ToTensor (), ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,torchvision.transforms.Normalize ( ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,(0.1307),(0.3081) ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,))), ,,,batch_size=batch_size,洗牌=False) x ,, y =,下一个(iter (train_loader)) 打印(x.shape, y.shape, x.min (),, x.max ()) plot_image (x, y,,“image_sample") class 净(nn.Module): ,,,def __init__(自我): ,,,,,,,超级(净,,自我). __init__ () ,,,,,,,self.fc1 =, nn.Linear (28 * 28,, 256) ,,,,,,,self.fc2 =, nn.Linear (256,, 64) ,,,,,,,self.fc3 =, nn.Linear (64, 10) ,,,def 向前(自我,,x): ,,,,,,,#,x:, [b,, 1,, 28日,28日) ,,,,,,,#,h2 =, relu (xw1 +, b1) ,,,,,,,x =, F.relu (self.fc1 (x)) ,,,,,,,#,h3 =, relu(时间+ h2w2 b2) ,,,,,,,x =, F.relu (self.fc2 (x)) ,,,,,,,#,h4 =, h3w3 + b3 null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null nullpytorch如何实现手写数字图片识别