通过MNIST熟悉Keras——《TensorFlow 实战》读书笔记
Tensorflow 的使用者虽多,但真的很难用。幸亏有基于TF和Theano的高层框架Keras
(不幸的是Theano已经停止更新了)。我们通过MNIST来熟悉一下Keras。
先推荐一个学习线性代数的教程http://www.bilibili.com/video/av6731067/,不管你多忙也请看上面这个视频。
3Blue1Brown制作,深入浅出、直观明了地分享数学之美。
下面的代码来源于keras examples
1 | '''Trains a simple deep NN on the MNIST dataset. |
Using TensorFlow backend.
0x01 读取数据库
下面代码执行的时候会自动下载https://s3.amazonaws.com/img-datasets/mnist.npz
到~/.keras/datasets
目录(自动下载过程不支持断点续传,如果一次下载没成功就会一直报错,可以用wget -c
或其它下载软件进行下载)。如果你用Windows系统,请直接按Alt+F4
1 | # the data, shuffled and split between train and test sets |
0x02 定义变量
很奇怪现在定义常量都不用大写字母了嘛>_<
1 | batch_size = 128 |
60000 train samples
10000 test samples
0x03 配置模型
用Keras来配置模型真的很简单,一层一层的add进去就可以了
1 | # convert class vectors to binary class matrices |
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_1 (Dense) (None, 512) 401920
_________________________________________________________________
dropout_1 (Dropout) (None, 512) 0
_________________________________________________________________
dense_2 (Dense) (None, 512) 262656
_________________________________________________________________
dropout_2 (Dropout) (None, 512) 0
_________________________________________________________________
dense_3 (Dense) (None, 10) 5130
=================================================================
Total params: 669,706
Trainable params: 669,706
Non-trainable params: 0
_________________________________________________________________
0x04 开始训练
1 | history = model.fit(x_train, y_train, |
Train on 60000 samples, validate on 10000 samples
Epoch 1/20
60000/60000 [==============================] - 5s - loss: 0.2453 - acc: 0.9253 - val_loss: 0.0976 - val_acc: 0.9697
Epoch 2/20
60000/60000 [==============================] - 5s - loss: 0.1009 - acc: 0.9693 - val_loss: 0.0836 - val_acc: 0.9742
Epoch 3/20
60000/60000 [==============================] - 5s - loss: 0.0749 - acc: 0.9770 - val_loss: 0.0924 - val_acc: 0.9731
Epoch 4/20
60000/60000 [==============================] - 5s - loss: 0.0601 - acc: 0.9820 - val_loss: 0.0820 - val_acc: 0.9771
Epoch 5/20
...
Epoch 19/20
60000/60000 [==============================] - 5s - loss: 0.0181 - acc: 0.9953 - val_loss: 0.1228 - val_acc: 0.9829
Epoch 20/20
60000/60000 [==============================] - 5s - loss: 0.0192 - acc: 0.9951 - val_loss: 0.1171 - val_acc: 0.9828
Test loss: 0.117063564365
Test accuracy: 0.9828