41
66

More than 5 years have passed since last update.

kerasのよく使うやつメモ

Posted at

keras.utils.to_categorical

one-hotなベクトルつくるやつ
↓のようなの。識別系で使う。

>>> keras.utils.to_categorical(1, 5)
array([ 0.,  1.,  0.,  0.,  0.])

>>> keras.utils.to_categorical(4, 5)
array([ 0.,  0.,  0.,  0.,  1.])

keras.layers.concatenate

レイヤーをマージする
複数の入力を取りまとめたりする。

hoge_input = Input(shape=(10,), name='hoge_input')
fuga_input = Input(shape=(2,), name='fuga_input')
x = keras.layers.concatenate([hoge_input, fuga_input])

keras.layers.Dense

全結合のレイヤーをつくる。中間層を追加するときなどに基本使う。

x = Dense(128, activation='relu')(x)

reluとかsigmoid

活性化関数。
以下などがわかりやすい。
https://qiita.com/hokekiyoo/items/bf7be0ae3bf4aa3905ef
https://qiita.com/namitop/items/d3d5091c7d0ab669195f

softmax

活性化関数。最終レイヤーで識別系をするときに基本使う。

hoge_output = Dense(10, activation='softmax', name='hoge_output')(x)

model.compileするときのoptimizerとかlossの選び方

公式をみるのがわかりやすい。
https://keras.io/ja/optimizers/
https://keras.io/ja/objectives/

keras.utils.vis_utils.model_to_dot

モデルを図にしてくれる。

SS_ 2017-11-30 17.18.46.png

学習曲線の表示

batch_size = 128
epochs = 2000
stack = model.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)

x = range(epochs)
plt.plot(x, stack.history['acc'], label="acc")
plt.title("accuracy")
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()

plt.plot(x, stack.history['loss'], label="loss")
plt.title("loss")
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()

SS_ 2017-11-30 18.00.22.png

テスト(model.evaluate)

score = model.evaluate(X_test, Y_test, batch_size=batch_size)
list(zip(model.metrics_names, score))

model.metrics_namesでscoreのラベルが取れるので、zipしてlistして見やすくしてる

モデルの保存と読み込み

h5pyが必要。pip install h5py

model.save('model.h5')
model = keras.models.load_model('model.h5')
41
66
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
41
66