TensorFlow-

 1 #load MNIST data
 2 import tensorflow.examples.tutorials.mnist.input_data as input_data
 3 mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
 4 
 5 #start tensorflow interactiveSession
 6 import tensorflow as tf
 7 sess = tf.InteractiveSession()
 8 
 9 #weight initilization
10 def weight_variable(shape):
11     initial = tf.truncated_normal(shape, stddev=0.1)
12     return tf.Variable(initial)
13 
14 def bias_variable(shape):
15     initial = tf.constant(0.1, shape= shape)
16     return tf.Variable(initial)
17 
18 #convolution
19 def conv2d(x, W):
20     return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')
21 
22 #pooling
23 def max_pool_2x2(x):
24     return tf.nn.max_pool(x, ksize=[1,2,2,1],strides=[1,2,2,1], padding='SAME')
25 
26 #Create the model
27 #placeholder
28 x = tf.placeholder("float",[None, 784])
29 y_ = tf.placeholder("float", [None, 10])
30 
31 #variable
32 W = tf.Variable(tf.zeros([784,10]))
33 b = tf.Variable(tf.zeros([10]))
34 
35 y = tf.nn.softmax(tf.matmul(x,W) +b)
36 
37 #first convolutional layer
38 w_conv1 = weight_variable([5,5,1,32])
39 b_conv1 = bias_variable([32])
40 
41 x_image = tf.reshape(x,[-1,28,28,1])
42 
43 h_conv1 =tf.nn.relu(conv2d(x_image,w_conv1) + b_conv1)
44 h_pool1 =max_pool_2x2(h_conv1)
45 
46 #second convolutional layer
47 w_conv2 = weight_variable([5,5,32,64])
48 b_conv2 = bias_variable([64])
49 
50 h_conv2 =tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)
51 h_pool2 =max_pool_2x2(h_conv2)
52 
53 #densely connected layer
54 w_fc1 = weight_variable([7*7*64, 1024])
55 b_fc1 = bias_variable([1024])
56 
57 h_pool2_flat = tf.reshape(h_pool2, [-1,7*7*64])
58 h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)
59 
60 #dropout
61 keep_prob = tf.placeholder("float")
62 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
63 
64 #readout layer
65 w_fc2 = weight_variable([1024,10])
66 b_fc2 = bias_variable([10])
67 
68 y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop,w_fc2) + b_fc2)
69 
70 #train and evaluate the model
71 cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
72 #train_step = tf.train.AdagradOptimizer(1e-4).minimize(cross_entropy)
73 train_step = tf.train.GradientDescentOptimizer(1e-4).minimize(cross_entropy)
74 correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
75 accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
76 sess.run(tf.initialize_all_variables())
77 for i in range(5000):
78     batch = mnist.train.next_batch(50)
79     if i%100 ==0:
80         train_accuracy = accuracy.eval(feed_dict={x:batch[0],y_:batch[1], keep_prob:1.0})
81         print "step %d, train accuracy %g " %(i,train_accuracy)
82     train_step.run(feed_dict={x:batch[0],y_:batch[1], keep_prob:0.5})
83 
84 print "test accuracy %g" % accuracy.eval(fedd_dict={x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0})

猜你喜欢

转载自www.cnblogs.com/jourluohua/p/9130310.html