Softmax Regression in TensorFlow

Softmax Regression

TensorFlow实现Softmax Regression识别手写数字,数据集用MINIST(Mixed National Institute of Standards and Technology database),其由几万张$28 \times 28$像素的手写数字组成,这些图片只包含灰度信息。我们的任务就是对这些图片进行分类,转成0~9共10类。

定义算法公式

在我们使用多分类任务时,通常需要使用Softmax Regression模型。它的工作原理很简单,将可以判定为某类的特征相加,然后将这些特征转化为判定是这一类的概率。上述特征可以通过一些简单的方法得到,比如对所有的像素求一个加权和,而权重是模型根据数据自动学习,训练出来的。即可以表示为

然后对所有特征计算softmax,即

其中softmax函数先对变量计算一个$\exp$函数,然后进行标准化(让所有类别输出的概率值和为1)。即

所以整个模型可以表示为

其TensorFlow的实现是

1
2
3
4
5
6
import tensorflow as tf
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)

首先载入TensorFlow库,并创建一个InteractiveSession,使用这个命令会将这个session注册为默认的session,之后的运算默认跑在这个session里,不同session之间的数据和运算应该都是互相独立的。接下来创建一个

784]```代表tensor的shape,这里None指不限条数的输入,784代表每条输入是一个784维的向量。接下来创建模型的weights和bias变量,```Variables```是用来存储模型参数的,不同于存储数据的tensor一旦使用掉就会消失,```Variables```在模型训练迭代中是持久化的,她可以长期存在并在每轮迭代中被更新。
1
2
3
4
5
6
7
8
9
10
11
12
13
14

## 定义损失函数
为了训练模型,一般需要定义一个 Loss Function来描述模型对问题的分类精度。Loss越小,代表模型的分类结果与真实值的偏差越小,也就是说模型越精确。
训练的目的就是不断将这个Loss减少,达到一个全局最优或者局部最优解。

对于多分类问题,通常使用 Cross-entropy 作为 Loss Function,用它来判断模型对真是概率分布估计的准确程度。其定义如下
$$
H_{y'}(y)= - \sum y'_i \log(y_i)
$$

在TensorFlow中,定义Cross-entropy的代码如下
```python
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y), reduction_indices=[1]))

先定义一个

1
2
3
4
5
6
7
8
9

## 选择优化方法并训练模型
有了算法定义和损失函数,定义一个优化方法便可以开始训练。这里采用随机梯度下降(Stochastic Gradient Descent, SGD)算法。TensorFlow用SGD训练模型的的实现是
```python
train_step = tf.train.GradientDescentOptimizier(0.5).moinimize(cross_entropy)
tf.global_variables_initializer().run()
for i in rang(1000):
batch_xs, batch_ys = mnist.train.next_batch9100)
train_step.run({x: batch_xs, y_: batch_ys})

TensorFlow可以根据我们定义的整个计算图自动求导,并根据反向传播(Back Propagation)算法进行训练,在每一轮迭代时更新参数来减少Loss。
这里每次都随机从训练集中抽取100条样本构成一个mini-batch,并feed给

1
2
3
4
5
6
7

## 评测算法
完成训练后,还需要对模型的准确率进行验证。
```python
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}))

将测试数据的特征和Label输入评测流程

Regression在MNIST数据进行分类识别,在测试集上的平均准确率可达92%左右。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64


## 完整代码
```python
"""A very simple MNIST classifier.

See extensive documentation at
https://www.tensorflow.org/get_started/mnist/beginners
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None


def main(_):
# Import data
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

# Create the model
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b

# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])

# The raw formulation of cross-entropy,
# tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)), reduction_indices=[1]))
# can be numerically unstable.
#
# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw
# outputs of 'y', and then average across the batch.
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
# Train
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})

# Test trained model
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}))

if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, default='./mnist/input_data',
help='Directory for storing input data')
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

Reference