AI 事始め9:いよいよ Get Started with TensorFlow :Fashion MNIST 編
まだまだ寄り道したい処はありますが、Get Started with TensorFlowに進むことにします。Start with these beginner-friendly notebook examples, then read the TensorFlow Keras guide.と書かれてますので、訳も分からず、冒頭のコードをコピーして、Anaconda Navigatorを起動して、既に作成したtensorflowの環境から、Open with Jyupiter Notebookを開き、Homeの[New]から新しい[Python 3]を選択して新しいノートを開き、貼り付けました。そのまま、RUNすると、まともに動作しているように見えます。
これを見ただけでは、何をやっているのか、皆目見当もつきません。気になりますが放置します。
1. Basic classificationを覘いてみました。
少し、詳しく書かれています、Fashion MNIST というdatasetを用いた例題のようです。
同様に、新しいJyupiter Notebookを開き、愚直にコピペしてJyupiter Notebookを作成します。コピペして、[Shift][Enter]で、即実行され、デバッグも容易そうです。
import matplotlib.pyplot as plt の所でエラーです。まだ、matplotlibを使用しているAnaconda環境にインストールしていませんでした。使用しているtensorflow環境でTerminalを開き、
pip install matplotlib と入力してインストールしました。
再度、Jyupiter Notebookを開いて、コードを加えていきます。
model.fit(train_images, train_labels, epochs=5)を実行させると、
<tensorflow.python.keras.callbacks.History at 0x23196160f98>
と吐き出して、エラーかな?。お手上げか?無視して、次のコードを入力して、[Shift][Enter]すると、正常動作している。エラーでは無いようです。
最後まで、エラー無しで入力でき、Basic classificationに記述されている結果とも、細かな数字の差異はありますが、動作は一致しています。(当たり前かな?)環境の準備段階では書類間に不整合がありましたので、一抹の不安があったのですが、お見事です。ひと昔前では考えられないような複雑な深層学習を、たったこれだけの記述で、中古のPCでも2分掛からずに実行できてしまうことに驚愕しました。
先人達の知能に敬意を払うとともに、このような足跡を残してくれた事に感謝します。動作の仕組みは皆目わかりませんが、シロウトでもフォローできた備忘録として、作成したJyupiter Notebookを残しておきます。
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras # 最新のtensorflowにはkerasが同梱されているのかな?
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
train_images.shape
len(train_labels)
train_labels
test_images.shape
len(test_labels)
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
train_images = train_images / 255.0
test_images = test_images / 255.0
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]])
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer=tf.train.AdamOptimizer(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5)
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)
predictions = model.predict(test_images)
predictions[0]
np.argmax(predictions[0])
test_labels[0]
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array[i], 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[i], true_label[i]
plt.grid(False)
plt.xticks([])
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, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions, test_labels)
i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions, test_labels)
# Plot the first X test images, their predicted label, and the true label
# Color correct predictions in blue, 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, test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions, test_labels)
# Grab an image from the test dataset
img = test_images[0]
print(img.shape)
# Add the image to a batch where it's the only member.
img = (np.expand_dims(img,0))
print(img.shape)
predictions_single = model.predict(img)
print(predictions_single)
plot_value_array(0, predictions_single, test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)
np.argmax(predictions_single[0])
#@title MIT License
#
# Copyright (c) 2017 François Chollet
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.