Tensorflow-CNN学习以及实现

代码参数解释

卷积操作

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

input:待卷积的数据。格式要求为一个张量,[batch, in_height, in_width, in_channels].
分别表示 批次数,图像高度,宽度,输入通道数。
filter: 卷积核。格式要求为[filter_height, filter_width, in_channels, out_channels].
分别表示 卷积核的高度,宽度,输入通道数,输出通道数。
strides :一个长为4的list. 表示每次卷积以后卷积窗口在input中滑动的距离
padding :有SAME和VALID两种选项,表示是否要保留图像边上那一圈不完全卷积的部分。如果是SAME,则保留
use_cudnn_on_gpu :是否使用cudnn加速。默认是True

池化操作

tf.nn.max_pool
进行最大值池化操作,而avg_pool 则进行平均值池化操作.函数的定义为:

max_pool(value, ksize, strides, padding, data_format="NHWC", name=None):
  • 1

value: 一个4D张量,格式为[batch, height, width, channels],与conv2d中input格式一样
ksize: 长为4的list,表示池化窗口的尺寸
strides: 池化窗口的滑动值,与conv2d中的一样
padding: 与conv2d中用法一样。

代码实现以及解释

import 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)# Parameters
learning_rate = 0.001
training_iters = 200000
batch_size = 128
display_step = 10# Network Parameters
n_input = 784 # MNIST data input (img shape: 28*28)
n_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, n_input])
y = tf.placeholder(tf.float32, [None, n_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 activation# 结果返回一个Tensor,这个输出是feature map,shape仍然是[batch, height, width, channels]这种形式。# 第二个参数(W):参数含义:[卷积核的高度,卷积核的宽度,图像通道数,卷积核个数]x = 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):# Reshape input picturex = tf.reshape(x, shape=[-1, 28, 28, 1])#第一层,输入x是28*28,通道数为1,输出通道为32,即feature map 数目为32# 又因为strides=[1,1,1,1] 所以单个通道的输出尺寸应该跟输入图像一样(为了保持输入和输出一样,在最边和上面补充0)。即总的卷积输出应该为?*28*28*32# 也就是单个通道输出为28*28,共有32个通道,共有?个批次# 在池化阶段,ksize=[1,2,2,1] 那么卷积结果经过池化以后的结果,其尺寸应该是?*14*14*32# Convolution Layerconv1 = conv2d(x, weights['wc1'], biases['bc1'])# Max Pooling (down-sampling)conv1 = maxpool2d(conv1, k=2)#第二层# 卷积核5*5,输入通道为32,输出通道为64。# 卷积前图像的尺寸为 ?*14*14*32, 卷积后为?*14*14*64# 池化后,输出的图像尺寸为?*7*7*64# Convolution Layerconv2 = conv2d(conv1, weights['wc2'], biases['bc2'])# Max Pooling (down-sampling)conv2 = maxpool2d(conv2, k=2)# 第三层,是个全连接层, 输入维数7 * 7 * 64, 输出维数为1024# 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)# 这里使用了drop out,即随机安排一些cell输出值为0,可以防止过拟合# Apply Dropoutfc1 = tf.nn.dropout(fc1, dropout)# 第四层,输入1024维,输出10维,也就是具体的0~9分类# Output, class predictionout = tf.add(tf.matmul(fc1, weights['out']), biases['out'])return out# Store layers weight & bias
# 这里的weight就是卷积核,卷积核就是要学习的参数(个人理解,不到位请指点)
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, n_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([n_classes]))
}# Construct model
pred = conv_net(x, weights, biases, keep_prob)# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)# Evaluate model
correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))# Initializing the variables
init = tf.global_variables_initializer()# Launch the graph
with tf.Session() as sess:sess.run(init)step = 1# Keep training until reach max iterationswhile step * batch_size < training_iters:batch_x, batch_y = mnist.train.next_batch(batch_size)# Run optimization op (backprop)sess.run(optimizer, feed_dict={x: batch_x, y: batch_y,keep_prob: dropout})if step % display_step == 0:# Calculate batch loss and accuracyloss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,y: batch_y,keep_prob: 1.})print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \"{:.6f}".format(loss) + ", Training Accuracy= " + \"{:.5f}".format(acc))step += 1print("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.}))


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部