keras quick start

keras的一个简单例子

使用keras以下几步,首先Sequential model

1
2
from keras.models import Sequential
model = Sequential()

使用.add()来添加你所需要layers:

1
2
3
4
5
6
from keras.layers import Dense, Activation

model.add(Dense(output_dim=64, input_dim=100))
model.add(Activation("relu"))
model.add(Dense(output_dim=10))
model.add(Activation("softmax"))

使用.compile()开始学习过程:

1
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])

如果有需要可以对optimizer进行设置,如:

1
2
from keras.optimizers import SGD
model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.01, momentum=0.9, nesterov=True))

开始训练:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    model.fit(X_train, Y_train, nb_epoch=5, batch_size=32)
```
对于不适合存放在内存中的数据集,可以使用
```python
model.train_on_batch(X_batch, Y_batch)
```
最后对模型进行评估:
```python
loss_and_metrics = model.evaluate(X_test, Y_test, batch_size=32)
```
或者预测:
```python
classes = model.predict_classes(X_test, batch_size=32)
proba = model.predict_proba(X_test, batch_size=32)

参考文献:

Keras Documentation