Osomaki67のブログ

個人的な備忘録兼日記にしたいと思います。

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すると、まともに動作しているように見えます。

f:id:Osomaki67:20181015151210p:plain

 これを見ただけでは、何をやっているのか、皆目見当もつきません。気になりますが放置します。

 

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を残しておきます。

In [31]:
# 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__)
 
1.11.0
In [3]:
fashion_mnist = keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
In [4]:
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
In [5]:
train_images.shape
Out[5]:
(60000, 28, 28)
In [6]:
len(train_labels)
Out[6]:
60000
In [7]:
train_labels
Out[7]:
array([9, 0, 0, ..., 3, 0, 5], dtype=uint8)
In [8]:
test_images.shape
Out[8]:
(10000, 28, 28)
In [9]:
len(test_labels)
Out[9]:
10000
In [10]:
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
 
In [11]:
train_images = train_images / 255.0

test_images = test_images / 255.0
In [12]:
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]])
 
In [13]:
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)
])
In [14]:
model.compile(optimizer=tf.train.AdamOptimizer(), 
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
In [15]:
model.fit(train_images, train_labels, epochs=5)
 
Epoch 1/5
60000/60000 [==============================] - 3s 44us/step - loss: 0.4964 - acc: 0.8258
Epoch 2/5
60000/60000 [==============================] - 2s 40us/step - loss: 0.3783 - acc: 0.8629
Epoch 3/5
60000/60000 [==============================] - 2s 39us/step - loss: 0.3395 - acc: 0.8760
Epoch 4/5
60000/60000 [==============================] - 3s 42us/step - loss: 0.3153 - acc: 0.8842
Epoch 5/5
60000/60000 [==============================] - 2s 40us/step - loss: 0.2980 - acc: 0.8894
Out[15]:
<tensorflow.python.keras.callbacks.History at 0x252ec4e5390>
In [16]:
test_loss, test_acc = model.evaluate(test_images, test_labels)

print('Test accuracy:', test_acc)
 
10000/10000 [==============================] - 0s 27us/step
Test accuracy: 0.8561
In [17]:
predictions = model.predict(test_images)
In [18]:
predictions[0]
Out[18]:
array([1.7286059e-06, 8.9293950e-10, 2.2988564e-09, 5.8621535e-10,
       1.2936779e-07, 2.2598982e-02, 2.5559504e-07, 1.8681921e-01,
       4.3079314e-07, 7.9057926e-01], dtype=float32)
In [19]:
np.argmax(predictions[0])
Out[19]:
9
In [20]:
test_labels[0]
Out[20]:
9
In [21]:
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')
In [22]:
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)
 
In [23]:
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)
 
In [24]:
# 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)
 
In [50]:
# Grab an image from the test dataset
img = test_images[0]

print(img.shape)
 
(28, 28)
In [51]:
# Add the image to a batch where it's the only member.
img = (np.expand_dims(img,0))

print(img.shape)
 
(1, 28, 28)
In [53]:
plot_value_array(0, predictions_single, test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)
 
In [54]:
np.argmax(predictions_single[0])
Out[54]:
9
In [30]:
#@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.