搭建一个 CNN识别手写数字
前面跟着莫烦python/tensorflow教程完成了神经网络识别手写数字的代码,这一part是cnn识别手写数字的
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot = True)
def compute_accuracy(v_xs, v_ys): # 计算精度函数
global prediction # 在函数里定义全局变量
y_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)) #预测值和真实数据差别
# 函数tf.equal(x,y,name=None)对比x与y矩阵/向量中相等的元素,
#相等的返回True,不相等返回False,返回的矩阵/向量的维度与x相同;
#tf.argmax()返回最大值对应的下标(1表示每一列中的,0表示每一行)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# tf.cast()类型转换函数,将correct_prediction转换成float32类型,并对correct_prediction求平均值得到arruracy
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob:1})
return result
这部分需要写一下函数的定义+构建层
def weight_variable(shape):
pass
def bias_variable(shape):
pass
def con2d(shape):
pass
def max_pool_2x2(shape):
pass
#define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None,784] )
ys = tf.placeholder(tf.float32, [None,10] )
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(xs, [-1, 28, 28, 1])
##conv1 layer##
##conv2 layer##
##func1 layer##
##func2 layer##
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),
reduction_indices=[1]))#交叉熵!
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
#通用片段
sess= tf.Session()
sess.run(tf.initialize_all_variables())
for i in range(1000):
batch_xs, batch_ys= mnist.train.next_batch(100) #SGD
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, mnist.test.labels))
初始化用到的函数:
truncated_normal( shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None )
产生截断正态分布随机数,取值范围为 [ mean - 2 * stddev, mean + 2 * stddev ]。
参数:
shape: 一维整数张量& array。 这个值决定输出张量的形状
mean: 零维张量&类型属于dtype的Python值. 这个值决定正态分布片段的平均值
stddev: 零维张量&类型属于dtype的Python值. 这个值决定正态分布片段的标准差
dtype: 输出的类型
seed: 一个Python整数. 被用来为正态分布创建一个随机种子.
name: 操作的名字 (可选参数)
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#cnn
mnist = input_data.read_data_sets('MNIST_data', one_hot = True)
def compute_accuracy(v_xs, v_ys): # 计算精度函数
global prediction # 在函数里定义全局变量
y_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)) #预测值和真实数据差别
# 函数tf.equal(x,y,name=None)对比x与y矩阵/向量中相等的元素,
#相等的返回True,不相等返回False,返回的矩阵/向量的维度与x相同;
#tf.argmax()返回最大值对应的下标(1表示每一列中的,0表示每一行)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# tf.cast()类型转换函数,将correct_prediction转换成float32类型,并对correct_prediction求平均值得到arruracy
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob:1})
return result
def weight_variable(shape):
inital = tf.random.truncated_normal(shape, stddev=0.1)
return tf.Variable(inital)
def bias_variable(shape):
inital = tf.constant(0.1, shape=shape)
return tf.Variable(inital)
def con2d(x, W):
#stride[1. x_movement, y_momvement, 1]
return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')
def max_pool_2x2(x):
#stride[1. x_movement, y_momvement, 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] )
ys = tf.placeholder(tf.float32, [None,10] )
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(xs, [-1, 28, 28, 1])
#print(x_image.shape) #[n_samples,28,28,1]
##conv1 layer##
W_conv1 = weight_variable([5,5,1,32])#patch5*5,in size 1,out size 32
b_conv1= bias_variable([32])
h_conv1 = tf.nn.relu(con2d(x_image, W_conv1) + b_conv1) #relu非线性 output size 28x28x32
h_pool1 = max_pool_2x2(h_conv1)#output size 14x14x32 由于max_pool_2x2 steide=2
##conv2 layer##卷积+池化
W_conv2 = weight_variable([5,5,32,64])#patch5*5,in size 32,out size 64
b_conv2= bias_variable([64])
h_conv2 = tf.nn.relu(con2d(h_pool1, W_conv2) + b_conv2) #relu非线性 output size 14x14x64
h_pool2 = max_pool_2x2(h_conv2)#output size 7x7x64 由于max_pool_2x2 steide=2
##func1 layer##
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)
##func2 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
# https://blog.csdn.net/weixin_42149550/article/details/98759006
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),
reduction_indices=[1]))#交叉熵!
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
sess= tf.Session()
sess.run(tf.initialize_all_variables())
for i in range(1000):
batch_xs, batch_ys= mnist.train.next_batch(100) #SGD
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, mnist.test.labels))
运行一下康康 !