LoginSignup
4
4

More than 3 years have passed since last update.

Google Colaboratoryを使ってMNISTデータの学習などをやってみる①

Posted at

はじめに

前から気になっていたGoogle Colaboratoryを使ってみることにしました。
最初とはいえ、多少は実践的なことをしたいので、MNISTデータを使ったCNNモデルの作成と、LIMEを使った説明可能性をやってみたいと思います。

Colaboratoryを使う際の全般的な解説は以下をご参照ください。
【秒速で無料GPUを使う】深層学習実践Tips on Colaboratory

Google DriveにColaboratoryを接続する

私はGoogle Driveに趣味のファイルをあげているので、ここを作業するベースの場所とします。

Google Drive の「+New」をクリックした、「Connect more apps」を選びます。

000_最初の新規作成.png

そして、Colaboratoryを検索して、「Connect」をクリックし、Google DriveからColaboratoryを使えるようにします。
001_Colaboratoryの接続.png

そうすると、ファイルを新規作成する「+New」からColaboratory用のファイルを選択できます。
新規の空白のipynbファイルを早速作ります。
002_Make_New_Colaboratory.png

ランタイムのタイプをGPUに変更することを忘れないようにしましょう。
003_ランタイムのタイプ.png

004_GPU選択.png

CNNのコードを書く

このファイルに、
Keras公式 CNN MNISTのページにあるコードを記載します。
まずはkerasのインポート、MNISTデータへの前処理、そしてCNNモデルの定義まで。

from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K

batch_size = 128
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

公式ページのコードのままだと、モデルの構造が出力されないので、以下のコードを追加しました。

model.summary()

このようなモデルができています。
005_model_summary().png

早速実行させてみましょう。学習の履歴をあとで表示できるよう、Keras公式ページのコードに少しだけ手を加えています。

%%time
history = model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))

次のような結果が得られました。
010_Coraboratory_学習時間.png

1分弱で計算が終わっています!
あとはモデルの精度検証と、学習履歴の表示です。

# モデルの評価
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

Test loss: 0.027914887178201026
Test accuracy: 0.9934

テストデータに対する精度は99.34%出ていますね。

import matplotlib.pyplot as plt
# 学習の履歴をグラフ化
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('Accuracy')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

011_history_plot.png

テストデータに対しても最初のエポックからそれなりの結果が出ていますね。

私のローカルPCとの比較

それにしても、無料でGPUが使えて、この速度で計算できるのはすごいです。
ちなみに、同じコードを私のPC(XPS13, Intel CORE i5なので比較対象とし貧弱ですが、、)での結果は
021_my_local_PC.png

私のPCでは約1時間20分もかかってます。Colaboratoryは80倍速いです!
軽いデータで、深層学習を色々試すならColaboratoryを使うのが時間の節約です。

今回はここまで。
次回はモデル式を保存したり、LIMEを適用したりしたいと思います。

4
4
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
4
4