keras的基本用法(二)——定义分类器

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

本文主要介绍Keras的一些基本用法。

  • Demo
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
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import RMSprop

# 加载数据集
(X_train, y_train), (X_test, y_test) = mnist.load_data()

# 数据集reshape, -1表示该参数不指定, 系统通过推断来获得
X_train = X_train.reshape(X_train.shape[0], -1) / 255.0
X_test = X_test.reshape(X_test.shape[0], -1) / 255.0

# 将label变为向量
y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)


# 构建分类器
model = Sequential([
Dense(32, input_dim = 784),
Activation('relu'),
Dense(10),
Activation('softmax')
])

# 选择并定义优化求解方法
rmsprop = RMSprop(lr = 0.001, rho = 0.9, epsilon = 1e-8, decay = 0.0)

# 选择损失函数、求解方法、度量方法
model.compile(optimizer = rmsprop, loss = 'categorical_crossentropy', metrics = ['accuracy'])

# 训练模型
model.fit(X_train, y_train, epochs = 2, batch_size = 32)

# 评估模型
loss, accuracy = model.evaluate(X_test, y_test)

print ''
print 'loss: ', loss
print 'accuracy: ', accuracy
  • 结果
1
2
3
4
5
6
7
8
Using TensorFlow backend.
Epoch 1/2
60000/60000 [==============================] - 2s - loss: 0.3382 - acc: 0.9048
Epoch 2/2
60000/60000 [==============================] - 2s - loss: 0.1913 - acc: 0.9454
7680/10000 [======================>.......] - ETA: 0s
loss: 0.16181669073
accuracy: 0.9535

参考资料

  1. https://www.youtube.com/user/MorvanZhou
如果有收获,可以请我喝杯咖啡!