はじめてのKerasと深層学習

先日、MeetupでKerasと深層学習の勉強をしてきました。 参加したのはこのMeetup: www.meetup.com

内容

Meetupとして以下の3つのTutorialを用意していて、そのうちの1つのDeep learningに関するTutorialを受けてきました。

  1. Working with Binary Data
  2. Sqlite3 and PEP249: A Beginner's Course
  3. Intro to Deep Learning with Keras

講義用のスライドとGithubのrepositoryもシェアされているので、貼り付けておきます。

GitHub - Dataweekends/intro_deep_learning_sf_python_meetup: Repository for the Python meetup tutorial in SF April 2017

www.slideshare.net

内容は、Kerasを使ってMNISTの手書き数字を認識する深層学習のモデルを作るというもの。 後で知りましたが、これはKerasに含まれるサンプルコードのひとつのようです。。 サンプルコードをExercise形式で、順に説明を含めながら読み解いていく形の講義でした。

コードと説明(インライン)

説明というほどのものでもないのですが、自分の理解のためのメモ書きを含めたコードが以下になります。

# 必要moduleのimport
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop
from keras.utils import to_categorical
# the data, shuffled and split between train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data('/tmp/mnist.npz')
# 60000枚の白黒画像 (28pixel x 28pixel)
print("X_train shape:", X_train.shape)
# 10000枚の白黒画像 (28pixel x 28pixel)
print("X_test shape:", X_test.shape)
# 1画素 unsigned int 8 bit (256階調)
print("Data type:", X_train.dtype)
# Exercise 1:
# Reshape your data so that each image becomes a long vector
# Your code here
# uint8の2次元配列を1次元に展開(784次元のベクトル)
X_train = X_train.reshape(60000, 784)
X_test = X_test.reshape(10000, 784)
# Exercise 2:
# change the type of the input vectors to be 'float32'
# and rescale them so that the values are between 0 and 1
# Your code here:
# uint8をfloat32に変換
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
# 0~255の階調データを1, 0に2値化(binary)
X_train /= 255
X_test /= 255
# Exercise 3:
# convert class vectors to binary class matrices
# using the keras.utils.to_categorical function
# Your code here:
# to_categorical(y, nb_classes=None):  0~(nb_classes-1)までを持つクラスベクトルyをバイナリのクラス行列に変換
# 0~9をもつクラスベクトルy_trainをバイナリのクラス行列に変換
# ex: 5 -> 1_0000, 8 -> 1000_0000
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# Exercise 4:
# Define a fully connected model using the Sequential API
# https://keras.io/getting-started/sequential-model-guide/
# Choose your architecture as you please
# Your code here:
# Sequentialは層の線形スタック
model = Sequential()
# addで層を追加できる。Denseは全結合ニューラルネットワークレイヤー
# ReLUを活性化関数にinput 784次元ベクトルにを512次元ベクトルに
model.add(Dense(512, activation='relu', input_shape=(784,)))
# Dropout 20%の入力を0として扱い過学習を防止(汎化促進)
model.add(Dropout(0.2))
# ReLUを活性化関数として層を追加
model.add(Dense(512, activation='relu'))
# Dropout 20%の入力を0として扱い過学習を防止(汎化促進)
model.add(Dropout(0.2))
# softmaxを出力層の活性化関数にすることで
# ニューラルネットワークの出力があたかもあるクラスに属する確率を表しているとして学習させることができる
model.add(Dense(10, activation='softmax'))

model.summary()
# Exercise 5:
# Compile your model using an optimizer of your choice
# make sure to display the accuracy metric
# https://keras.io/optimizers/
# Your code here:
# 誤差関数(損失関数)としてクロスエントロピー関数を設定
# 最適化(モデルの予測値と実際の値との誤差から、パラメータ(重み)を更新すること)にRMSpropを使う。
model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy'])
# Exercise 6:
# Fit the model on the training data. Use 30% of the
# data as validation. Experiment with different batch sizes
# and number of epochs. Save the history of training and print it.
# Your code here:
# X_train: 入力となるnumpy配列、y_train: ラベルとなるnumpy配列
# batch_size: 設定したサンプル数ごとに勾配の更新
# epochs: モデルを学習するエポック数
# verbose: 0 とすると標準出力にログを出力しません. 1 の場合はログをプログレスバーで標準出力
# validation_split: float (0. < x < 1) 型で, 検証のデータとして使うデータの割合
history = model.fit(X_train, y_train, batch_size=1024, epochs=10, verbose=1, validation_split=0.3)

print(history.history)
# Exercise 7:
# Calculate the score on the test data using `model.evaluate`
# Your code here:
# バリデーションデータによる評価とloss/accuracyの確認
score = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

所感

Kerasを使ってみての感想は、複雑なモデルを簡単に作れちゃうんだな。という印象。(深層学習的に複雑なモデル、という意味ではなく)
ただ深層学習の素人だったので、1行1行何をやっているのかを理解するが非常に大変でした。専門用語も知らないものが多い上に英語だったので、残念ながら講義にはついていけなかったのが実際です。
家に戻った後の復習として、以下のサイトとKerasのDocumentを参考に、なんとなく理解が追いついた感じです。
何はともあれ、新しいものに触れるいい機会だったので、引き続き深層学習の勉強に取り組みたいと思います。

高卒でもわかる機械学習 (0) 前置き – 頭の中に思い浮かべた時には

おまけ

同じMeetup内で講義された資料もせっかくなので貼り付けておきます。 自分も後で読んでみようと思います。

https://bradfieldcs.com/sfpython/

[Python] SF Python Project Night 4/19/2017: Working with Binary Data - Pastebin.com