直接上代码进行分析:

""" Convolutional Neural Network.Build and train a convolutional neural network with TensorFlow.
This example is using the MNIST database of handwritten digits
(http://yann.lecun.com/exdb/mnist/)Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
"""from __future__ import division, print_function, absolute_importimport tensorflow as tf# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("tmp/data/", one_hot=True)# Training Parameters
learning_rate = 0.001
num_steps = 200
batch_size = 128
display_step = 10# Network Parameters
num_input = 784 # MNIST data input (img shape: 28*28)
num_classes = 10 # MNIST total classes (0-9 digits)
dropout = 0.75 # Dropout, probability to keep units# tf Graph input
X = tf.placeholder(tf.float32, [None, num_input])
Y = tf.placeholder(tf.float32, [None, num_classes])
keep_prob = tf.placeholder(tf.float32) # dropout (keep probability)# Create some wrappers for simplicity
def conv2d(x, W, b, strides=1):# Conv2D wrapper, with bias and relu activationx = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')x = tf.nn.bias_add(x, b)return tf.nn.relu(x)def maxpool2d(x, k=2):# MaxPool2D wrapperreturn tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],padding='SAME')# Create model
def conv_net(x, weights, biases, dropout):# MNIST data input is a 1-D vector of 784 features (28*28 pixels)# Reshape to match picture format [Height x Width x Channel]# Tensor input become 4-D: [Batch Size, Height, Width, Channel]x = tf.reshape(x, shape=[-1, 28, 28, 1])# Convolution Layerconv1 = conv2d(x, weights['wc1'], biases['bc1'])# Max Pooling (down-sampling)conv1 = maxpool2d(conv1, k=2)# Convolution Layerconv2 = conv2d(conv1, weights['wc2'], biases['bc2'])# Max Pooling (down-sampling)conv2 = maxpool2d(conv2, k=2)# Fully connected layer# Reshape conv2 output to fit fully connected layer inputfc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])fc1 = tf.nn.relu(fc1)# Apply Dropoutfc1 = tf.nn.dropout(fc1, dropout)# Output, class predictionout = tf.add(tf.matmul(fc1, weights['out']), biases['out'])return out# Store layers weight & bias
weights = {# 5x5 conv, 1 input, 32 outputs'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),# 5x5 conv, 32 inputs, 64 outputs'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),# fully connected, 7*7*64 inputs, 1024 outputs'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),# 1024 inputs, 10 outputs (class prediction)'out': tf.Variable(tf.random_normal([1024, num_classes]))
}biases = {'bc1': tf.Variable(tf.random_normal([32])),'bc2': tf.Variable(tf.random_normal([64])),'bd1': tf.Variable(tf.random_normal([1024])),'out': tf.Variable(tf.random_normal([num_classes]))
}# Construct model
logits = conv_net(X, weights, biases, keep_prob)
prediction = tf.nn.softmax(logits)# Define loss and optimizer
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)# Evaluate model
correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()# Start training
with tf.Session() as sess:# Run the initializersess.run(init)for step in range(1, num_steps+1):batch_x, batch_y = mnist.train.next_batch(batch_size)# Run optimization op (backprop)sess.run(train_op, feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.8})if step % display_step == 0 or step == 1:# Calculate batch loss and accuracyloss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x,Y: batch_y,keep_prob: 1.0})print("Step " + str(step) + ", Minibatch Loss= " + \"{:.4f}".format(loss) + ", Training Accuracy= " + \"{:.3f}".format(acc))print("Optimization Finished!")# Calculate accuracy for 256 MNIST test imagesprint("Testing Accuracy:", \sess.run(accuracy, feed_dict={X: mnist.test.images[:256],Y: mnist.test.labels[:256],keep_prob: 1.0}))

tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)

第一个参数input:指需要做卷积的输入图像,它要求是一个Tensor,具有[batch, in_height, in_width, in_channels]这样的shape,具体含义是[训练时一个batch的图片数量, 图片高度, 图片宽度, 图像通道数],注意这是一个4维的Tensor,要求类型为float32和float64其中之一,其中图像通道数:比如rgb24图像,通道数为3

第二个参数filter:相当于CNN中的卷积核,它要求是一个Tensor,具有[filter_height, filter_width, in_channels, out_channels]这样的shape,具体含义是[卷积核的高度,卷积核的宽度,图像通道数,输出通道],要求类型与参数input相同,有一个地方需要注意,第三维in_channels,就是参数input的第四维

