# 利用CNN卷积神经网络进行手写MNIST数字识别

3 篇文章 0 订阅
7 篇文章 0 订阅

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

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))
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 result

def W(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)

def Conv2d(x,y):
return tf.nn.conv2d(x, y, strides=[1, 1, 1, 1], padding='SAME')

def Pool(x):

xs = tf.placeholder(tf.float32,[None,784])
ys = tf.placeholder(tf.float32,[None,10])
x_imag = tf.reshape(xs,[-1,28,28,1])
keep_prob = tf.placeholder(tf.float32)

#conv1
W1 = W([5,5,1,32])
B1 = tf.Variable(tf.constant(0.1,shape=[32]))
H1 = tf.nn.relu(Conv2d(x_imag,W1)+B1)
P1 = Pool(H1)
#conv2
W2 = W([5,5,32,64])
B2 = tf.Variable(tf.constant(0.1,shape=[64]))
H2 = tf.nn.relu(Conv2d(P1,W2)+B2)
P2 = Pool(H2)
#F1
W3 = W([7*7*64,1024])
B3 = tf.Variable(tf.constant(0.1,shape=[1024]))
H31 = tf.reshape(P2,[-1,7*7*64])
H32 = tf.nn.relu(tf.matmul(H31,W3)+B3)
H33 = tf.nn.dropout(H32,keep_prob)
#F2
W4 = W([1024,10])
B4 = tf.Variable(tf.constant(0.1,shape=[10]))
H4 = tf.matmul(H33,W4)+B4
prediction = tf.nn.softmax(H4)

cross_entropy =  tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
reduction_indices=[1]))

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

for i in range(1000):
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]))



• 0
点赞
• 1
评论
• 2
收藏
• 打赏
• 扫一扫，分享海报

02-14
08-16 12万+

11-07 7万+
06-02 5885
05-17 6594
05-29 1万+
11-24 8290
04-17 1040
06-16
12-18
09-03 1374
01-24 1614
01-17 770
04-07 9618

Gipsyu

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。