奉献pytorch 搭建 CNN 卷积神经网络训练图像识别的模型,配合numpy 和matplotlib 一起使用调用 cuda GPU进行加速训练
1、Torch构建简单的模型
# coding:utf-8
import torch class Net(torch.nn.Module):
def __init__(self,img_rgb=3,img_size=32,img_class=13):
super(Net, self).__init__()
self.conv1 = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=img_rgb, out_channels=img_size, kernel_size=3, stride=1,padding= 1), #
torch.nn.ReLU(),
torch.nn.MaxPool2d(2),
# torch.nn.Dropout(0.5)
)
self.conv2 = torch.nn.Sequential(
torch.nn.Conv2d(28, 64, 3, 1, 1),
torch.nn.ReLU(),
torch.nn.MaxPool2d(2)
)
self.conv3 = torch.nn.Sequential(
torch.nn.Conv2d(64, 64, 3, 1, 1),
torch.nn.ReLU(),
torch.nn.MaxPool2d(2)
)
self.dense = torch.nn.Sequential(
torch.nn.Linear(64 * 3 * 3, 128),
torch.nn.ReLU(),
torch.nn.Linear(128, img_class)
) def forward(self, x):
conv1_out = self.conv1(x)
conv2_out = self.conv2(conv1_out)
conv3_out = self.conv3(conv2_out)
res = conv3_out.view(conv3_out.size(0), -1)
out = self.dense(res)
return out CUDA = torch.cuda.is_available() model = Net(1,28,13)
print(model) optimizer = torch.optim.Adam(model.parameters())
loss_func = torch.nn.MultiLabelSoftMarginLoss()#nn.CrossEntropyLoss() if CUDA:
model.cuda() def batch_training_data(x_train,y_train,batch_size,i):
n = len(x_train)
left_limit = batch_size*i
right_limit = left_limit+batch_size
if n>=right_limit:
return x_train[left_limit:right_limit,:,:,:],y_train[left_limit:right_limit,:]
else:
return x_train[left_limit:, :, :, :], y_train[left_limit:, :]
2、奉献训练过程的代码
# coding:utf-8
import time
import os
import torch
import numpy as np
from data_processing import get_DS
from CNN_nework_model import cnn_face_discern_model
from torch.autograd import Variable
from use_torch_creation_model import optimizer, model, loss_func, batch_training_data,CUDA
from sklearn.metrics import accuracy_score os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' st = time.time()
# 获取训练集与测试集以 8:2 分割
x_,y_,y_true,label = get_DS() label_number = len(label) x_train,y_train = x_[:960,:,:,:].reshape((960,1,28,28)),y_[:960,:] x_test,y_test = x_[960:,:,:,:].reshape((340,1,28,28)),y_[960:,:] y_test_label = y_true[960:] print(time.time() - st)
print(x_train.shape,x_test.shape) batch_size = 100
n = int(len(x_train)/batch_size)+1 for epoch in range(100):
global loss
for batch in range(n):
x_training,y_training = batch_training_data(x_train,y_train,batch_size,batch)
batch_x,batch_y = Variable(torch.from_numpy(x_training)).float(),Variable(torch.from_numpy(y_training)).float()
if CUDA:
batch_x=batch_x.cuda()
batch_y=batch_y.cuda() out = model(batch_x)
loss = loss_func(out, batch_y) optimizer.zero_grad()
loss.backward()
optimizer.step()
# 测试精确度
if epoch%9==0:
global x_test_tst
if CUDA:
x_test_tst = Variable(torch.from_numpy(x_test)).float().cuda()
y_pred = model(x_test_tst) y_predict = np.argmax(y_pred.cpu().data.numpy(),axis=1) acc = accuracy_score(y_test_label,y_predict) print("loss={} aucc={}".format(loss.cpu().data.numpy(),acc))
3、总结
通过博主通过TensorFlow、keras、pytorch进行训练同样的模型同样的图像数据,结果发现,pyTorch快了很多倍,特别是在导入模型的时候比TensorFlow快了很多。合适部署接口和集成在项目中。
奉献pytorch 搭建 CNN 卷积神经网络训练图像识别的模型,配合numpy 和matplotlib 一起使用调用 cuda GPU进行加速训练的更多相关文章
- pytorch 8 CNN 卷积神经网络
# library # standard library import os # third-party library import torch import torch.nn as nn impo ...
- 用Keras搭建神经网络 简单模版(三)—— CNN 卷积神经网络(手写数字图片识别)
# -*- coding: utf-8 -*- import numpy as np np.random.seed(1337) #for reproducibility再现性 from keras.d ...
- Keras(四)CNN 卷积神经网络 RNN 循环神经网络 原理及实例
CNN 卷积神经网络 卷积 池化 https://www.cnblogs.com/peng8098/p/nlp_16.html 中有介绍 以数据集MNIST构建一个卷积神经网路 from keras. ...
- Deep Learning模型之:CNN卷积神经网络(一)深度解析CNN
http://m.blog.csdn.net/blog/wu010555688/24487301 本文整理了网上几位大牛的博客,详细地讲解了CNN的基础结构与核心思想,欢迎交流. [1]Deep le ...
- [转]Theano下用CNN(卷积神经网络)做车牌中文字符OCR
Theano下用CNN(卷积神经网络)做车牌中文字符OCR 原文地址:http://m.blog.csdn.net/article/details?id=50989742 之前时间一直在看 Micha ...
- Deep Learning论文笔记之(四)CNN卷积神经网络推导和实现(转)
Deep Learning论文笔记之(四)CNN卷积神经网络推导和实现 zouxy09@qq.com http://blog.csdn.net/zouxy09 自己平时看了一些论文, ...
- CNN(卷积神经网络)、RNN(循环神经网络)、DNN(深度神经网络)的内部网络结构有什么区别?
https://www.zhihu.com/question/34681168 CNN(卷积神经网络).RNN(循环神经网络).DNN(深度神经网络)的内部网络结构有什么区别?修改 CNN(卷积神经网 ...
- day-16 CNN卷积神经网络算法之Max pooling池化操作学习
利用CNN卷积神经网络进行训练时,进行完卷积运算,还需要接着进行Max pooling池化操作,目的是在尽量不丢失图像特征前期下,对图像进行downsampling. 首先看下max pooling的 ...
- cnn(卷积神经网络)比较系统的讲解
本文整理了网上几位大牛的博客,详细地讲解了CNN的基础结构与核心思想,欢迎交流. [1]Deep learning简介 [2]Deep Learning训练过程 [3]Deep Learning模型之 ...
随机推荐
- P2197 【模板】nim游戏
博弈初心者... 学习地址luogu上可以找到.关于比较好的证明地址放在了地址页里了.这里不再赘述. 大概感觉还是所谓先手必胜就是面对当前局面一定可以采取一种策略,然后后手无论再怎么做,先手都可以“控 ...
- k8spod生命周期
pod对象自从创建开始至终止退出的时间范围称为生命周期,在这段时间中,pod会处于多种不同的状态,并执行一些操作:其中,创建主容器为必须的操作,其他可选的操作还包括运行初始化容器(init conta ...
- sed基础语法
sed 太强大了 参考博客如下:https://www.cnblogs.com/ctaixw/p/5860221.html sed: Stream Editor文本流编辑,sed是一个“非交互式的”面 ...
- LOJ-6284-数列分块入门8
链接: https://loj.ac/problem/6284 题意: 给出一个长为 的数列,以及 个操作,操作涉及区间询问等于一个数 的元素,并将这个区间的所有元素改为 . 思路: 维护一个分块是否 ...
- JSP中的四种作用域?
page.request.session和application,具体如下: ①page 代表与一个页面相关的对象和属性. ②request 代表与Web客户机发出的一个请求相关的对象和属性.一个请求 ...
- Python实现PDF文件截取
python3截取PDF文件中的一部分. from PyPDF2 import PdfFileWriter, PdfFileReader # 开始页 start_page = 0 # 截止页 end_ ...
- electron-vue 升级 从2.x升级到4.x的坑
子窗口 2.x modal为true let messageRightMenu = new BrowserWindow({ // height: 170, // width: 70, useConte ...
- 2018 计蒜之道 初赛 第五场 A 贝壳找房搬家
贝壳找房换了一个全新的办公室,每位员工的物品都已经通过搬家公司打包成了箱子,搬进了新的办公室了,所有的箱子堆放在一间屋子里(这里所有的箱子都是相同的正方体),我们可以把这堆箱子看成一个 x*y*z 的 ...
- 16位masm汇编实现记忆化递归搜索斐波那契数列第50项
.model small ;递归fib,使用压缩BCD码,小端派 .data y1 byte 6 dup(0) y2 byte 6 dup(0) vis byte 1,1,1,61 dup(0) ;便 ...
- 【学习】mysql 时间戳与日期格式的相互转换
1.UNIX时间戳转换为日期用函数: FROM_UNIXTIME() ); 输出:2006-08-22 12:11:10 2.日期转换为UNIX时间戳用函数: UNIX_TIMESTAMP() Sel ...