TensorFlow-简单的卷积神经网络

Posted Run_For_Love一朝一夕一点一滴

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TensorFlow-简单的卷积神经网络相关的知识,希望对你有一定的参考价值。

先弄懂卷积神经网络的原理,推荐这两篇博客:http://blog.csdn.net/yunpiao123456/article/details/52437794   http://blog.csdn.net/qq_25762497/article/details/51052861#%E6%A6%82%E6%8F%BD

 简单的测试程序如下(具体各参数代表什么可以百度):

技术分享图片
 1 from tensorflow.examples.tutorials.mnist import input_data
 2 import tensorflow as tf
 3 
 4 mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)
 5 sess=tf.InteractiveSession()
 6 
 7 def weight_variable(shape):
 8     initial=tf.truncated_normal(shape,stddev=0.1)
 9     return tf.Variable(initial)
10 
11 def bias_variable(shape):
12     initial=tf.constant(0.1,shape=shape)
13     return tf.Variable(initial)
14 
15 def conv2d(x,w):
16     return tf.nn.conv2d(x,w,strides=[1,1,1,1],padding=SAME)
17 
18 def max_pool_2x2(x):
19     return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding=SAME)
20 
21 x=tf.placeholder(tf.float32,[None,784])
22 y_=tf.placeholder(tf.float32,[None,10])
23 x_image=tf.reshape(x,[-1,28,28,1])
24 
25 w_conv1=weight_variable([5,5,1,32])
26 b_conv1=bias_variable([32])
27 h_conv1=tf.nn.relu(conv2d(x_image,w_conv1)+b_conv1)
28 h_pool1=max_pool_2x2(h_conv1)
29 
30 w_conv2=weight_variable([5,5,32,64])
31 b_conv2=bias_variable([64])
32 h_conv2=tf.nn.relu(conv2d(h_pool1,w_conv2)+b_conv2)
33 h_pool2=max_pool_2x2(h_conv2)
34 
35 w_fc1=weight_variable([7*7*64,1024])
36 b_fc1=bias_variable([1024])
37 h_pool2_flat=tf.reshape(h_pool2,[-1,7*7*64])
38 h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,w_fc1)+b_fc1)
39 
40 keep_prob=tf.placeholder(tf.float32)
41 h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)
42 
43 w_fc2=weight_variable([1024,10])
44 b_fc2=bias_variable([10])
45 y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop,w_fc2)+b_fc2)
46 
47 cross_entropy=tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y_conv),reduction_indices=[1]))
48 train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
49 
50 correct_prediction=tf.equal(tf.argmax(y_conv,1),tf.argmax(y_,1))
51 accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
52 
53 tf.initialize_all_variables().run()
54 for i in range(20000):
55     batch=mnist.train.next_batch(50)
56     if i%100==0:
57         train_accuracy=accuracy.eval(feed_dict={x:batch[0],y_:batch[1],keep_prob:1.0})
58         print("step %d,training accuracy %g"%(i,train_accuracy))
59     train_step.run(feed_dict={x:batch[0],y_:batch[1],keep_prob:0.5})
60 
61 print("test accuracy %g"%accuracy.eval(feed_dict={x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0}))
View Code

运行结果:

 

以上是关于TensorFlow-简单的卷积神经网络的主要内容,如果未能解决你的问题,请参考以下文章

TensorFlow/简单网络MNIST数据集-softmax全连接神经网络,卷积神经网络模型

『TensorFlow』读书笔记_简单卷积神经网络

TensorFlow 中的卷积网络

Tensorflow实现卷积神经网络

Tensorflow卷积神经网络[转]

Tensorflow利用卷积神经网络实现图片分类