tensorflow 第一个程序MNIST手写数字识别（Softmax Regression实现）

# -*- coding: utf-8 -*-

"""
Spyder Editor

This is a temporary script file.
"""

from tensorflow.examples.tutorials.mnist import input_data

#query the situation of the data set
print(mnist.train.images.shape, mnist.train.labels.shape)#the dimension and type number of training set data
print(mnist.test.images.shape, mnist.test.labels.shape)#...of the test set data
print(mnist.validation.images.shape, mnist.validation.labels.shape)#...of the vertification set data

import tensorflow as tf

#This use of InteractiveSession() allow us to run variables without needing to constantly refer to the session object
sess = tf.InteractiveSession()

#Create a placeholder which using to input data
x = tf.placeholder(tf.float32, [None, 784])#the first parameter is the data type and the second is the shape of data
#'None' means un-limited data-input and '784' up to the demensions of the data

#Create Variable Objects for the weights and biases of Softmax Regression Model.We firstly update these with zero.
W = tf.Variable(tf.zeros([784, 10]))#the shape of W is [784,10],the number of demensions and type.
b = tf.Variable(tf.zeros([10]))
#We use function softmax() which belonging to tf.nn to calculate y
#tf.matmul() is the function using to calculate the result of the matrix multiplication
y = tf.nn.softmax(tf.matmul(x, W) + b)

#Here we use cross-entropy as the loss function
y_ = tf.placeholder(tf.float32, [None, 10])
#calculate the cross-entry
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
#tf.reduce_sum is the function using to calculate the sum and tf.reduce_mean using to calculate the average of every batch
#the second parameter is used to demensionality reduction and the '1'means the demension you wants

#the Optimization algorithm using to change the weights
#tf.train.GradientDescentOptimizer is a packaged optimizer and set the learning rate to 0.5,the optimal object is cross-entropy

#Use function tf.global_variables_initializer().run() to start iterative training to execute operation train-step
tf.global_variables_initializer().run()

#everytime,produce a mini-batch consisting of 100 randly drawing samples and feeds them toplaceholder and train.

for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
train_step.run({x: batch_xs, y_: batch_ys})

#calculate the accuracy
#true or false judgement
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))

#transform the data type 'Bool' to 'float32' and calculate the average value
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))

• 本文已收录于以下专栏：

举报原因： 您举报文章：tensorflow 第一个程序MNIST手写数字识别（Softmax Regression实现） 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)