#Softmax Regression识别手写数字 import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/",one_hot=True) print(mnist.train.images.shape,mnist.train.labels.shape) print(mnist.test.images.shape,mnist.test.labels.shape) print(mnist.validation.images.shape,mnist.validation.labels.shape) sess = tf.InteractiveSession() #第一步,定义算法公式 x = tf.placeholder(tf.float32,[None,784]) #None表示任意维数 W = tf.Variable(tf.zeros([784,10])) #初始权重 b = tf.Variable(tf.zeros([10]))#初始偏置 y = tf.nn.softmax(tf.matmul(x,W)+b) #第二步,定义损失函数 y_ = tf.placeholder(tf.float32,[None,10]) cross_entropy = -1*tf.reduce_sum(y_*tf.log(y)) #梯度下降最小化交叉熵 train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) #第三步,迭代地对数据进行训练 tf.global_variables_initializer().run() for i in range(1000): batch_xs,batch_ys = mnist.train.next_batch(100) train_step.run({x:batch_xs,y_:batch_ys}) #第四步,在测试集或验证集上对准确率进行评判 correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels})) print(accuracy.eval({x:mnist.validation.images,y_:mnist.validation.labels}))
运行结果: