利用Tensorflow实现卷积神经网络模型
首先看一下卷积神经网络模型,如下图:
卷积神经网络(CNN)由输入层、卷积层、激活函数、池化层、全连接层组成,即INPUT-CONV-RELU-POOL-FC
池化层:为了减少运算量和数据维度而设置的一种层。
代码如下:
- n_input = 784 # 28*28的灰度图
- n_output = 10 # 完成一个10分类的操作
- weights = {
- #'权重参数': tf.Variable(tf.高期([feature的H, feature的W, 当前feature连接的输入的深度, 最终想得到多少个特征图], 标准差=0.1)),
- 'wc1': tf.Variable(tf.random_normal([3, 3, 1, 64], stddev=0.1)),
- 'wc2': tf.Variable(tf.random_normal([3, 3, 64, 128], stddev=0.1)),
- #'全连接层参数': tf.Variable(tf.高斯([特征图H*特征图W*深度, 最终想得到多少个特征图], 标准差=0.1)),
- 'wd1': tf.Variable(tf.random_normal([7*7*128, 1024], stddev=0.1)),
- 'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1))
- }
- biases = {
- #'偏置参数': tf.Variable(tf.高斯([第1层有多少个偏置项], 标准差=0.1)),
- 'bc1': tf.Variable(tf.random_normal([64], stddev=0.1)),
- 'bc2': tf.Variable(tf.random_normal([128], stddev=0.1)),
- 'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)),
- 'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1))
- }
- #卷积神经网络
- def conv_basic(_input, _w, _b, _keepratio):
- #将输入数据转化成一个四维的[n, h, w, c]tensorflow格式数据
- #_input_r = tf.将输入数据转化成tensorflow格式(输入, shape=[batch_size大小, H, W, 深度])
- _input_r = tf.reshape(_input, shape=[-1, 28, 28, 1])
- #第1层卷积
- #_conv1 = tf.nn.卷积(输入, 权重参数, 步长=[batch_size大小, H, W, 深度], padding='建议选择SAME')
- _conv1 = tf.nn.conv2d(_input_r, _w['wc1'], strides=[1, 1, 1, 1], padding='SAME')
- #_conv1 = tf.nn.非线性激活函数(tf.nn.加法(_conv1, _b['bc1']))
- _conv1 = tf.nn.relu(tf.nn.bias_add(_conv1, _b['bc1']))
- #第1层池化
- #_pool1 = tf.nn.池化函数(_conv1, 指定池化窗口的大小=[batch_size大小, H, W, 深度], strides=[1, 2, 2, 1], padding='SAME')
- _pool1 = tf.nn.max_pool(_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
- #随机杀死一些节点,不让所有神经元都加入到训练中
- #_pool_dr1 = tf.nn.dropout(_pool1, 保留比例)
- _pool_dr1 = tf.nn.dropout(_pool1, _keepratio)
- #第2层卷积
- _conv2 = tf.nn.conv2d(_pool_dr1, _w['wc2'], strides=[1, 1, 1, 1], padding='SAME')
- _conv2 = tf.nn.relu(tf.nn.bias_add(_conv2, _b['bc2']))
- _pool2 = tf.nn.max_pool(_conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
- _pool_dr2 = tf.nn.dropout(_pool2, _keepratio)
- #全连接层
- #转化成tensorflow格式
- _dense1 = tf.reshape(_pool_dr2, [-1, _w['wd1'].get_shape().as_list()[0]])
- #第1层全连接层
- _fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1']))
- _fc_dr1 = tf.nn.dropout(_fc1, _keepratio)
- #第2层全连接层
- _out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2'])
- #返回值
- out = { 'input_r': _input_r, 'conv1': _conv1, 'pool1': _pool1, 'pool1_dr1': _pool_dr1,
- 'conv2': _conv2, 'pool2': _pool2, 'pool_dr2': _pool_dr2, 'dense1': _dense1,
- 'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out
- }
- return out
- print ("CNN READY")
- #设置损失函数&优化器(代码说明:略 请看前面文档)
- learning_rate = 0.001
- x = tf.placeholder("float", [None, nsteps, diminput])
- y = tf.placeholder("float", [None, dimoutput])
- myrnn = _RNN(x, weights, biases, nsteps, 'basic')
- pred = myrnn['O']
- cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
- optm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) # Adam Optimizer
- accr = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(pred,1), tf.argmax(y,1)), tf.float32))
- init = tf.global_variables_initializer()
- print ("Network Ready!")
- #训练(代码说明:略 请看前面文档)
- training_epochs = 5
- batch_size = 16
- display_step = 1
- sess = tf.Session()
- sess.run(init)
- print ("Start optimization")
- for epoch in range(training_epochs):
- avg_cost = 0.
- #total_batch = int(mnist.train.num_examples/batch_size)
- total_batch = 100
- # Loop over all batches
- for i in range(total_batch):
- batch_xs, batch_ys = mnist.train.next_batch(batch_size)
- batch_xs = batch_xs.reshape((batch_size, nsteps, diminput))
- # Fit training using batch data
- feeds = {x: batch_xs, y: batch_ys}
- sess.run(optm, feed_dict=feeds)
- # Compute average loss
- avg_cost += sess.run(cost, feed_dict=feeds)/total_batch
- # Display logs per epoch step
- if epoch % display_step == 0:
- print ("Epoch: %03d/%03d cost: %.9f" % (epoch, training_epochs, avg_cost))
- feeds = {x: batch_xs, y: batch_ys}
- train_acc = sess.run(accr, feed_dict=feeds)
- print (" Training accuracy: %.3f" % (train_acc))
- testimgs = testimgs.reshape((ntest, nsteps, diminput))
- feeds = {x: testimgs, y: testlabels, istate: np.zeros((ntest, 2*dimhidden))}
- test_acc = sess.run(accr, feed_dict=feeds)
- print (" Test accuracy: %.3f" % (test_acc))
- print ("Optimization Finished.")
利用Tensorflow实现卷积神经网络模型的更多相关文章
- 手写数字识别 ----卷积神经网络模型官方案例注释(基于Tensorflow,Python)
# 手写数字识别 ----卷积神经网络模型 import os import tensorflow as tf #部分注释来源于 # http://www.cnblogs.com/rgvb178/p/ ...
- CNN-1: LeNet-5 卷积神经网络模型
1.LeNet-5模型简介 LeNet-5 模型是 Yann LeCun 教授于 1998 年在论文 Gradient-based learning applied to document ...
- 使用PyTorch简单实现卷积神经网络模型
这里我们会用 Python 实现三个简单的卷积神经网络模型:LeNet .AlexNet .VGGNet,首先我们需要了解三大基础数据集:MNIST 数据集.Cifar 数据集和 ImageNet 数 ...
- 【TensorFlow/简单网络】MNIST数据集-softmax、全连接神经网络,卷积神经网络模型
初学tensorflow,参考了以下几篇博客: soft模型 tensorflow构建全连接神经网络 tensorflow构建卷积神经网络 tensorflow构建卷积神经网络 tensorflow构 ...
- CNN-2: AlexNet 卷积神经网络模型
1.AlexNet 模型简介 由于受到计算机性能的影响,虽然LeNet在图像分类中取得了较好的成绩,但是并没有引起很多的关注. 知道2012年,Alex等人提出的AlexNet网络在ImageNet大 ...
- CNN-3: VGGNet 卷积神经网络模型
1.VGGNet 模型简介 VGG Net由牛津大学的视觉几何组(Visual Geometry Group)和 Google DeepMind公司的研究员一起研发的的深度卷积神经网络,在 ILSVR ...
- CNN-4: GoogLeNet 卷积神经网络模型
1.GoogLeNet 模型简介 GoogLeNet 是2014年Christian Szegedy提出的一种全新的深度学习结构,该模型获得了ImageNet挑战赛的冠军. 2.GoogLeNet 模 ...
- caffe中LetNet-5卷积神经网络模型文件lenet.prototxt理解
caffe在 .\examples\mnist文件夹下有一个 lenet.prototxt文件,这个文件定义了一个广义的LetNet-5模型,对这个模型文件逐段分解一下. name: "Le ...
- 吴裕雄--天生自然python Google深度学习框架:经典卷积神经网络模型
import tensorflow as tf INPUT_NODE = 784 OUTPUT_NODE = 10 IMAGE_SIZE = 28 NUM_CHANNELS = 1 NUM_LABEL ...
随机推荐
- nodejs抓取页面内容,并分析有无某些内容的js文件
nodejs获取网页内容绑定data事件,获取到的数据会分几次相应,如果想全局内容匹配,需要等待请求结束,在end结束事件里把累积起来的全局数据进行操作! 举个例子,比如要在页面中找有没有www.ba ...
- [Android实例] Android Studio插件-自动根据布局生成Activity等代码1.4 (开源)(申明:来源于网络)
[Android实例] Android Studio插件-自动根据布局生成Activity等代码1.4 (开源)(申明:来源于网络) 地址:http://www.eoeandroid.com/thre ...
- MySQL设置只读模式
MySQL设置了主从复制,为保证数据一致性需要在从库设置只读状态 查看默认读写状态 show global variables like "%read_only%"; 设置只读 # ...
- hdparm命令(转)
转自:http://man.linuxde.net/hdparm hdparm命令提供了一个命令行的接口用于读取和设置IDE或SCSI硬盘参数. 语法 hdparm(选项)(参数) 选项 -a< ...
- F#周报2018年第48期
新闻 F#2018年圣诞日历 Mac上的Visual Studio 2017新版本7.7 Rider 2018.3将引入远程调试功能 Visual Studio 2017新版本15.9.3 视频及幻灯 ...
- 动态环境下的slam问题如何解决?
作者:颜沁睿链接:https://www.zhihu.com/question/47817909/answer/107775045来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注 ...
- ES6 import
ES6标准发布后,module成为标准,标准的使用是以export指令导出接口,以import引入模块,但是在我们一贯的node模块中,我们采用的是CommonJS规范,使用require引入模块,使 ...
- 网络层block,delegate之优劣分析
正常情况下, block 缺点: 1.block很难追踪,难以维护 2.block会延长先关对象的生命周期 block会给内部所有的对象引用计数+1, 一方面会带来潜在的循环引用(retain cyc ...
- 快速排序javascript实现
快速排序基本思想: 以升序为例 数组arr,数组个数n; 1.选取一个待排序的元素.一般选第一个位置作为基准值temp=arr[0]. 2.选取带排序数组的两端元素的位置作为哨兵的位置,左端为哨兵i, ...
- php之二叉树
二叉树的特点: ①.每个节点最多有两个子树,所以二叉树中不存在度大于2的节点.注意不是只有两个子树,最多有两个子树,没有子树或者只有一颗子树都是可以的. ②左子树和右子树是有顺序的. ③即使树中只有一 ...