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

 

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