思路比较简单,直接结合着注释看代码!
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#导入mnist数据
mnist = input_data.read_data_sets("../data/mnsit", one_hot=True)
# Parameters设置参数,进行批梯度下降
learning_rate = 0.01
training_epochs = 25
batch_size = 100
display_step = 1
# tf Graph Input
x = tf.placeholder(tf.float32, [None, 784]) # mnist data image of shape 28*28=784
y = tf.placeholder(tf.float32, [None, 10]) # 0-9 digits recognition => 10 classes
# Set model weights
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# Construct model 利用参数创建预测模型
pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax
entropy = tf.nn.softmax_cross_entropy_with_logits(labels = y, logits = pred)
cost = tf.reduce_mean(entropy)
# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)#cost 可以看做是损失函数
# Initializing the variables
init = tf.global_variables_initializer()
# Launch the graph
with tf.Session() as sess:
sess.run(init)
# Training cycle
for epoch in range(training_epochs):
avg_cost = 0. #float
total_batch = int(mnist.train.num_examples/batch_size)
# Loop over all batches
for i in range(total_batch):
#分批次获得数据
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Run optimization op (backprop) and cost op (to get loss value) # 这里返回一个[optimizer,cost]的list, 其中 _代表optimizer,cost代表bath cost的值
_, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,
y: batch_ys})
# Compute average loss
avg_cost += c / total_batch
# Display logs per epoch step
if (epoch+1) % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
print("Optimization Finished!")
# Test model 得到模型的准确性
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
# Calculate accuracy correct_prediction本来是bool型的tensor,Tensor("Equal_6:0", shape=(?,), dtype=bool) 将correct_prediction转换成浮点型
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
网友评论