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进行加速训练的更多相关文章

  1. pytorch 8 CNN 卷积神经网络

    # library # standard library import os # third-party library import torch import torch.nn as nn impo ...

  2. 用Keras搭建神经网络 简单模版(三)—— CNN 卷积神经网络(手写数字图片识别)

    # -*- coding: utf-8 -*- import numpy as np np.random.seed(1337) #for reproducibility再现性 from keras.d ...

  3. Keras(四)CNN 卷积神经网络 RNN 循环神经网络 原理及实例

    CNN 卷积神经网络 卷积 池化 https://www.cnblogs.com/peng8098/p/nlp_16.html 中有介绍 以数据集MNIST构建一个卷积神经网路 from keras. ...

  4. Deep Learning模型之:CNN卷积神经网络(一)深度解析CNN

    http://m.blog.csdn.net/blog/wu010555688/24487301 本文整理了网上几位大牛的博客,详细地讲解了CNN的基础结构与核心思想,欢迎交流. [1]Deep le ...

  5. [转]Theano下用CNN(卷积神经网络)做车牌中文字符OCR

    Theano下用CNN(卷积神经网络)做车牌中文字符OCR 原文地址:http://m.blog.csdn.net/article/details?id=50989742 之前时间一直在看 Micha ...

  6. Deep Learning论文笔记之(四)CNN卷积神经网络推导和实现(转)

    Deep Learning论文笔记之(四)CNN卷积神经网络推导和实现 zouxy09@qq.com http://blog.csdn.net/zouxy09          自己平时看了一些论文, ...

  7. CNN(卷积神经网络)、RNN(循环神经网络)、DNN(深度神经网络)的内部网络结构有什么区别?

    https://www.zhihu.com/question/34681168 CNN(卷积神经网络).RNN(循环神经网络).DNN(深度神经网络)的内部网络结构有什么区别?修改 CNN(卷积神经网 ...

  8. day-16 CNN卷积神经网络算法之Max pooling池化操作学习

    利用CNN卷积神经网络进行训练时,进行完卷积运算,还需要接着进行Max pooling池化操作,目的是在尽量不丢失图像特征前期下,对图像进行downsampling. 首先看下max pooling的 ...

  9. cnn(卷积神经网络)比较系统的讲解

    本文整理了网上几位大牛的博客,详细地讲解了CNN的基础结构与核心思想,欢迎交流. [1]Deep learning简介 [2]Deep Learning训练过程 [3]Deep Learning模型之 ...

随机推荐

  1. VS开发框架DevExtreme v19.1全解析!Windows资源管理器UX值得拥有

    行业领先的.NET界面控件DevExpress 正式发布了v19.1版本,本文将以系列文章的方式为大家介绍DevExtreme Complete Subscription v19.1中全新发布的文件管 ...

  2. 用Python实现简单购物车

    作业二:简单购物车# 实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,# 如果输入为空或其他非法输入则要求用户重新输入 shopping_list = [] w ...

  3. shell中条件判断if中的-z到-d

    shell中条件判断if中的-z到-d的意思 [ -a FILE ] 如果 FILE 存在则为真. [ -b FILE ] 如果 FILE 存在且是一个块特殊文件则为真.[ -c FILE ] 如果 ...

  4. 赋值语句C++(面宝P29)

    ; void main(){ int i=i; } 解析:main里面的i从声明的那一刻就是可见的了,所以main里的i不是1,而是一个未定义的值. 这段代码ctrl+F7编译能通过(有警告如下) c ...

  5. Python 模块Ⅲ

    globals() 和 locals() 函数 根据调用地方的不同,globals() 和 locals() 函数可被用来返回全局和局部命名空间里的名字. 如果在函数内部调用 locals(),返回的 ...

  6. selenium环境搭建:Error: could not find java.dll 报错问题

    搭建java环境,参照其他的安装步骤,搭建即可. 问题:出现如下报错信息. Error: could not find java.dll Error: Could not find Java SE R ...

  7. json的值键对,对象,数组,逻辑值

    详细说一下有关json的相关知识: ㈠json与xml的异同 ★与 XML 相同之处 ⑴JSON 是纯文本 ⑵JSON 具有"自我描述性"(人类可读) ⑶JSON 具有层级结构(值 ...

  8. JS中对小数取整的函数,向上(下),四舍五入取整

    1.丢弃小数部分,保留整数部分 js:parseInt(7/2) 2.向上取整,有小数就整数部分加1 js: Math.ceil(7/2) 3,四舍五入. js: Math.round(7/2) 4, ...

  9. CF G. Indie Album AC自动机+fail树+线段树

    这个套路挺有意思的. 把 $trie$ 和 $fail$ 树都建出来,然后一起跑一跑就好了~ #include <queue> #include <cstdio> #inclu ...

  10. 洛谷 P2820 局域网x

    题目背景 某个局域网内有n(n<=100)台计算机,由于搭建局域网时工作人员的疏忽,现在局域网内的连接形成了回路,我们知道如果局域网形成回路那么数据将不停的在回路内传输,造成网络卡的现象.因为连 ...