文章作者: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
# 加載數(shù)據(jù)集
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# 數(shù)據(jù)集reshape, -1表示該參數(shù)不指定, 系統(tǒng)通過推斷來獲得
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ōu)橄蛄?y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)
# 構(gòu)建分類器
model = Sequential([
Dense(32, input_dim = 784),
Activation('relu'),
Dense(10),
Activation('softmax')
])
# 選擇并定義優(yōu)化求解方法
rmsprop = RMSprop(lr = 0.001, rho = 0.9, epsilon = 1e-8, decay = 0.0)
# 選擇損失函數(shù)假瞬、求解方法憨奸、度量方法
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
- 結(jié)果
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