1.代码:
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets('data/', one_hot=True)
trainimg = mnist.train.images
trainlabel = mnist.train.labels
testimg = mnist.test.images
testlabel = mnist.test.labels
print (trainimg.shape)
print (trainlabel.shape)
print (testimg.shape)
print (testlabel.shape)
print (trainlabel[0])
x = tf.placeholder("float", [None, 784])
y = tf.placeholder("float", [None, 10])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
actv = tf.nn.softmax(tf.matmul(x, W) + b)
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(actv), reduction_indices=1))
learning_rate = 0.01
optm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
pred = tf.equal(tf.argmax(actv, 1), tf.argmax(y, 1))
accr = tf.reduce_mean(tf.cast(pred, "float"))
init = tf.global_variables_initializer()
training_epochs = 50
batch_size = 100
display_step = 5
sess = tf.Session()
sess.run(init)
for epoch in range(training_epochs):
avg_cost = 0.
num_batch = int(mnist.train.num_examples/batch_size)
for i in range(num_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(optm, feed_dict={x: batch_xs, y: batch_ys})
feeds = {x: batch_xs, y: batch_ys}
avg_cost += sess.run(cost, feed_dict=feeds)/num_batch
if epoch % display_step == 0:
feeds_train = {x: batch_xs, y: batch_ys}
feeds_test = {x: mnist.test.images, y: mnist.test.labels}
train_acc = sess.run(accr, feed_dict=feeds_train)
test_acc = sess.run(accr, feed_dict=feeds_test)
print ("Epoch: %03d/%03d cost: %.9f train_acc: %.3f test_acc: %.3f"
% (epoch, training_epochs, avg_cost, train_acc, test_acc))
print ("DONE")
2.测试:
2019-05-13 20:59:21.419000: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
Epoch: 000/050 cost: 1.177192063 train_acc: 0.820 test_acc: 0.855
Epoch: 005/050 cost: 0.440947708 train_acc: 0.870 test_acc: 0.895
Epoch: 010/050 cost: 0.383374388 train_acc: 0.940 test_acc: 0.904
Epoch: 015/050 cost: 0.357302828 train_acc: 0.870 test_acc: 0.909
Epoch: 020/050 cost: 0.341495150 train_acc: 0.940 test_acc: 0.913
Epoch: 025/050 cost: 0.330547747 train_acc: 0.960 test_acc: 0.913
Epoch: 030/050 cost: 0.322318969 train_acc: 0.940 test_acc: 0.916
Epoch: 035/050 cost: 0.315943215 train_acc: 0.960 test_acc: 0.917
Epoch: 040/050 cost: 0.310750899 train_acc: 0.940 test_acc: 0.918
Epoch: 045/050 cost: 0.306379970 train_acc: 0.930 test_acc: 0.919
DONE