莫烦视频网址

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

 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. Codeforces 1163A - Eating Soup

    题目链接:http://codeforces.com/problemset/problem/1163/A 题意:n 只猫围成一圈,离开 m 只,最多剩下几组猫. 思路:当 n == m 即猫都离开时 ...

  2. Linux下rsync的安装及简单使用

    2018-09-25 15:39:04 一.RSYNC安装环境: centos6.5 iptables关闭和selinux为disabled 源码安装:到rsync官网下载rsync源码安装包,上传到 ...

  3. centos 7 设置IP地址

    先说下安装方式:我是采用的最小化安装 虚拟机软件:vmware 设置IP有两种情况,动态IP和静态IP,下面分别说明两种IP地址的设置方法 1.动态IP 条件:路由设置了动态分配IP地址(一般默认是动 ...

  4. sshpass批量分发ssh秘钥

    首先安装sshpass: yum -y install sshpass 单条命令: sshpass -p“password” ssh-copy-id -i /root/.ssh/id_rsa.pub ...

  5. 3.3_springBoot2.1.x检索之RestHighLevelClient方式

    1.版本依赖 注意对 transport client不了解先阅读官方文档: transport client(传送门) 这里需要版本匹配,如失败查看官网或百度. pom.xml <?xml v ...

  6. jsonArray转换成List

    从字符串String转换成List 字符串格式: String jsonstr = "{'studentsjson':[{'student':'张三'},{'student':'李四'}] ...

  7. drupal7 代码生成用户,并自动登录

    直接上代码 1. 生成用户(注册) $edit = [ "name" => "name", "pass" => "pa ...

  8. if else 和 swith效率比较

    读大话设计模式,开头的毛病代码用if else实现了计算器,说计算机做了三次无用功,优化后是用switch,那么switch为什么比if else效率高呢, 百度找了几个说是底层算法不一样,找了一个比 ...

  9. C# - Finalize 和 Dispose

    重要: https://www.cnblogs.com/Jessy/articles/2552839.html https://blog.csdn.net/daxia666/article/detai ...

  10. Windows netstat

    { 显示协议统计信息和当前 TCP/IP 网络连接. NETSTAT [-a] [-b] [-e] [-f] [-n] [-o] [-p proto] [-r] [-s] [-x] [-t] [int ...