如同其他语言的"hello world",机器学习的hello world就是MNIST。这里讲采用Softmax Regression模型训练MNIST。

MNIST数据托管在Yann LeCun网站,首先下载并读取数据

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

MNIST将数据分为3部分:

  • mnist.train:55,000份

  • mnist.test: 10,000份

  • mnist.validation: 5,000份

每个数据由两部分组成:数字图片x,标签y

mnist.train.images
mnist.train.labels

每个图片是28x28的像素矩阵,将其flat为784维的向量。尽管这丢弃了2D的结构信息,但是对于目前使用的softmax regression模型不会有很大影响。

训练MNIST模型

首先导入tensorflow

import tensorflow as tf

创建输入量x

x = tf.placeholder(tf.float32, [None, 784])

设置模型参数

W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

创建softmax regression模型

y = tf.nn.softmax(tf.matmul(x, W) + b)

创建输入量y_

y_ = tf.placeholder(tf.float32, [None, 10])

定义损失函数

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

定义训练模型

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

创建tf的session

sess = tf.InteractiveSession()

初始化参数

tf.global_variables_initializer().run()

训练模型1000

for _ 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, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

results matching ""

    No results matching ""