卷积神经网络比神经网络稍微复杂一些,因为其多了一个卷积层(convolutional layer)和池化层(pooling layer)。

使用mnist数据集,n个数据,每个数据的像素为28*28*1=784。先让这些数据通过第一个卷积层,在这个卷积上指定一个3*3*1的feature,这个feature的个数设为64。接着经过一个池化层,让这个池化层的窗口为2*2。然后在经过一个卷积层,在这个卷积上指定一个3*3*64的feature,这个featurn的个数设置为128,。接着经过一个池化层,让这个池化层的窗口为2*2。让结果经过一个全连接层,这个全连接层大小设置为1024,在经过第二个全连接层,大小设置为10,进行分类。

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('data/', one_hot=True)
trainimg   = mnist.train.images
trainlabel = mnist.train.labels
testimg    = mnist.test.images
testlabel  = mnist.test.labels
print ("MNIST ready")

#像素点为784
n_input  = 784
#十分类
n_output = 10
#wc1,第一个卷积层参数,3*3*1,共有64个
#wc2,第二个卷积层参数,3*3*64,共有128个
#wd1,第一个全连接层参数,经过两个池化层被压缩到7*7
#wd2,第二个全连接层参数
weights  = {'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)),'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   = {'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))}

定义前向传播函数。先将输入数据预处理,变成tensorflow支持的四维图像;进行第一层的卷积层处理,调用conv2d函数;将卷积结果用激活函数进行处理(relu函数);将结果进行池化层处理,ksize代表窗口大小;将池化层的结果进行随机删除节点;进行第二层卷积和池化...;进行全连接层,先将数据进行reshape(此处为7*7*128);进行激活函数处理;得出结果。前向传播结束。

def conv_basic(_input, _w, _b, _keepratio):# INPUT_input_r = tf.reshape(_input, shape=[-1, 28, 28, 1])# CONV LAYER 1_conv1 = tf.nn.conv2d(_input_r, _w['wc1'], strides=[1, 1, 1, 1], padding='SAME')_conv1 = tf.nn.relu(tf.nn.bias_add(_conv1, _b['bc1']))_pool1 = tf.nn.max_pool(_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')_pool_dr1 = tf.nn.dropout(_pool1, _keepratio)# CONV LAYER 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)# VECTORIZE_dense1 = tf.reshape(_pool_dr2, [-1, _w['wd1'].get_shape().as_list()[0]])# FULLY CONNECTED LAYER 1_fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1']))_fc_dr1 = tf.nn.dropout(_fc1, _keepratio)# FULLY CONNECTED LAYER 2_out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2'])# RETURNout = { '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")

定义损失函数,定义优化器

x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_output])
keepratio = tf.placeholder(tf.float32)# FUNCTIONS

_pred = conv_basic(x, weights, biases, keepratio)['out']
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(_pred, y))
optm = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)
_corr = tf.equal(tf.argmax(_pred,1), tf.argmax(y,1))
accr = tf.reduce_mean(tf.cast(_corr, tf.float32))
init = tf.global_variables_initializer()# SAVER
save_step = 1
saver = tf.train.Saver(max_to_keep=3) print ("GRAPH READY")

进行迭代

do_train = 1
sess = tf.Session()
sess.run(init)training_epochs = 15
batch_size      = 16
display_step    = 1
if do_train == 1:for epoch in range(training_epochs):avg_cost = 0.total_batch = int(mnist.train.num_examples/batch_size)# Loop over all batchesfor i in range(total_batch):batch_xs, batch_ys = mnist.train.next_batch(batch_size)# Fit training using batch datasess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7})# Compute average lossavg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/total_batch# Display logs per epoch stepif epoch % display_step == 0: print ("Epoch: %03d/%03d cost: %.9f" % (epoch, training_epochs, avg_cost))train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})print (" Training accuracy: %.3f" % (train_acc))#test_acc = sess.run(accr, feed_dict={x: testimg, y: testlabel, keepratio:1.})#print (" Test accuracy: %.3f" % (test_acc))print ("OPTIMIZATION FINISHED")

转载于:https://www.cnblogs.com/xxp17457741/p/9480521.html

