奉献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模型之 ...
随机推荐
- 零拷贝的原理及Java实现
在谈论Kafka高性能时不得不提到零拷贝.Kafka通过采用零拷贝大大提供了应用性能,减少了内核和用户模式之间的上下文切换次数.那么什么是零拷贝,如何实现零拷贝呢? 什么是零拷贝 WIKI中对其有如下 ...
- javasctipt之DOM知识点
一:DOM节点 子节点:childNodes 父节点:parentNode offsetPrent 二:元素属性操作 方式一:xxx.style.xxx 方式二:xxx.style["xxx ...
- .net中[Serializable]序列化的应用
原文链接:https://blog.csdn.net/wanlong360599336/article/details/9222459 浅析.NET中的Serialization 摘要 本文简要介绍了 ...
- JavaScript 数组2—关联数组
㈠什么是关联数组 可以自定义下标名称的数组 ㈡为什么 索引数组中的数字下标没有明确的意义 ㈢何时 只希望每个元素都有专门的名称时 ㈣如何:2步 1)创建空数组 2)向空数组中添加新元素,并自定义下标名 ...
- BZOJ 3697: 采药人的路径 点分治
好久不做点分治的题了,正好在联赛之前抓紧复习一下. 先把边权为 $0$ 的置为 $-1$.定义几个状态:$f[dis][0/1],g[dis][0/1]$ 其中 $f$ 代表在当前遍历的子树内的答案. ...
- 【转载】使用 scikit-learn 进行特征选择
[转载]使用 scikit-learn 进行特征选择 Read more: http://bluewhale.cc/2016-11-25/use-scikit-learn-for-feature-se ...
- Java 8 - Stream Collectors分组的例子
1.分组依据,计数和排序 1.1按a分组List并显示它的总数. package com.mkyong.java8; import java.util.Arrays; import java.util ...
- auth 认证组件的补充
Django自带的用户认证 我们在开发一个网站的时候,无可避免的需要设计实现网站的用户系统.此时我们需要实现包括用户注册.用户登录.用户认证.注销.修改密码等功能,这还真是个麻烦的事情呢. Djang ...
- JVM----堆上为对象动态分配内存
jvm中内存划分: 如上图,一共分为五块,其中: 线程共享区域为: 1.java堆 2.方法区 线程私有区域为: 3.JVM栈 4.本地方法栈 5.程序计数器 java技术体 ...
- Android动态广播的注册与销毁
一个内部类:BroadcastReceiver的子类,并定义收到广播之后的操作: class LockScreenBroadcastReceiver extends BroadcastReceiver ...