Tensorflow入门到实战五(卷积神经网络)
方法定义
tf.nn.conv2d (input, filter, strides, padding, use_cudnn_on_gpu=None, data_format=None, name=None)
参数:
**input : ** 输入的要做卷积的图片,要求为一个张量,shape为 [ batch, in_height, in_weight, in_channel ],其中batch为图片的数量,in_height 为图片高度,in_weight 为图片宽度,in_channel 为图片的通道数,灰度图该值为1,彩色图为3。(也可以用其它值,但是具体含义不是很理解)
filter: 卷积核,要求也是一个张量,shape为 [ filter_height, filter_weight, in_channel, out_channels ],其中 filter_height 为卷积核高度,filter_weight 为卷积核宽度,in_channel 是图像通道数 ,和 input 的 in_channel 要保持一致,out_channel 是卷积核数量。
strides: 卷积时在图像每一维的步长,这是一个一维的向量,[ 1, strides, strides, 1],第一位和最后一位固定必须是1
padding: string类型,值为“SAME” 和 “VALID”,表示的是卷积的形式,是否考虑边界。"SAME"是考虑边界,不足的时候用0去填充周围,"VALID"则不考虑
use_cudnn_on_gpu: bool类型,是否使用cudnn加速,默认为true
最近在用tensorflow搭建卷积神经网络,遇到了一个比较棘手的问题,我一直理解的padding有两个值,一个是SAME,一个是VALID,如果padding设置为SAME,则说明输入图片大小和输出图片大小是一致的,如果是VALID则图片经过滤波器后可能会变小。
1.VALID模式
输出的宽和高为
o_w = (i_w - f_w + 1)/ s_w #(结果向上取整) o_h = (i_h - f_h + 1)/ s_h #(结果向上取整)
2. SAME模式
输出的宽和高为
o_w = i_w / s_w#(结果向上取整) o_h = i_h / s_h#(结果向上取整)
inputs = tf.Variable(tf.random_normal([1,5,5,3]))
filters = tf.Variable(tf.random_normal([3,3,3,7]))result = tf.nn.conv2d(inputs,filters,strides=[1,2,2,1],padding='SAME')
init = tf.global_variables_initializer()
session = tf.Session()
session.run(init)
print(result.shape)(1, 3, 3, 7)
inputs = tf.Variable(tf.random_normal([1,5,5,3]))
filters = tf.Variable(tf.random_normal([3,3,3,7]))result = tf.nn.conv2d(inputs,filters,strides=[1,2,2,1],padding='VALID')
init = tf.global_variables_initializer()
session = tf.Session()
session.run(init)
print(result.shape)
(1, 2, 2, 7)
卷积神经网络:
"""
卷积神经网络
两个卷积层,两个全连接层
输入 [sample * 28 * 28 * 1 ] (灰度图)
[ 28 * 28 *1 ] --> (32个卷积核,每个大小5*5*1,sample方式卷积) --> [ 28 * 28 * 32] --> (池化 2*2 ,步长2)--> [14 *14 *32]
[ 14 * 14 *32] --> (64个卷积核,每个大小 5 * 5 * 32,sample方式卷积) --> [14 * 14 *64] --> (池化 2*2 ,步长2)--> [7 * 7 *64]
[ 7 * 7 * 64] --> reshape 成列向量 --> (7 * 7 * 64)
[sample * (7*7*64)] 全连接层1 weights:[7*7*64 , 1024] --> [sample * 1024]
[sample * 1024] 全连接层2 weights:[1024,10] --> [sample *10]
输出:10个分类
"""import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# number 1 to 10 data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)def compute_accuracy(v_xs, v_ys):global predictiony_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1})return resultdef weight_variable(shape):initial = tf.truncated_normal(shape, stddev=0.1)return tf.Variable(initial)def bias_variable(shape):initial = tf.constant(0.1, shape=shape)return tf.Variable(initial)def conv2d(x, W):# stride [1, x_movement, y_movement, 1]# Must have strides[0] = strides[3] = 1return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')def max_pool_2x2(x):# stride [1, x_movement, y_movement, 1]return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 784])/255. # 28x28
ys = tf.placeholder(tf.float32, [None, 10])
keep_prob = tf.placeholder(tf.float32)#把xs的形状变成[-1,28,28,1],-1代表先不考虑输入的图片例子多少这个维度,后面的1是channel的数量
#因为我们输入的图片是黑白的,因此channel是1,例如如果是RGB图像,那么channel就是3。
x_image = tf.reshape(xs, [-1, 28, 28, 1])
# print(x_image.shape) # [n_samples, 28,28,1]#建立卷积层
## 本层我们的卷积核patch的大小是5x5,因为黑白图片channel是1所以输入是1,输出是32个featuremap ??? 32 是什么意思?
W_conv1 = weight_variable([5,5, 1,32]) # patch 5x5, in size 1, out size 32
b_conv1 = bias_variable([32])
#卷积运算
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # output size 28x28x32
h_pool1 = max_pool_2x2(h_conv1) # output size 14x14x32W_conv2 = weight_variable([5,5, 32, 64]) # patch 5x5, in size 32, out size 64 ??? 64 是什么意思?
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # output size 14x14x64
h_pool2 = max_pool_2x2(h_conv2) # output size 7x7x64#全连接层
W_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])
# [n_samples, 7, 7, 64] ->> [n_samples, 7*7*64]
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)## fc2 layer ##
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)# the error between prediction and real data
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),reduction_indices=[1])) # loss
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)sess = tf.Session()if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:init = tf.initialize_all_variables()
else:init = tf.global_variables_initializer()
sess.run(init)# 原来是1000 为了快一点 改成了1000
for i in range(500):batch_xs, batch_ys = mnist.train.next_batch(100)sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})if i % 50 == 0:print(compute_accuracy(mnist.test.images[:1000], mnist.test.labels[:1000]))
Tensorflow入门到实战五(卷积神经网络)相关推荐
- 通过 Tensorflow 的基础类,构建卷积神经网络,用于花朵图片的分类
实验目的 通过 Tensorflow 的基础类,构建卷积神经网络,用于花朵图片的分类. 实验环境 import tensorflow as tfprint(tf.__version__) output ...
- 深度学习实战——利用卷积神经网络对手写数字二值图像分类(附代码)
系列文章目录 深度学习实战--利用卷积神经网络对手写数字二值图像分类(附代码) 目录 系列文章目录 前言 一.案例需求 二.MATLAB算法实现 三.MATLAB源代码 参考文献 前言 本案例利用MA ...
- 实战▍利用卷积神经网络(VGG19)实现火灾分类(附tensorflow代码及训练集)
作者| 帅虫哥 编辑|布袋熊 利用卷积神经网络(VGG19)实现火灾分类 先看两组数据: <新民周刊>:2018年6月到11月,美国加利福尼亚州的山火断断续续地烧了小半年,到入冬方才算 ...
- TensorFlow官方入门实操课程-卷积神经网络
知识点 卷积:用原始像素数据与过滤器中的值相乘,以后加起来. 如下是增强水平特征的过滤器. MaxPooling:每次卷积结束以后用一个MaxPooling用来增强图像的特征. 可以看出经过MaxPo ...
- PyTorch实战福利从入门到精通之四——卷积神经网络CIFAR-10图像分类
在本教程中,我们将使用CIFAR10数据集.它有类别:"飞机"."汽车"."鸟"."猫"."鹿".& ...
- PyTorch实战福利从入门到精通之七——卷积神经网络(LeNet)
卷积神经网络就是含卷积层的网络.介绍一个早期用来识别手写数字图像的卷积神经网络:LeNet [1].这个名字来源于LeNet论文的第一作者Yann LeCun.LeNet展示了通过梯度下降训练卷积神经 ...
- 【拔刀吧 TensorFlow】TensorFlow学习笔记八——何为卷积神经网络
TensorFlow直接以官方手册作为切入点,在趣味性和快速性上优势很大,但是对于学习深入理论的理解产生了巨大的阻碍. 在"深入MNIST"这一节中,遇到了卷积神经网络的构建,涉及 ...
- Tensorflow系列 | TensorFlowNews五大经典卷积神经网络介绍
编译 | fendouai 编辑 | 安可 [导读]:这个系列文章将会从经典的卷积神经网络历史开始,然后逐个讲解卷积神经网络结构,代码实现和优化方向.下一篇文章将会是 LeNet 卷积神经网络结构,代 ...
- keras构建卷积神经网络_在python中使用tensorflow s keras api构建卷积神经网络的初学者指南...
keras构建卷积神经网络 初学者的深度学习 (DEEP LEARNING FOR BEGINNERS) Welcome to Part 2 of the Neural Network series! ...
最新文章
- kaldi 源码分析(十) - gmm-init-mono.c分析
- 让你的 conda “回滚”到以前版本的环境
- Anaconda,pytorch如何安装中文版的BERT和使用
- 【算法】论平衡二叉树(AVL)的正确种植方法
- AngularJS开发人员最常犯的10个错误
- 深入理解计算机系统(2.7)------浮点数舍入以及运算
- C++以字符串形式返回第N个斐波那契的算法(附完整源码)
- MSE | 阿里巴巴云原生网关三位一体的选择与实践
- [笔试题目] 美团2015年9月后端开发工程师笔试题
- 调用postman拿CSRF token的隐藏Cookie处理
- 数据库---聚合查询
- MVC Html.AntiForgeryToken() 防止CSRF***
- C#水晶报表,窗体不显示,闪退
- Python中利用*打印不同的三角形
- 提交App中断出现 Cannot proceed with delivery an existing transporter instan
- cognos安装和配置即席报表流程
- 使用jmeter测试接口
- 主数据管理(MDM)的成熟度
- [CATARC_2017] 第一周
- JavaScript 压缩图片
热门文章
- 阿里云服务器+腾讯域名进行域名解析
- 笔记本 Ubuntu 16.04 单目ORB_SLAM2 + ROS + usb_cam 环境的搭建与实现(地图的构建)
- Java 位运算基础
- Swagger-ui.html页面简单的修改
- 实验三 基本表的定义、删除与修改
- 近距离无线通信(NFC)技术介绍
- 第四代微型计算机,第四代树莓派微型电脑正式发布 首搭4GB内存,支持USB 3.0和双屏4K输出...
- 无尽长廊(Gallery)
- python画位势高度图_气候变化位势高度
- 软件测试之测试主流技能