tensorflow学习笔记七----------卷积神经网络相关推荐

  1. 深度学习笔记:卷积神经网络的可视化--卷积核本征模式

    目录 1. 前言 2. 代码实验 2.1 加载模型 2.2 构造返回中间层激活输出的模型 2.3 目标函数 2.4 通过随机梯度上升最大化损失 2.5 生成滤波器模式可视化图像 2.6 将多维数组变换 ...

  2. 霹雳吧啦wz学习笔记1_卷积神经网络

    霹雳吧啦wz学习笔记1_卷积神经网络 全连接层: 全连接层就是由许许多多的神经元共同连接而得来的 卷积层: 卷积就是一个滑动窗口在我们的特征图上进行滑动并计算 卷积的目的:进行图像特征提取 卷积核的c ...

  3. [TensorFlow 学习笔记-04]卷积函数之tf.nn.conv2d

    [版权说明] TensorFlow 学习笔记参考: 李嘉璇 著 TensorFlow技术解析与实战 黄文坚 唐源 著 TensorFlow实战郑泽宇  顾思宇 著 TensorFlow实战Google ...

  4. 深度学习入门之PyTorch学习笔记:卷积神经网络

    深度学习入门之PyTorch学习笔记 绪论 1 深度学习介绍 2 深度学习框架 3 多层全连接网络 4 卷积神经网络 4.1 主要任务及起源 4.2 卷积神经网络的原理和结构 4.2.1 卷积层 1. ...

  5. 深度学习笔记:卷积神经网络的Tensorflow实现

    文章出处:深度学习笔记11:利用numpy搭建一个卷积神经网络 免费视频课程:Hellobi Live | 从数据分析师到机器学习(深度学习)工程师的进阶之路 在上一讲中,我们学习了如何利用 nump ...

  6. 吴恩达深度学习笔记- lesson4 卷积神经网络

    文章目录 Week 1 卷积神经网络基础 4.1.1 计算机视觉(Computer vision) 4.1.2 边缘检测示例(Edge detection example) 4.1.3 更多边缘检测内 ...

  7. 【TensorFlow实战笔记】卷积神经网络CNN实战-cifar10数据集(tensorboard可视化)

    IDE:pycharm Python: Python3.6 OS: win10 tf : CPU版本 代码可在github中下载,欢迎star,谢谢 CNN-CIFAR-10 一.CIFAR10数据集 ...

  8. 深度学习笔记:卷积神经网络的可视化--特征图

    目录 1. 前言 2. 模型的训练 3. 特征图可视化 3.1 加载保存的模型¶ 3.2 图像预处理:将图像转换为张量 3.3 例化一个模型用于返回各层激活输出(即feature map) 3.5 各 ...

  9. 学习笔记 | 深度卷积神经网络在计算机视觉中的应用

    图像识别是一种利用计算机对图像进行处理.分析和理解,以识别各种不同模式的目标和对象的技术,是计算机视觉领域的一个主要研究方向,在以图像为主体的智能化数据采集与处理中具有十分重要 的作用和影响.目前图像 ...

最新文章

  1. java中final关键字的使用
  2. 异步FIFO芯片IDT7204、IDT7205的使用
  3. uploadify 附件上传
  4. php5.5 sqlserver 2012,PHP连接SQLSERVER2012
  5. linux c 文件映射,linuxc试题
  6. esri geometry-api-java的maven创建
  7. 最后解密的两弹元勋,众帅之帅朱光亚。
  8. Editplus For Python[转]
  9. linux服务与进程管理sup,linux下进程管理工具-supervisord
  10. 在Spring Boot 项目中使用Spring AOP实现切面日志
  11. 【IDEA类注释模板和方法注释模板】
  12. 应用计算机测线性电阻伏安特性曲线,测绘线性电阻和非线性电阻的伏安特性曲线.pdf...
  13. 杭电校赛(油菜花王国)
  14. 面向开发人员的 ChatGPT 提示词教程 - ChatGPT Prompt Engineering for Developers
  15. 连打印机时网络里面没有计算机,打印机显示打印系统没有连接到计算机怎么回事...
  16. 小重山 【南宋】 岳飞
  17. 5g通用模组是什么_5G通用模组使能行业数字化转型,中国电信在行动
  18. win7如何设置通电自动开机_dell主板win10如何设置通电自动启动_dell主板win10怎么设置通电自动启动...
  19. 【Android源码面试宝典】MMKV从使用到原理分析(一)
  20. JS 实现鼠标进入变色

热门文章

  1. angular路由操作中'#'字符的解决办法
  2. 六角填数---第五届蓝桥杯
  3. Windows Shell 编程 第六章 【来源:http://blog.csdn.net/wangqiulin123456/article/details/7987951】...
  4. 如何判断网通、电信、铁通IP地址分配段
  5. IHttpHandler与IHttpHandlerFactory的区别一例
  6. [pytorch、学习] - 3.5 图像分类数据集
  7. Android 长按照片保存 工具类
  8. mysql学习(2)索引的本质
  9. 移动开发web第一天
  10. CenterOs 防火墙设置