Tensorflow - Implement for a Softmax Regression Model on MNIST.

Coding according to TensorFlow 官方文档中文版

 1 import tensorflow as tf
 2 from tensorflow.examples.tutorials.mnist import input_data
 3 mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
 4 
 5 ''' Intro. for this python file.
 6 Objective:
 7     Implement for a Softmax Regression Model on MNIST.
 8 Operation Environments:
 9     python = 3.6.4
10     tensorflow = 1.15.0
11 '''
12 
13 # Set a placeholder. We hope arbitrary number of images could be input to this model.
14 x = tf.placeholder("float", [None, 784])
15 
16 # Set weight/bias variables. Their initial values could be set Randomly.
17 W = tf.Variable(tf.zeros([784, 10]))
18 b = tf.Variable(tf.zeros([10]))
19 
20 # Model implementation
21 y = tf.nn.softmax(tf.matmul(x, W) + b)
22 
23 # Set a placeholder 'y_' to accept the ground-truth values.
24 y_ = tf.placeholder("float", [None, 10])
25 
26 # Calculate cross-entropy
27 cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
28 
29 # Train Softmax Regression Model
30 train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
31 
32 # Initialize variables
33 # init = tf.initialize_all_variables()  # Warning
34 init = tf.global_variables_initializer()
35 
36 # Launch the graph in a session.
37 sess = tf.Session()
38 sess.run(init)
39 
40 for i in range(1000):
41     batch_xs, batch_ys = mnist.train.next_batch(100)    # Grabbing 100 batch data points from training data randomly.
42     sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
43 
44 # Model Evaluation
45 # correct_prediction = tf.equal(tf.arg_max(y, 1), tf.arg_max(y_, 1))    # Warning
46 ''' tf.argmax(input, axis=None, name=None, dimension=None, output_type=tf.int64)
47 Explanation: Returns the index with the largest value across axes of a tensor. 
48     test = np.array([[1, 2, 3], [2, 3, 4], [5, 4, 3], [8, 7, 2]])
49     np.argmax(test, 0)      # output:array([3, 3, 1])
50     np.argmax(test, 1)      # output:array([2, 2, 0, 0])
51 '''
52 correct_prediction = tf.equal(tf.argmax(y, axis=1), tf.argmax(y_, axis=1))
53 accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
54 print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
55 
56 # The result is around 0.91.

猜你喜欢

转载自www.cnblogs.com/zlian2016/p/9549371.html