第三个参数strides:卷积时在图像每一维的步长,这是一个一维的向量,长度4

第四个参数padding:string类型的量,只能是"SAME","VALID"其中之一,这个值决定了不同的卷积方式(后面会介绍)

第五个参数:use_cudnn_on_gpu:bool类型,是否使用cudnn加速,默认为true

结果返回一个Tensor,这个输出,就是我们常说的feature map,shape仍然是[batch, height, width, channels]这种形式。

卷积的结果可以查看上一篇的卷积。这里就举个例子吧:

input = tf.Variable(tf.random_normal([1,5,5,5])) =》数量1 图像高度5 宽度5 通道数5

filter = tf.Variable(tf.random_normal([3,3,5,1]))==》卷积核高3 卷积核宽5 通道5 输出通道1

=》输出结果数量1  高3 宽3 通道数1

x = tf.nn.bias_add(x, b)

举个例子好理解一点:

a=tf.constant([[1,1],[2,2],[3,3]],dtype=tf.float32)
b=tf.constant([1,-1],dtype=tf.float32)
c=tf.constant([1],dtype=tf.float32)with tf.Session() as sess:print('bias_add:')print(sess.run(tf.nn.bias_add(a, b)))#执行下面语句错误#print(sess.run(tf.nn.bias_add(a, c)))print('add:')print(sess.run(tf.add(a, c)))

输出如下:

tf.nn.relu(x)

tf.nn.relu(features, name = None)

将大于0的数保持不变,小于0的数置为0。

举个例子:

a = tf.constant([-1.0, 2.0])
with tf.Session() as sess:b = tf.nn.relu(a)print (sess.run(b))

输出:

tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],
                          padding='SAME')

tf.nn.max_pool(value, ksize, strides, padding, name=None)

参数是四个,和卷积很类似:

第一个参数value:需要池化的输入,一般池化层接在卷积层后面,所以输入通常是feature map,依然是[batch, height, width, channels]这样的shape

第二个参数ksize:池化窗口的大小,取一个四维向量,一般是[1, height, width, 1],因为我们不想在batch和channels上做池化,所以这两个维度设为了1

第三个参数strides:和卷积类似,窗口在每一个维度上滑动的步长,一般也是[1, stride,stride, 1]

第四个参数padding:和卷积类似,可以取'VALID' 或者'SAME'

返回一个Tensor,类型不变,shape仍然是[batch, height, width, channels]这种形式

举个例子:

示例源码:

假设有这样一张图,双通道

第一个通道:

第二个通道:

用程序去做最大值池化:

a=tf.constant([  [[1.0,2.0,3.0,4.0],  [5.0,6.0,7.0,8.0],  [8.0,7.0,6.0,5.0],  [4.0,3.0,2.0,1.0]],  [[4.0,3.0,2.0,1.0],  [8.0,7.0,6.0,5.0],  [1.0,2.0,3.0,4.0],  [5.0,6.0,7.0,8.0]]  ])  a=tf.reshape(a,[1,4,4,2])  pooling=tf.nn.max_pool(a,[1,2,2,1],[1,1,1,1],padding='VALID')
with tf.Session() as sess:  print("image:")  image=sess.run(a)  print (image)  print("reslut:")  result=sess.run(pooling)  print (result)  

输出为:

池化后的图就是:

