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

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

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

  • Demo
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 'loss: ', loss
print 'accuracy: ', accuracy
  • 结果
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: 0sloss:  0.16181669073
accuracy:  0.9535
    原文作者:SnailTyan
    原文地址: https://www.jianshu.com/p/a931fa1975b7
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