莫烦pytorch学习笔记(八)——卷积神经网络(手写数字识别实现)
这个代码实现了预测和可视化
import os # third-party library
import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import matplotlib.pyplot as plt # torch.manual_seed() # reproducible # Hyper Parameters
EPOCH = # train the training data n times, to save time, we just train epoch
BATCH_SIZE =
LR = 0.001 # learning rate
DOWNLOAD_MNIST = False # Mnist digits dataset
if not(os.path.exists('./mnist/')) or not os.listdir('./mnist/'):
# not mnist dir or mnist is empyt dir
DOWNLOAD_MNIST = True train_data = torchvision.datasets.MNIST(
root='./mnist/',
train=True, # this is training data
transform=torchvision.transforms.ToTensor(), # 把数据压缩到0到1之间的numpy数据
# torch.FloatTensor of shape (C x H x W) and normalize in the range [0.0, 1.0]
download=DOWNLOAD_MNIST,
) # plot one example
print(train_data.train_data.size()) # (, , )
print(train_data.train_labels.size()) # ()
plt.imshow(train_data.train_data[].numpy(), cmap='gray')
plt.title('%i' % train_data.train_labels[])
plt.show() # Data Loader for easy mini-batch return in training, the image batch shape will be (, , , )
train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True) # pick samples to speed up testing
test_data = torchvision.datasets.MNIST(root='./mnist/', train=False)
test_x = torch.unsqueeze(test_data.test_data, dim=).type(torch.FloatTensor)[:]/. # shape from (, , ) to (, , , ), value in range(,)
test_y = test_data.test_labels[:] class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Sequential( # input shape (, , )
nn.Conv2d(
in_channels=, # input height
out_channels=, # n_filters
kernel_size=, # filter size
stride=, # filter movement/step
padding=, # if want same width and length of this image after Conv2d, padding=(kernel_size-)/ if stride=
), # output shape (, , )
nn.ReLU(), # activation
nn.MaxPool2d(kernel_size=), # choose max value in 2x2 area, output shape (, , )
)
self.conv2 = nn.Sequential( # input shape (, , )
nn.Conv2d(, , , , ), # output shape (, , )
nn.ReLU(), # activation
nn.MaxPool2d(), # output shape (, , )
)
self.out = nn.Linear( * * , ) # fully connected layer, output classes def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = x.view(x.size(), -) # flatten the output of conv2 to (batch_size, * * )
output = self.out(x)
return output, x # return x for visualization cnn = CNN()
print(cnn) # net architecture optimizer = torch.optim.Adam(cnn.parameters(), lr=LR) # optimize all cnn parameters
loss_func = nn.CrossEntropyLoss() # the target label is not one-hotted # following function (plot_with_labels) is for visualization, can be ignored if not interested
from matplotlib import cm
try: from sklearn.manifold import TSNE; HAS_SK = True
except: HAS_SK = False; print('Please install sklearn for layer visualization')
def plot_with_labels(lowDWeights, labels):
plt.cla()
X, Y = lowDWeights[:, ], lowDWeights[:, ]
for x, y, s in zip(X, Y, labels):
c = cm.rainbow(int( * s / )); plt.text(x, y, s, backgroundcolor=c, fontsize=)
plt.xlim(X.min(), X.max()); plt.ylim(Y.min(), Y.max()); plt.title('Visualize last layer'); plt.show(); plt.pause(0.01) plt.ion()
# training and testing
for epoch in range(EPOCH):
for step, (b_x, b_y) in enumerate(train_loader): # gives batch data, normalize x when iterate train_loader output = cnn(b_x)[] # cnn output
loss = loss_func(output, b_y) # cross entropy loss
optimizer.zero_grad() # clear gradients for this training step
loss.backward() # backpropagation, compute gradients
optimizer.step() # apply gradients if step % == :
test_output, last_layer = cnn(test_x)
pred_y = torch.max(test_output, )[].data.numpy()
accuracy = float((pred_y == test_y.data.numpy()).astype(int).sum()) / float(test_y.size())
print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.numpy(), '| test accuracy: %.2f' % accuracy)
if HAS_SK:
# Visualization of trained flatten layer (T-SNE)
tsne = TSNE(perplexity=, n_components=, init='pca', n_iter=)
plot_only =
low_dim_embs = tsne.fit_transform(last_layer.data.numpy()[:plot_only, :])
labels = test_y.numpy()[:plot_only]
plot_with_labels(low_dim_embs, labels)
plt.ioff() # print predictions from test data
test_output, _ = cnn(test_x[:])
pred_y = torch.max(test_output, )[].data.numpy()
print(pred_y, 'prediction number')
print(test_y[:].numpy(), 'real number')
去掉可视化进行代码简化
import os
# third-party library
import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import matplotlib.pyplot as plt EPOCH = # train the training data n times, to save time, we just train epoch
BATCH_SIZE =
LR = 0.001 # learning rate train_data = torchvision.datasets.MNIST(
root='./mnist/', #下载后的存放目录
train=True, # this is training data
transform=torchvision.transforms.ToTensor(), # 把数据压缩到0到1之间的numpy数据,如果原始数据是rgb数据(-)则变为黑白数据,并使numpy数据变为tensor数据 # torch.FloatTensor of shape (C x H x W) and normalize in the range [0.0, 1.0]
download=True#不存在该数据就设置为True进行下载,存在则改为False
) # plot one example
print(train_data.train_data.size()) # (, , ),六万图片
print(train_data.train_labels.size()) # (),六万标签
plt.imshow(train_data.train_data[].numpy(), cmap='gray')#展现第一个训练数据图片
plt.title('%i' % train_data.train_labels[])
plt.show() # Data Loader for easy mini-batch return in training, the image batch shape will be (, , , )
train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True) # pick samples to speed up testing
test_data = torchvision.datasets.MNIST(root='./mnist/', train=False)
test_x = torch.unsqueeze(test_data.test_data, dim=).type(torch.FloatTensor)[:]/. # shape from (, , ) to (, , , ), value in range(,)
test_y = test_data.test_labels[:] class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Sequential( # input shape (, , ),考虑batch是(batch,,,)
nn.Conv2d(
in_channels=, # input height
out_channels=, # n_filters
kernel_size=, # filter size
stride=, # filter movement/step
padding=, # if want same width and length of this image after Conv2d, padding=(kernel_size-)/ if stride=
), # output shape (, , )
nn.ReLU(), # activation
nn.MaxPool2d(kernel_size=), # choose max value in 2x2 area, output shape (, , )
)
self.conv2 = nn.Sequential( # input shape (, , )
nn.Conv2d(, , , , ), # output shape (, , )
nn.ReLU(), # activation
nn.MaxPool2d(), # output shape (, , )
)
self.out = nn.Linear( * * , ) # fully connected layer, output classes def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = x.view(x.size(), -) # flatten the output of conv2 to (batch_size, * * ),只有tensor对象才可以使用x.size()
output = self.out(x)
return output, x # return x for visualization cnn = CNN()
#print(cnn) # net architecture optimizer = torch.optim.Adam(cnn.parameters(), lr=LR) # optimize all cnn parameters
loss_func = nn.CrossEntropyLoss() # the target label is not one-hotted # training and testing
for epoch in range(EPOCH):
for step, (b_x, b_y) in enumerate(train_loader): # gives batch data, normalize x when iterate train_loader output = cnn(b_x)[] # cnn output
loss = loss_func(output, b_y) # cross entropy loss
optimizer.zero_grad() # clear gradients for this training step
loss.backward() # backpropagation, compute gradients
optimizer.step() # apply gradients if step % == :
test_output = cnn(test_x)[]
print("----------------")
#print(test_output.shape) #*
#print(torch.max(test_output, )) #返回的每一行中最大值和其下标
pred_y = torch.max(test_output, )[].data.numpy() #返回的是每个样本对应0-9数字可能性最大的概率对应的下标
accuracy = float((pred_y == test_y.data.numpy()).astype(int).sum()) / float(test_y.size())
print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.numpy(), '| test accuracy: %.2f' % accuracy) # print predictions from test data
test_output, _ = cnn(test_x[:])
pred_y = torch.max(test_output, )[].data.numpy()
print(pred_y, 'prediction number')
print(test_y[:].numpy(), 'real number')
莫烦pytorch学习笔记(八)——卷积神经网络(手写数字识别实现)的更多相关文章
- TensorFlow 卷积神经网络手写数字识别数据集介绍
欢迎大家关注我们的网站和系列教程:http://www.tensorflownews.com/,学习更多的机器学习.深度学习的知识! 手写数字识别 接下来将会以 MNIST 数据集为例,使用卷积层和池 ...
- SVM学习笔记(二)----手写数字识别
引言 上一篇博客整理了一下SVM分类算法的基本理论问题,它分类的基本思想是利用最大间隔进行分类,处理非线性问题是通过核函数将特征向量映射到高维空间,从而变成线性可分的,但是运算却是在低维空间运行的.考 ...
- 深度学习-使用cuda加速卷积神经网络-手写数字识别准确率99.7%
源码和运行结果 cuda:https://github.com/zhxfl/CUDA-CNN C语言版本参考自:http://eric-yuan.me/ 针对著名手写数字识别的库mnist,准确率是9 ...
- 深度学习(一):Python神经网络——手写数字识别
声明:本文章为阅读书籍<Python神经网络编程>而来,代码与书中略有差异,书籍封面: 源码 若要本地运行,请更改源码中图片与数据集的位置,环境为 Python3.6x. 1 import ...
- 基于Numpy的神经网络+手写数字识别
基于Numpy的神经网络+手写数字识别 本文代码来自Tariq Rashid所著<Python神经网络编程> 代码分为三个部分,框架如下所示: # neural network class ...
- 深度学习之PyTorch实战(3)——实战手写数字识别
上一节,我们已经学会了基于PyTorch深度学习框架高效,快捷的搭建一个神经网络,并对模型进行训练和对参数进行优化的方法,接下来让我们牛刀小试,基于PyTorch框架使用神经网络来解决一个关于手写数字 ...
- Pytorch入门——手把手教你MNIST手写数字识别
MNIST手写数字识别教程 要开始带组内的小朋友了,特意出一个Pytorch教程来指导一下 [!] 这里是实战教程,默认读者已经学会了部分深度学习原理,若有不懂的地方可以先停下来查查资料 目录 MNI ...
- 5 TensorFlow入门笔记之RNN实现手写数字识别
------------------------------------ 写在开头:此文参照莫烦python教程(墙裂推荐!!!) ---------------------------------- ...
- 【深度学习系列】PaddlePaddle之手写数字识别
上周在搜索关于深度学习分布式运行方式的资料时,无意间搜到了paddlepaddle,发现这个框架的分布式训练方案做的还挺不错的,想跟大家分享一下.不过呢,这块内容太复杂了,所以就简单的介绍一下padd ...
随机推荐
- 为什么 TCP 建立连接是三次握手,关闭连接确是四次挥手呢?
Java技术栈 www.javastack.cn 优秀的Java技术公众号 作者:小书go https://blog.csdn.net/qzcsu/article/details/72861891 背 ...
- 【POJ】1182 食物链
这是<挑战设计程序竞赛>中的例题. 题目链接:http://poj.org/problem?id=1182 题意:中文题面.不赘述. 题解: 代码: //带权并查集 #include< ...
- 【2018ACM/ICPC网络赛】焦作赛区
A Magic Mirror 题目链接:https://nanti.jisuanke.com/t/31710 题意:输入字符串,如果是“Jessy”就输出“Good Guy!",否则输出“D ...
- Permission denied: user=root, access=WRITE, inode="/":hdfs:supergroup:drwxr-xr-x
通过手动安装CDH没权限 [root@slave1 ~]# groupadd supergroup[root@slave1 ~]# hadoop fs -mkdir /tao3^C[root@slav ...
- The linux command 之 扩展
echo * " * "字符意味着匹配文件名中的任意字符,shell会在执行echo命令之前把*扩展成其他内容. 一.路径扩展(pathname Expansion) 通过使用通配 ...
- eclipse导出说明文档
选中项目--右键--Export--Java--Javadoc—Finish 1.为程序添加文档注释 2.选中项目--右键Export--Java--Javadoc--next, 3.next--在V ...
- PyQt6的在线安装与环境配置
https://www.jianshu.com/p/185e277e0058 一,安装好Python,Pycharm 二,安装或更新pip C:\> python -m pip install ...
- Java基本语法.part02
变量 变量的概念: 内存中的一个存储区域 该区域有自己的名称(变量名)和类型(数据类型) Java中每个变量必须先声明,后使用 该区域的数据可以在同一类型范围内不断变化 使用变量注意: 变量的作用域: ...
- PHP MVC运用
php中的MVC模式运用 首先我来举个例子: 一个简单的文章显示系统 简单期间,我们假定这个文章系统是只读的,也就是说这个例子将不涉及文章的发布,现在开始了. 由于只涉及数据库的读取,所以我定义了两个 ...
- 17个方法防止dedeCMS织梦网站被黑挂木马
dede织梦cms系统的程序存在漏洞,黑客攻击方法层出不穷,导致网站经常被黑,被百度安全中心等拦截,影响排名和流量,让站长非常头疼,下面总结一些防止dede织梦cms系统被攻击设置的方法,可有效的防止 ...