tensorflow之卷积神经网络相关推荐

  1. 【深度学习】Tensorflow搭建卷积神经网络实现情绪识别

    [深度学习]Tensorflow搭建卷积神经网络实现情绪识别 文章目录 1 Tensorflow的基本使用方法1.1 计算图1.2 Feed1.3 Fetch1.4 其他解释 2 训练一个Tensor ...

  2. 从零开始用TensorFlow搭建卷积神经网络

     https://www.jiqizhixin.com/articles/2017-08-29-14 机器之心GitHub项目:从零开始用TensorFlow搭建卷积神经网络 By 蒋思源2017 ...

  3. TF之CNN:Tensorflow构建卷积神经网络CNN的简介、使用方法、应用之详细攻略

    TF之CNN:Tensorflow构建卷积神经网络CNN的简介.使用方法.应用之详细攻略 目录 TensorFlow 中的卷积有关函数入门 1.tf.nn.conv2d函数 案例应用 1.TF之CNN ...

  4. 04.卷积神经网络 W1.卷积神经网络(作业:手动/TensorFlow 实现卷积神经网络)

    文章目录 作业1:实现卷积神经网络 1. 导入一些包 2. 模型框架 3. 卷积神经网络 3.1 Zero-Padding 3.2 单步卷积 3.3 卷积神经网络 - 前向传播 4. 池化层 5. 卷 ...

  5. 基于tensorflow和卷积神经网络的电影推荐系统的实现

    基于tensorflow和卷积神经网络的电影推荐系统的实现 一. 数据处理 1. MovieLens数据集 2. 处理后的数据 二. 建模&训练 1. 嵌入层 2. 文本卷积层 3. 全连接层 ...

  6. TensorFlow CNN卷积神经网络实现工况图分类识别(一)

    1. Tensorflow知识点 1.1. 张量 在Tensorflow程序中,所有的数据都是通过张量的形式来表示.从功能的角度上看,张量可以简单的理解为多维数组. (1)占位符Placeholder ...

  7. 【深度学习】我的第一个基于TensorFlow的卷积神经网络

    基于MNIST数据集实现简单的卷积神经网络,熟悉基于TensorFlow的CNN的流程和框架. #1.导入相关库 import numpy as np import tensorflow as tf ...

  8. 【Tensorflow】卷积神经网络实现艺术风格化通过Vgg16实现

    卷积神经网络实现艺术风格化 基于卷积神经网络实现图片风格的迁移,可以用于大学生毕业设计基于python,深度学习,tensorflow卷积神经网络, 通过Vgg16实现,一幅图片内容特征的基础上添加另 ...

  9. 【深度学习】TensorFlow之卷积神经网络

    卷积神经网络的概念 在多层感知器(Multilayer Perceptrons,简称MLP)中,每一层的神经元都连接到下一层的所有神经元.一般称这种类型的层为完全连接. 多层感知器示例 反向传播 几个 ...

  10. python神经网络库识别验证码_基于TensorFlow 使用卷积神经网络识别字符型图片验证码...

    本项目使用卷积神经网络识别字符型图片验证码,其基于TensorFlow 框架.它封装了非常通用的校验.训练.验证.识别和调用 API,极大地减低了识别字符型验证码花费的时间和精力. 项目地址:http ...

最新文章

  1. python画图三维-对python mayavi三维绘图的实现详解
  2. Framebuffer 机制
  3. 【SpringBoot零基础案例08】【IEDA 2021.1】SpringBoot获取核心配置文件application.properties中的自定义配置
  4. 如何保证战略落地_如何让战略落地:流程管理的道法术器让战略落地提升竞争力...
  5. 各個瀏覽器CSS樣式控制
  6. 学习ASP.NET之前,先了解它
  7. centos 的网关和什么相同_CentOS操作系统:为什么转移到CentOS流是一个大错误
  8. 【元胞自动机】基于matlab元胞自动机短消息网络病毒传播仿真【含Matlab源码 1289期】
  9. matlab 模式识别(第四版),模式识别与智能计算—MATLAB技术实现(第4版)
  10. linux 一键安装字体,在deepin中一键安装喜欢的字体,文档气质瞬间提升!
  11. IIS7安装URLReWrite的妙用
  12. mac用u盘安装linux系统教程视频,教你如何用u盘重装mac系统教程
  13. ASP.NET类计算机专业毕业设计题目选题课题
  14. 手机安全卫士------查询号码归属地
  15. 乐视x820android最新版本,乐视MAX2|MIUI10|安卓8.1|最终完美版|极速_最新最全的乐Max2ROM刷机包下载、刷机教程_...
  16. IoT with Mongodb cloud
  17. 这些年我要读的书【不断更新中】
  18. 第一次阅读与准备作业
  19. 12-render函数
  20. 【连接池】Tomcat 连接池中 maxActive,maxWait,maxAge,testOnBorrow,testWhileIdle等选项的作用

热门文章

  1. shell 面试题 (一) 待续
  2. 【转载】异步调用与多线程的区别
  3. 详细讲解怎样做数据仓库需求分析
  4. php读取doc pdf文件,PHP读取创建txt,doc,xls,pdf类型文件
  5. mysql 8 配置参数优化_MySQL性能优化之参数配置
  6. 如何操作别人计算机,如何远程控制别人的电脑【图解】
  7. [笔记] Ubuntu 18.04安装Docker CE及nvidia-docker2流程
  8. EBS AP 创建会计科目失败
  9. 【bzoj5071】[Lydsy十月月赛]小A的数字 乱搞
  10. nodejs pm2教程(转载)