下载Fasion-MNIST数据集

Fashion-MNIST是一个替代原始的MNIST手写数字数据集的另一个图像数据集。 它是由Zalando(一家德国的时尚科技公司)旗下的研究部门提供。其涵盖了来自10种类别的共7万个不同商品的正面图片。Fashion-MNIST的大小、格式和训练集/测试集划分与原始的MNIST完全一致。60000/10000的训练测试数据划分,28x28的灰度图片。你可以直接用它来测试你的机器学习和深度学习算法性能,且不需要改动任何的代码。

Fashion-MNIST 数据集的中文文档说明

label包含了image里面64张图片对应的标签

标注编号 描述
0 T-shirt/top(T恤)
1 Trouser(裤子)
2 Pullover(套衫)
3 Dress(裙子)
4 Coat(外套)
5 Sandal(凉鞋)
6 Shirt(汗衫)
7 Sneaker(运动鞋)
8 Bag(包)
9 Ankle boot(踝靴)
  1. import torch # 导入pytorch
  2. from torch import nn, optim # 导入神经网络与优化器对应的类
  3. import torch.nn.functional as F
  4. from torchvision import datasets, transforms # 导入数据集与数据预处理的方法
  5. from torch.autograd import Variable
  6. import matplotlib.pyplot as plt
  7. %matplotlib inline

CNN Le-Net5

构建

设置超参数

  1. EPOCH = 3 # 训练次数
  2. LR = 1.0E-3 # 学习率
  3. batch_size = 64

数据预处理:

