奉献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模型之 ...
随机推荐
- 【洛谷P3957】跳房子
题目大意:给定一个数轴和 N 个点,点有点权,现从 0 位置出发,初始时每次只能走 d 的距离,可以在数轴上任意位置停下,此时,会得到一个点权和.现允许支付 x 的费用,使得每次可以走的距离为一个范围 ...
- 常用ASCII码表
- 各种环境下搭建ruby on rails开发环境
win10上搭建raby on rails环境: 步骤如下 1.安装ruby (我选择的版本是ruby 2.2.3p173) 2.安装rails gem 在这之前建议先把gem的源换成淘宝的源,速度快 ...
- JavaScript 函数调用时带括号和不带括号的区别
function countBodyChildren(){ var body_element = document.getElementsByTagName("body")[0]; ...
- 【leetcode】1253. Reconstruct a 2-Row Binary Matrix
题目如下: Given the following details of a matrix with n columns and 2 rows : The matrix is a binary mat ...
- Log4net日志文件自动按月份存放和日志独占问题的解决
让log4net日志文件自动按月份存放 log4net日志文件的作用还真不小,可以保存管理员.用户对数据库的任何操作,保存管理员和用户的登录记录,分析系统运行错误,所以不舍得随便将日志文件Delete ...
- poj 2187 Beauty Contest 凸包模板+求最远点对
题目链接 题意:给你n个点的坐标,n<=50000,求最远点对 #include <iostream> #include <cstdio> #include <cs ...
- scala基础-1
函数式编程 并行编程 多核计算.云计算 引用透明,给值确定,结果也确定 数据类型 三种变量修饰符 val 定义immutable variable var 定义mutable va ...
- GC类型以及不同类型GC的搭配 1
jvm内存分配,以及gc算法在上两篇博客中已经有所介绍.接下来我们重点分析不同gc器的特点和他们的搭配使用(并非任何一种新生代GC策略都可以和另一种年老代GC策略进行配合工作)
- Override和Overload的含义与区别
overload是重载,重载是一种参数多态机制,即代码通过参数的类型或个数不同而实现的多态机制. 是一种静态的绑定机制(在编译时已经知道具体执行的是哪个代码段). override是重写,重写是一种 ...