首先看一下卷积神经网络模型,如下图:

卷积神经网络(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实现卷积神经网络模型的更多相关文章

  1. 手写数字识别 ----卷积神经网络模型官方案例注释(基于Tensorflow,Python)

    # 手写数字识别 ----卷积神经网络模型 import os import tensorflow as tf #部分注释来源于 # http://www.cnblogs.com/rgvb178/p/ ...

  2. CNN-1: LeNet-5 卷积神经网络模型

    1.LeNet-5模型简介 LeNet-5 模型是 Yann LeCun 教授于 1998 年在论文 Gradient-based learning applied to document      ...

  3. 使用PyTorch简单实现卷积神经网络模型

    这里我们会用 Python 实现三个简单的卷积神经网络模型:LeNet .AlexNet .VGGNet,首先我们需要了解三大基础数据集:MNIST 数据集.Cifar 数据集和 ImageNet 数 ...

  4. 【TensorFlow/简单网络】MNIST数据集-softmax、全连接神经网络,卷积神经网络模型

    初学tensorflow,参考了以下几篇博客: soft模型 tensorflow构建全连接神经网络 tensorflow构建卷积神经网络 tensorflow构建卷积神经网络 tensorflow构 ...

  5. CNN-2: AlexNet 卷积神经网络模型

    1.AlexNet 模型简介 由于受到计算机性能的影响,虽然LeNet在图像分类中取得了较好的成绩,但是并没有引起很多的关注. 知道2012年,Alex等人提出的AlexNet网络在ImageNet大 ...

  6. CNN-3: VGGNet 卷积神经网络模型

    1.VGGNet 模型简介 VGG Net由牛津大学的视觉几何组(Visual Geometry Group)和 Google DeepMind公司的研究员一起研发的的深度卷积神经网络,在 ILSVR ...

  7. CNN-4: GoogLeNet 卷积神经网络模型

    1.GoogLeNet 模型简介 GoogLeNet 是2014年Christian Szegedy提出的一种全新的深度学习结构,该模型获得了ImageNet挑战赛的冠军. 2.GoogLeNet 模 ...

  8. caffe中LetNet-5卷积神经网络模型文件lenet.prototxt理解

    caffe在 .\examples\mnist文件夹下有一个 lenet.prototxt文件,这个文件定义了一个广义的LetNet-5模型,对这个模型文件逐段分解一下. name: "Le ...

  9. 吴裕雄--天生自然python Google深度学习框架:经典卷积神经网络模型

    import tensorflow as tf INPUT_NODE = 784 OUTPUT_NODE = 10 IMAGE_SIZE = 28 NUM_CHANNELS = 1 NUM_LABEL ...

随机推荐

  1. Python数据结构———队列

    队列(Queue) 队列也是一系列有顺序的元素的集合,新元素的加入在队列的一端,叫做“队尾”(rear),已有元素的移除发生在队列的另一端,叫做“队首”(front),和栈不同的是,队列只能在队尾插入 ...

  2. pycharm平台下的Django教程(转)

    本文面向:有python基础,刚接触web框架的初学者. 环境:windows7   python3.5.1  pycharm专业版  Django 1.10版 pip3 一.Django简介 百度百 ...

  3. [No000014D]chrome console 调试 引入 jquery等外部库

    var importJs=document.createElement('script') //在页面新建一个script标签 importJs.setAttribute("type&quo ...

  4. windows hook 钩子

    windows  hook  钩子 场景: 1.打印机 Ctrl+P弹出支付窗口,付款成功后打印

  5. [daily] 使用左右对比查看diff 格式的文件

    如题: Given your references to Vim in the question, I'm not sure if this is the answer you want :) but ...

  6. 将DOS格式的shell脚本转为UNIX格式

    shell脚本是UNIX格式,在修改其中内容时,务必保持UNIX格式.UE编辑器打开时,会询问是否转为DOS格式,请点否.如果修改完成后,不能确认是否为DOS格式,可以使用UE文件菜单下的Conver ...

  7. PLSQL游标

    静态游标:结果集已经确实(静态定义)的游标.分为隐式和显式游标 隐式游标:所有DML语句为隐式游标,通过隐式游标属性可以获取SQL语句信息: 显式游标:用户显式声明的游标,即指定结果集.当查询返回结果 ...

  8. LeetCode 637 Average of Levels in Binary Tree 解题报告

    题目要求 Given a non-empty binary tree, return the average value of the nodes on each level in the form ...

  9. JVM java垃圾回收机制

    一.jvm简介 1.JVM内存运行时数据区的三个重要的地方 1.1.堆(heap):它是最大的一块区域,用于存放对象实例数组,是全局共享的. 1.2.栈(stack):全称为虚拟机栈,主要存储基本数据 ...

  10. 8.0-uC/OS-III单任务应用

    1.单任务应用 app.c文件: (1).APP_CFG.H 是用于配置的头文件.例如, APP_CFG.H 中包含的#define常量确定了任务优先级,堆栈大小,以及其他特性. BSP.H 是 BS ...