莫烦视频网址

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

 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. Python3 From Zero——{最初的意识:008~初级实例演练}

    一.构显国际橡棋8x8棋盘 #!/usr/bin/env python3 #-*- coding:utf-8 -*- color_0="\033[41m \033[00m" col ...

  2. 分布式存储glusterfs

    什么是glusterfs? Glusterfs是一个开源分布式文件系统,具有强大的横向扩展能力,可支持数PB存储容量的数干客户端,通过网络互联成一个并行的网络文件系统.具有可扩展性.高性能.高可用性等 ...

  3. Python+Django+ansible playbook自动化运维项目实战✍✍✍

    Python+Django+ansible playbook自动化运维项目实战  整个课程都看完了,这个课程的分享可以往下看,下面有链接,之前做java开发也做了一些年头,也分享下自己看这个视频的感受 ...

  4. [eJOI2018]元素周期表

    题目 \((r_1,c_1),(r_2,c_1),(r_1,c_2)\)三个格子存在就说明\((r_2,c_2)\)存在,如果我们将\(r_1,c_2,c_1,r_2\)都看成一些点的话,那么这个关系 ...

  5. python接口自动化(接口基础)

    一.什么是接口? 前端负责展示和收集数据 后端负责处理数据,返回对应的结果 接口是前端与后端之间的桥梁,传递数据的通道 二.

  6. Navicat Premium_11.2.7 安装及破解,连接Oracle数据库

    下载Navicat Premium_11.2.7简体中文版, 安装 Navicat 11 for Windows 系列原版程序.Navicat | 下载 Navicat 14 天 Windows.Ma ...

  7. [JZOJ1904] 【2010集训队出题】拯救Protoss的故乡

    题目 题目大意 给你一个树形的网络,每条边从父亲流向儿子.根节点为原点,叶子节点流向汇点,容量为无穷大. 可以给一些边扩大容量,最多总共扩大\(m\)容量.每条边的容量有上限. 求扩大容量后最大的最大 ...

  8. http://wiki.ros.org/navigation/Tutorials/RobotSetup

    http://wiki.ros.org/navigation/Tutorials/RobotSetup

  9. Python中%r和%s的详解及区别_python_脚本之家

    Python中%r和%s的详解及区别_python_脚本之家 https://www.jb51.net/article/108589.htm

  10. centos一些故障解决方法

    1. vmware下虚拟机centos,root登录时候提示鉴定故障解决方法 - lippor - 博客园 https://www.cnblogs.com/lippor/p/5537931.html ...