Tensorflow 实现 Softmax Regression 识别手写数字 1 2 3 4 5 from tensorflow.examples.tutorials.mnist import input_datamnist = 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)
定义算法公式 y = softmax(Wx + b) 1 2 3 import tensorflow as tfsess = tf.InteractiveSession() x = tf.placeholder(tf.float32, [None , 784 ])
InteractiveSession
该方法将 sess
注册为默认的session
1 2 3 W = tf.Variable(tf.zeros([784 , 10 ])) b = tf.Variable(tf.zeros([10 ])) y = tf.nn.softmax(tf.matmul(x, W) + b)
定义 loss,选定优化器 1 2 y_ = tf.placeholder(tf.float32, [None , 10 ]) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1 ]))
tf.reduce_mean(x) 如果不指定第二个参数,那么就在所有的元素中取平均值
tf.reduce_mean(x, 0)
指定第二个参数为 0,则第一维的元素取平均值,即每一列求平均值
沿着reduction_indices
所指定的维度求和。
1 train_step = tf.train.GradientDescentOptimizer(0.5 ).minimize(cross_entropy)
reduce_mean
取均值
GradientDescentOptimizer
梯度下降优化器
对数据进行迭代训练 1 2 3 4 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})
评测准确率 1 2 3 correct_predicton = tf.equal(tf.argmax(y, 1 ), tf.argmax(y_, 1 )) accuracy = tf.reduce_mean(tf.cast(correct_predicton, tf.float32)) print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))