莫烦视频网址

这个代码实现了预测和可视化

 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学习笔记(八)——卷积神经网络(手写数字识别实现)的更多相关文章

  1. TensorFlow 卷积神经网络手写数字识别数据集介绍

    欢迎大家关注我们的网站和系列教程:http://www.tensorflownews.com/,学习更多的机器学习.深度学习的知识! 手写数字识别 接下来将会以 MNIST 数据集为例,使用卷积层和池 ...

  2. SVM学习笔记(二)----手写数字识别

    引言 上一篇博客整理了一下SVM分类算法的基本理论问题,它分类的基本思想是利用最大间隔进行分类,处理非线性问题是通过核函数将特征向量映射到高维空间,从而变成线性可分的,但是运算却是在低维空间运行的.考 ...

  3. 深度学习-使用cuda加速卷积神经网络-手写数字识别准确率99.7%

    源码和运行结果 cuda:https://github.com/zhxfl/CUDA-CNN C语言版本参考自:http://eric-yuan.me/ 针对著名手写数字识别的库mnist,准确率是9 ...

  4. 深度学习(一):Python神经网络——手写数字识别

    声明:本文章为阅读书籍<Python神经网络编程>而来,代码与书中略有差异,书籍封面: 源码 若要本地运行,请更改源码中图片与数据集的位置,环境为 Python3.6x. 1 import ...

  5. 基于Numpy的神经网络+手写数字识别

    基于Numpy的神经网络+手写数字识别 本文代码来自Tariq Rashid所著<Python神经网络编程> 代码分为三个部分,框架如下所示: # neural network class ...

  6. 深度学习之PyTorch实战(3)——实战手写数字识别

    上一节,我们已经学会了基于PyTorch深度学习框架高效,快捷的搭建一个神经网络,并对模型进行训练和对参数进行优化的方法,接下来让我们牛刀小试,基于PyTorch框架使用神经网络来解决一个关于手写数字 ...

  7. Pytorch入门——手把手教你MNIST手写数字识别

    MNIST手写数字识别教程 要开始带组内的小朋友了,特意出一个Pytorch教程来指导一下 [!] 这里是实战教程,默认读者已经学会了部分深度学习原理,若有不懂的地方可以先停下来查查资料 目录 MNI ...

  8. 5 TensorFlow入门笔记之RNN实现手写数字识别

    ------------------------------------ 写在开头:此文参照莫烦python教程(墙裂推荐!!!) ---------------------------------- ...

  9. 【深度学习系列】PaddlePaddle之手写数字识别

    上周在搜索关于深度学习分布式运行方式的资料时,无意间搜到了paddlepaddle,发现这个框架的分布式训练方案做的还挺不错的,想跟大家分享一下.不过呢,这块内容太复杂了,所以就简单的介绍一下padd ...

随机推荐

  1. windows下安装sass,以及常见错误和解决办法

    简介: sass依赖于ruby环境,安装sass之前得先装ruby. 1.安装ruby 1.1.下载地址:http://rubyinstaller.org/downloads 1.2.注意事项:安装时 ...

  2. 好文 | MySQL 索引B+树原理,以及建索引的几大原则

    Java技术栈 www.javastack.cn 优秀的Java技术公众号 来源:小宝鸽 blog.csdn.net/u013142781/article/details/51706790 MySQL ...

  3. C 自己实现strcpy,strcmp,strlen,strcat等函数

    // mystrlen() 测试字符长度方法 int mystrlen(char *str) { int cnt = 0; char *p= str; while(*p++ != '\0') { cn ...

  4. vc面试题目

    class B { public: B() { cout << "default constructor" << endl; } ~B() { cout & ...

  5. COGS2355 【HZOI2015】 有标号的DAG计数 II

    题面 题目描述 给定一正整数n,对n个点有标号的有向无环图(可以不连通)进行计数,输出答案mod 998244353的结果 输入格式 一个正整数n 输出格式 一个数,表示答案 样例输入 3 样例输出 ...

  6. 「题解」:$Game$

    问题 B: $Game$ 时间限制: 1 Sec  内存限制: 256 MB 题面 题面谢绝公开. 题解 对于最初加入的每一个元素开桶记录出现次数. 然后记录一个前p个元素最大值. 先由先手玩家取走一 ...

  7. 1003CSP-S模拟测试赛后总结

    我是垃圾……我只会骗分. 拿到题目通读一遍,感觉T3(暴力)是个树剖+线段树. 刚学了树刨我这个兴奋啊.然而手懒决定最后再说. 对着T1一顿yyxjb码了个60pts的测试点分治就失去梦想了.(顺便围 ...

  8. 针对发送网络附件的java方法(使用Apache的jar包调用)

    1.先要在pom.xml文件中引入对应的jar包 <!--添加邮件的网络附件 start--> <dependency> <groupId>org.apache.c ...

  9. VC++ MFC文件的移动复制删除更名遍历操作

    1.判断文件是否存在 利用CFile类和CFileStatus类判断 CFileStatus filestatus; if (CFile::GetStatus(_T("d://softist ...

  10. (转)谈谈Android中的Rect类——奇葩的思维

    最近在工作中遇到了一些问题,总结下来就是Android中Rect这个类造成的.不得不说,不知道Android SDK的开发人员是怎么想的, 这个类设计的太奇葩了.首先介绍一下Rect类:Rect类主要 ...