标准化图像数据,使得灰度数据在-1到+1之间

  1. transform = transforms.Compose(
  2. [transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
  3. # 下载Fashion-MNIST训练集数据,并构建训练集数据载入器trainloader,每次从训练集中载入64张图片,每次载入都打乱顺序
  4. trainset = datasets.FashionMNIST(
  5. 'dataset/', download=True, train=True, transform=transform)
  6. trainloader = torch.utils.data.DataLoader(
  7. trainset, batch_size, shuffle=True)
  8. # 下载Fashion-MNIST测试集数据,并构建测试集数据载入器trainloader,每次从测试集中载入64张图片,每次载入都打乱顺序
  9. testset = datasets.FashionMNIST(
  10. 'dataset/', download=True, train=False, transform=transform)
  11. # 分开验证集的输入和标签
  12. with torch.no_grad():
  13. test_x = Variable(torch.unsqueeze(testset.data,dim = 1)).type(torch.FloatTensor)
  14. test_y = testset.targets
  15. ### 显示图片和标签

显示多张图片 绘制封面图片的程序

  1. %matplotlib inline
  2. import matplotlib
  3. import matplotlib.pyplot as plt
  4. from IPython.core.pylabtools import figsize # import figsize
  5. figsize(12.5, 4) # 设置 figsize
  6. plt.rcParams['savefig.dpi'] = 600 #图片像素
  7. plt.rcParams['figure.dpi'] = 600 #
  8. imagedemo = image[0:50]
  9. imagedemolabel = label[0:50]
  10. labellist = ['T恤','裤子','套衫','裙子','外套','凉鞋','汗衫','运动鞋','包包','靴子']
  11. for i,img in enumerate(imagedemo):
  12. plt.subplot(5,10,i+1)
  13. imagedemo = img.reshape((28,28))
  14. plt.imshow(imagedemo)

随机显示一张图片以及对应的标签

  1. image, label = next(iter(trainloader))
  2. # image图片中有64张图片,我们查看索引为2的图片
  3. imagedemo = image[3]
  4. imagedemolabel = label[3]
  5. imagedemo = imagedemo.reshape((28,28))
  6. import matplotlib.pyplot as plt
  7. %matplotlib inline
  8. plt.imshow(imagedemo)
  9. labellist = ['T恤','裤子','套衫','裙子','外套','凉鞋','汗衫','运动鞋','包包','靴子']
  10. print(f'这张图片对应的标签是 {labellist[imagedemolabel]}')
  1. 这张图片对应的标签是 包包

构建CNN Le-Net 5 框架

  1. # Building CNN
  2. class CNN(nn.Module):
  3. def __init__(self):
  4. super().__init__()
  5. self.conv1 = nn.Sequential(nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=2,bias=True),
  6. nn.ReLU(),
  7. nn.MaxPool2d(kernel_size=2) # 默认 stride 为 kernel_size
  8. )
  9. # 输入的维度 输出的特征图个数 卷积核大小 步长 padding 池化大小 (28+4-5)/1 +1 卷积完 16*28*28
  10. # 池化之后 16*14*14
  11. self.conv2 = nn.Sequential(nn.Conv2d(in_channels=16,out_channels = 32, kernel_size = 5, stride = 1,padding= 2,bias=True),
  12. nn.ReLU(),# (14+4-5)/1+1 32*14*14
  13. nn.MaxPool2d(2), # 32*7*7
  14. )
  15. self.out = nn.Linear(32*7*7,10)
  16. def forward(self, x):
  17. # make sure input tensor is flattened
  18. x = self.conv1(x)
  19. x = self.conv2(x)
  20. x = x.view(x.size(0),-1) # 将数据展成一维向量
  21. output = self.out(x)
  22. return output

效果

  1. cnn = CNN()
  2. # print(cnn)
  3. # params = list(cnn.parameters())
  4. # print(len(params))
  5. # print(params[0].size())
  6. optimizer = torch.optim.Adam(cnn.parameters(),lr = LR )
  7. loss_function = nn.CrossEntropyLoss()
  8. for epoch in range(EPOCH):
  9. for step,(x,y) in enumerate(trainloader): # 第几个 batch 和 对应的 (x y)
  10. b_x = Variable(x)
  11. b_y = Variable(y)
  12. output = cnn(b_x)
  13. loss = loss_function(output,b_y)
  14. optimizer.zero_grad() # 每次batch都会重新初始化参数
  15. loss.backward() # 反向传播
  16. optimizer.step() # 参数更新
  17. if step % 100 ==0:
  18. test_output = cnn(test_x)
  19. pred_y = torch.max(test_output,1)[1].data.squeeze()
  20. accuracy = torch.div(sum(pred_y == test_y).float(),test_y.size(0)).item()
  21. #print(accuracy)
  22. print('Epoch: ',epoch, '|Step: {:4d} '.format(step) ,'|train loss: {:.4f}'.format(loss.item()),'|accuracy: {:.4 大专栏  CNN Mini-Fashion数据集以及Pytorch初体验f}'.format(accuracy))
  23. test_output = cnn(test_x[:20])
  24. pred_y = torch.max(test_output,1)[1].data.numpy().squeeze()
  25. print(pred_y[:20],'prediction number')
  26. print(test_y[:20].numpy(),'real number')
  1. Epoch: 0 |Step: 0 |train loss: 2.3198 |accuracy: 0.0985
  2. Epoch: 0 |Step: 100 |train loss: 0.5568 |accuracy: 0.6158
  3. Epoch: 0 |Step: 200 |train loss: 0.4198 |accuracy: 0.7657
  4. Epoch: 0 |Step: 300 |train loss: 0.4027 |accuracy: 0.7500
  5. Epoch: 0 |Step: 400 |train loss: 0.4926 |accuracy: 0.8013
  6. Epoch: 0 |Step: 500 |train loss: 0.5777 |accuracy: 0.8019
  7. Epoch: 0 |Step: 600 |train loss: 0.4225 |accuracy: 0.7863
  8. Epoch: 0 |Step: 700 |train loss: 0.3374 |accuracy: 0.7923
  9. Epoch: 0 |Step: 800 |train loss: 0.3786 |accuracy: 0.8097
  10. Epoch: 0 |Step: 900 |train loss: 0.5368 |accuracy: 0.7916
  11. Epoch: 1 |Step: 0 |train loss: 0.4121 |accuracy: 0.8282
  12. Epoch: 1 |Step: 100 |train loss: 0.1796 |accuracy: 0.8263
  13. Epoch: 1 |Step: 200 |train loss: 0.3874 |accuracy: 0.8095
  14. Epoch: 1 |Step: 300 |train loss: 0.1994 |accuracy: 0.7990
  15. Epoch: 1 |Step: 400 |train loss: 0.2593 |accuracy: 0.8180
  16. Epoch: 1 |Step: 500 |train loss: 0.3459 |accuracy: 0.8109
  17. Epoch: 1 |Step: 600 |train loss: 0.2256 |accuracy: 0.8291
  18. Epoch: 1 |Step: 700 |train loss: 0.2070 |accuracy: 0.8023
  19. Epoch: 1 |Step: 800 |train loss: 0.1974 |accuracy: 0.8039
  20. Epoch: 1 |Step: 900 |train loss: 0.2006 |accuracy: 0.8391
  21. Epoch: 2 |Step: 0 |train loss: 0.1453 |accuracy: 0.7999
  22. Epoch: 2 |Step: 100 |train loss: 0.2584 |accuracy: 0.8271
  23. Epoch: 2 |Step: 200 |train loss: 0.3501 |accuracy: 0.7970
  24. Epoch: 2 |Step: 300 |train loss: 0.2962 |accuracy: 0.8296
  25. Epoch: 2 |Step: 400 |train loss: 0.1276 |accuracy: 0.8364
  26. Epoch: 2 |Step: 500 |train loss: 0.1695 |accuracy: 0.8192
  27. Epoch: 2 |Step: 600 |train loss: 0.1782 |accuracy: 0.7678
  28. Epoch: 2 |Step: 700 |train loss: 0.2317 |accuracy: 0.7607
  29. Epoch: 2 |Step: 800 |train loss: 0.1997 |accuracy: 0.7731
  30. Epoch: 2 |Step: 900 |train loss: 0.3183 |accuracy: 0.8053
  31. [9 2 1 1 6 1 4 6 5 7 4 5 8 3 4 1 2 4 8 0] prediction number
  32. [9 2 1 1 6 1 4 6 5 7 4 5 7 3 4 1 2 4 8 0] real number

从结果中可以看出,Le-Net5架构的CNN网络的准确率最高大约为75%-85%.说实话这个效果,不应该是卷积神经网络的威力呀,接下来试一试普通的神经网络看看效果。

Feedforward neural network

用前向神经网络对比一下,看看效果。

构建

  1. ## feedforward_nn
  2. import torch
  3. import torch.nn as nn
  4. import torchvision.datasets as datasets
  5. import torchvision.transforms as transforms
  6. import matplotlib.pyplot as plt
  7. import torch.utils.data as data
  8. from torch.autograd import Variable
  9. input_size = 784
  10. hedden_size = 100
  11. num_classes = 10
  12. num_epochs = 15
  13. batch_size = 64
  14. lr = 0.001
  15. # 数据预处理:标准化图像数据,使得灰度数据在-1到+1之间
  16. transform = transforms.Compose(
  17. [transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
  18. # 下载Fashion-MNIST训练集数据,并构建训练集数据载入器trainloader,每次从训练集中载入64张图片,每次载入都打乱顺序
  19. trainset = datasets.FashionMNIST(
  20. 'dataset/', download=True, train=True, transform=transform)
  21. trainloader = torch.utils.data.DataLoader(
  22. trainset, batch_size, shuffle=True)
  23. # 下载Fashion-MNIST测试集数据,并构建测试集数据载入器trainloader,每次从测试集中载入64张图片,每次载入都打乱顺序
  24. testset = datasets.FashionMNIST(
  25. 'dataset/', download=False, train=True, transform=transform)
  26. testloader = torch.utils.data.DataLoader(testset, batch_size, shuffle=True)
  27. with torch.no_grad():
  28. test_x = Variable(torch.unsqueeze(testset.data,dim = 1)).type(torch.FloatTensor)
  29. test_y = testset.targets
  30. class Net(nn.Module):
  31. def __init__(self,input_size,hidden_size,num_calsses):
  32. super(Net, self).__init__()
  33. self.fc1 = nn.Linear(input_size,hedden_size)
  34. self.relu = nn.ReLU()
  35. self.fc2 = nn.Linear(hidden_size,num_classes)
  36. def forward(self, x):
  37. out = self.fc1(x)
  38. out = self.relu(out)
  39. out = self.fc2(out)
  40. return out
  41. net = Net(input_size,hedden_size,num_classes)
  42. criterion = nn.CrossEntropyLoss()
  43. optimizer = torch.optim.Adam(net.parameters(),lr = lr)
  44. for epoch in range(num_epochs):
  45. for step,(image,label) in enumerate(trainloader):
  46. images = Variable(image.view(-1,28*28))
  47. labels = Variable(label)
  48. optimizer.zero_grad()
  49. output = net(images)
  50. loss = criterion(output,label)
  51. loss.backward()
  52. optimizer.step()
  53. if (step) % 100 == 0:
  54. loss = loss.item()
  55. print("Epoch: {:2d}/{:2d}".format(epoch,num_epochs),
  56. "step: {:3d}/{:d}".format(step,int(len(trainset)/batch_size)),
  57. "loss: {:4f}".format(loss))
  58. # 计算准确率
  59. correct = 0
  60. total = 0
  61. for images,labels in testloader:
  62. images = Variable(images.view(-1,28*28))
  63. outputs = net(images)
  64. _,predict = torch.max(outputs.data,1)
  65. total += labels.size(0)
  66. correct += (predict == labels).sum()
  67. corre = correct.item()/total*100
  68. print("Accuracy of feedforward neural network is {:.2f}%".format(corre))
  69. test_x = test_x[:20].view(-1,28*28)
  70. test_output = net(test_x)
  71. pred_y = torch.max(test_output.data,1)[1].data.numpy().squeeze()
  72. print("real number,",test_y[:20].numpy())
  73. print("pred number,",pred_y)

效果

  1. Epoch: 14/15 step: 200/937 loss: 0.233361
  2. Epoch: 14/15 step: 300/937 loss: 0.137285
  3. Epoch: 14/15 step: 400/937 loss: 0.177613
  4. Epoch: 14/15 step: 500/937 loss: 0.255258
  5. Epoch: 14/15 step: 600/937 loss: 0.174280
  6. Epoch: 14/15 step: 700/937 loss: 0.132471
  7. Epoch: 14/15 step: 800/937 loss: 0.348314
  8. Epoch: 14/15 step: 900/937 loss: 0.172310
  9. Accuracy of feedforward neural network is 92.24%
  10. real number, [9 0 0 3 0 2 7 2 5 5 0 9 5 5 7 9 1 0 6 4]
  11. pred number, [6 0 0 6 0 2 7 2 5 5 0 9 5 6 0 9 1 2 6 4]

这就很尴尬,普通的神经网络效果很好,准确率为92%

。。。。还不知道原因是什么,可能是参数没有设置好,也可能是LeNet架构的缺陷,之后会更新更多的CNN框架,看看效果之后再做对比,分析原因。

总结

OK,anyway!

这篇笔记的目的在于学习pytorch的卷积神经网络基本构建方式和构建步骤。
总结为

  1. 构造数据集
  2. 创建CNN神经网络正向传播对象,需要定制网络的卷积核大小,步长等参数,以及激活函数等。
  3. 在epoch循环中,喂进去batchsize,调用cnn对象,正向传播,损失函数,逆向传播,优化算法进行下一步更新。
  4. 就算准确率,格式化输出你想要的loss或Accuracy

CNN Mini-Fashion数据集以及Pytorch初体验的更多相关文章

  1. pytorch入门2.0构建回归模型初体验(数据生成)

    pytorch入门2.x构建回归模型系列: pytorch入门2.0构建回归模型初体验(数据生成) pytorch入门2.1构建回归模型初体验(模型构建) pytorch入门2.2构建回归模型初体验( ...

  2. pytorch入门2.2构建回归模型初体验(开始训练)

    pytorch入门2.x构建回归模型系列: pytorch入门2.0构建回归模型初体验(数据生成) pytorch入门2.1构建回归模型初体验(模型构建) pytorch入门2.2构建回归模型初体验( ...

  3. pytorch入门2.1构建回归模型初体验(模型构建)

    pytorch入门2.x构建回归模型系列: pytorch入门2.0构建回归模型初体验(数据生成) pytorch入门2.1构建回归模型初体验(模型构建) pytorch入门2.2构建回归模型初体验( ...

  4. Spark系列-初体验(数据准备篇)

    Spark系列-初体验(数据准备篇) Spark系列-核心概念 在Spark体验开始前需要准备环境和数据,环境的准备可以自己按照Spark官方文档安装.笔者选择使用CDH集群安装,可以参考笔者之前的文 ...

  5. (数据科学学习手札35)tensorflow初体验

    一.简介 TensorFlow时谷歌于2015年11月宣布在Github上开源的第二代分布式机器学习系统,目前仍处于快速开发迭代中,有大量的新功能新特性在陆续研发中: TensorFlow既是一个实现 ...

  6. Spring boot集成Rabbit MQ使用初体验

    Spring boot集成Rabbit MQ使用初体验 1.rabbit mq基本特性 首先介绍一下rabbitMQ的几个特性 Asynchronous Messaging Supports mult ...

  7. 痞子衡嵌入式:恩智浦机器视觉模块OpenMV-RT那些事(1)- 初体验

    大家好,我是痞子衡,是正经搞技术的痞子.本系列痞子衡给大家介绍的是机器视觉模块OpenMV-RT初体验. 近些年机器视觉应用一直是个很火的方向,想象一下机器如果能长上"眼睛",是不 ...

  8. Kaggle初体验之泰坦尼特生存预测

    Kaggle初体验之泰坦尼特生存预测 学习完了决策树的ID3.C4.5.CART算法,找一个试手的地方,Kaggle的练习赛泰坦尼特很不错,记录下 流程     首先注册一个账号,然后在顶部菜单栏Co ...

  9. MindSpore手写数字识别初体验,深度学习也没那么神秘嘛

    摘要:想了解深度学习却又无从下手,不如从手写数字识别模型训练开始吧! 深度学习作为机器学习分支之一,应用日益广泛.语音识别.自动机器翻译.即时视觉翻译.刷脸支付.人脸考勤--不知不觉,深度学习已经渗入 ...

随机推荐

  1. POJ 3083:Children of the Candy Corn

    Children of the Candy Corn Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 11015   Acce ...

  2. Zookeeper--复制模式安装

    参考: https://www.cnblogs.com/lsdb/p/7297731.html https://zookeeper.apache.org/doc/r3.4.13/zookeeperSt ...

  3. Cracking Digital VLSI Verification Interview 第二章

    Computer Architecture 对Cracking Digital VLSI Verification Interview:Interview Success这本书的汉化,最新更新请关注微 ...

  4. UVA 11404 简单LCS模型DP 字典序比较

    这个题目求某个字符串中含的最长的回文子串. 就是一个很简单的LCS模型吗,而且我不明白为什么网上这么多人都说仿照某写法把字符串先逆序一下,然后求LCS,我只想问一下,有必要吗? 直接按LCS的套路来就 ...

  5. 排序算法 python实现

    一.排序的基本概念和分类 所谓排序,就是使一串记录,按照其中的某个或某些关键字的大小,递增或递减的排列起来的操作.排序算法,就是如何使得记录按照要求排列的方法. 排序的稳定性: 经过某种排序后,如果两 ...

  6. MySQL索引(一)

    1.索引的类型 1) B-Tree索引 (1)概念 人们常说的Mysql索引一般是指B-Tree索引,它使用B-Tree数据结构来存储数据.存储引擎以不同的方式使用B-Tree索引,性能也各有不同,各 ...

  7. ZJNU 2356 - 六学家

    “选出来三个六学家,他们的编号是i,j,k,满足i<j<k,且a[k]=a[j]-a[i]” 所以输入第i个数a[i]时,直接让答案加上前i-1个数中能构成差值为a[i]的数量即可 然后让 ...

  8. JavaScript学习总结(八)

    这一节结束,我们的JavaScript学习总结系列文章第一阶段就要结束了,今后会适当的补充一些高级的内容,敬请期待. 好了,废话不说进入这一节的学习. 联动框 联动框,实在是太常见了.比如淘宝,我们选 ...

  9. 图形化编程娱乐于教,Kittenblock实例,图章效果的音乐画面

    跟很多学生聊过,很多学生不是不努力,只是找不到感觉.有一点不可否认,同样在一个教室上课,同样是一个老师讲授,学习效果迥然不同.关键的问题在于,带入感,我能给出的建议,就是咬咬牙,坚持住,没有学不会的知 ...

  10. electron-builder打包跳过publish

    默认情况下执行 npm run release使用build命令打包时自动将打包好的安装程序发布到仓库,有时候不需要每次打包都上传到仓库,这时我们只需要在build命令后面加上参数-p never 即 ...