MNIST数据集入门

来源:互联网 发布:淘宝上买手机 编辑:程序博客网 时间:2024/06/05 16:02

学习文章地址:

http://www.tensorfly.cn/tfdoc/tutorials/mnist_beginners.html

解读

1、Softmax回归介绍


i:数字类别,如i=6,则代表数字6的类别

j:图片像素索引

公式解释:图片被判断为数字i(如6)的证据值为,将(该像素被判断为数字i的权重 * 图像的每个像素值(0或1))的乘积求和,然后再加上数字i的相应偏置量


图形表示:


公式表示:(感叹线性代数之美)



有了这么好的数学工具,tensorflow封装的方法就很简单了:

import tensorflow as tfx = tf.placeholder("float", [None, 784])W = tf.Variable(tf.zeros([784,10]))b = tf.Variable(tf.zeros([10]))y = tf.nn.softmax(tf.matmul(x,W) + b)

完整代码:

import tensorflow as tfimport input_datamnist = input_data.read_data_sets("MNIST_data/", one_hot=True)x = tf.placeholder("float", [None, 784])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("float", [None,10])#交叉熵cross_entropy = -tf.reduce_sum(y_*tf.log(y))#反向传播算法不断地修改变量以降低成本train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)#初始化变量init = tf.global_variables_initializer()#执行初始化sess = tf.Session()sess.run(init)#训练for i in range(1000):  batch_xs, batch_ys = mnist.train.next_batch(100)  sess.run(train_step, feed_dict={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, "float"))print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))#关闭Seessionsess.close()

输出:

0.916



原创粉丝点击