cnn实现手写数字识别
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
In [ ]: mnist = input_data.read_data_sets('MNIST_data',one_hot =Tr ue)
batch_size =100
n_batch = mnist.train.num_examples // batch_size
def 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):
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
#strides[0] = strides[3] = 1:
def max_pool_2x2(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1], padding='SAME')
#ksize
#ksize: A list of ints that has length >= 4. The size of th
e window for each dimension o
f the input tensor.
#In general for images, your input is of shape [batch_size, 64, 64, 3] for an RGB image of 64x64 pixels.
#The kernel size ksize will typically be [1, 2, 2, 1] if yo u have a 2x2 window over which you take the maximum.
# On the batch size dimension and the channels dimension, k size is 1 because we don't want to take the maximum over mu ltiple examples,
# or over multiples channels.
#strides
# The first 1 is the batch: You don't usually want to skip over examples in your batch, or you shouldn't have included them in the first place. :)
# The last 1 is the depth of the convolution: You don't usu ally want to skip inputs, for the same reason.
x = tf.placeholder(tf.float32,[None,784])#none为任意维度
y = tf.placeholder(tf.float32,[None,10])
x_image = tf.reshape(x,[-1,28,28,1])#-1计算得出
W_conv1 = weight_variable([5,5,1,32])#w,h,输入channel,输出channel
b_conv1 = bias_variable([32])#维数?
h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1) + b_conv1)#x_
image为一批数据
h_pool1 = max_pool_2x2(h_conv1)
W_conv2 = weight_variable([5,5,32,64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
W_fc1 = weight_variable([7*7*64,1024])
b_fc1 = bias_variable([1024])
h_pool2_fla = tf.reshape(h_pool2,[-1,7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_fla,W_fc1) + b_fc1)
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)
W_fc2 = weight_variable([1024,10])
b_fc2 = bias_variable([10])
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2) + b _fc2)
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy _with_logits(labels=y,logits=prediction))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_e ntropy)
correct_prediction = tf.equal(tf.argmax(prediction,1),tf.a rgmax(y,1))#argmax返回一维tensor中最大值的位置,1每行位置最大值