目次
Google Colabを用いたDeep Learningのファッション画像認識
Deep Learningは理論を理解するのは時間がかかるケースがあるからまずは実践をしてみようという内容の記事だ
理論難しいから後回しですね
Deep Learningを説明してくれているサイトは多いのですが、Deep Learningを実装するにはPythonの習得、機械学習の理解、Deep Learingの理解、Deep Learningフレームの理解、そして実装という順序になるので時間がかかる問題があります。
Deep Learningの実装はゲームと同じような面があり、習うより慣れろの面もあります。そこでこの記事では実際に動くコードを見せて、コードに関連する説明を載せている形にしています。
Google Colabを使うための準備
Google Accountの作成
Google Colabを使用するにはGoogle Accountが必要だぞ
アカウント作るの面倒ですね・・・
最初だけだから我慢してくれ。アカウントを持っている人はこのステップは不要だ!!
下記リンクをクリックしてください。
下記のような画面がでるので”Google アカウントを作成する”をクリックします。

次のベージで名前、ユーザー名、パスワードを設定します。

本人確認のため、電話番号の設定を尋ねられます。

電話番号の確認をされたあとに送られた確認コードを入力します。

生年月日、性別などの情報を入力します。

利用規約の同意画面が出ます。

ファッションデータの画像識別
いよいよファッション画像の識別ですね!!
コードが多くなるから手を動かしながら読み直すことをおすすめする
下記がFashion データの画像識別のまとめつぶやきです。
Fashion MNISTのColab
– 画像の前処理時のピクセルの可視化
– 分類が正しく動作しているかの確認
– 推論が間違った場合にすぐに判断できるようにするためのコード記述あり
– クラスごとに画像と推論結果の確認が可能https://t.co/Q5Y3SHPYNU pic.twitter.com/fHbbUPYB0X— Yurui☁DeepLearning (@DeepYurui) March 7, 2020
実際のコードについて
画像データはコードから読み込むことができます。自分でファイルを用意する必要がありません。
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
画像の最大値が255のため画像データを0-1の範囲にして学習を容易にできるように前処理しています。
train_images = train_images / 255.0
test_images = test_images / 255.0
画像描画ライブラリmatplotlibを用いて描画することで下記のコードで画像データを確認できます。
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()

下記の種類のファッション画像の種類は下記になります。
‘T-shirt/top’, ‘Trouser’, ‘Pullover’, ‘Dress’, ‘Coat’, ‘Sandal’, ‘Shirt’, ‘Sneaker’, ‘Bag’, ‘Ankle boot’
下記のコードで確認できるため、サンプルベースですが学習、推論に使用する画像データが確認できます。
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show()

Kerasのコードを使用すると簡単にモデル定義ができます。
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10)
])
今回作成したモデルは下記です。

学習のための設定です。学習の進み具合を調整するOptimizerの設定。学習の際に正解データとの剥離度合いを図るLossと精度評価のための指標を”metrics”で設定します。
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
下記のコードで学習できます。kerasはこの点がシンプルに学習できます。
model.fit(train_images, train_labels, epochs=10)
モデルの性能を評価します。
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)
学習したモデルで推論します。推論の値が0-1の範囲になるようにSoftmaxレイヤーを追加します。
probability_model = tf.keras.Sequential([model,
tf.keras.layers.Softmax()])
下記で水遁したクラスの画像と実際に推論したクラスと正解のクラスが一致しているかを視覚的に確認するための関数を作成します。
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array, true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color)
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array, true_label[i]
plt.grid(False)
plt.xticks(range(10))
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')
下記のコードで上記で定義した関数を実行します。
i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i], test_labels)
plt.show()

下記のコードの場合は正解とは異なるクラスを推論している例になります。
i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i], test_labels)
plt.show()

上記のコードを応用して、各クラスの性能を下記コードで見てみます。
# Plot the first X test images, their predicted labels, and the true labels.
# Color correct predictions in blue and incorrect predictions in red.
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions[i], test_labels)
plt.tight_layout()
plt.show()

単一の画像を入力する場合はバッチの次元がないので追加する必要があります。
# Add the image to a batch where it's the only member.
img = (np.expand_dims(img,0))
print(img.shape)
バッチの次元を追加することで推論が可能になります。
predictions_single = probability_model.predict(img)
print(predictions_single)
数値ラベル情報を変換するための`class_names`を設定しておくと数値情報ではなくクラス名で結果を確認できます。
plot_value_array(1, predictions_single[0], test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)

下記のGoogle Colabで実際に試してみましょう。
ここまで来たら実際に試してみよう
下記リンクをクリックしてGoogle Colabのボタンを押すとGoogle Accountがあれば実行できます。
https://colab.research.google.com/drive/1rmzOJK5G7aS7g3leB6ucKL_pwTqDwklc
