AI 事始め10:Get Started with TensorFlow :Fashion MNIST その2
Get Started with TensorFlowの冒頭のコードが気になります。1. Basic classificationのコードとは、model、model.compile、model.evaluateなどの記述が異なります。
先に作成した、Fashion MNISTのJyupiter Notebookを下記のように変更してみました。
<tensorflow.python.keras.callbacks.History at 0x252ec4e5390>のようなメッセージは出力されません。Trainの時間が長くなっています。精度も少し良くなっているように見えます。動作の仕組みに関して知識がゼロの状態では、なんですが、実験はできそうな感じですね。
In [1]:
# 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を変えてみました。
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
# ここの記述を変えてみました。
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5)
model.evaluate(test_images, test_labels)
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.
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.
AI 事始め8:ちょっと寄り道:ジュピターノートブックを使ってみた
Anaconda Navigatorには、Jupyter notebookというツールが付属しています。これをインストールして使ってみました。各Enviroment毎にインストールが必要みたいですが、インストールが終了したEnviromentのJupyter notebookを起動する方法は、2つあるようです。
1つは、Anaconda NavigatorのHomeから、Applications on **** を確認して、Launchする方法。
もう1つは、Anaconda NavigatorのEnviromentsで、使用するEnviroment、例えば、tfgggから、Open with Jupyter notebookを選択すると、コマンドプロンプトが立ち上がり、ブラウザで選択した環境でのHomeが表示されます。このHomeで、[New]のボタンから、Python 3を選択すると、ブラウザの新しいタブが開き、新しいUntitled Jupyter notebookが開始されるようです。[Untitled]の部分をクリックすると、名前が付けられます。
AI 事始め7で作成した計算速度表示のスクリプトをコピペで、新しいJupyter notebookに張り付けます。Runボタンを押すと、少し、間をおいてから時間の表示を開始しました。測定結果は、スクリプトをTerminalで動作させた場合と大差ありませんが、tensorflowが吐き出しているMessageが表示されません。使い方が悪いのかもしれませんが、今後も気をつけて見ていきましょう。
AI 事始め7:ちょっと寄り道:tensorflow行列の表記とPythonのお勉強
tensorflow ハードウェア条件の確認をした時に、行列の表記と行列の掛け算が出現したので、整理して覚える。また、ついでに,shape=[2, 3]のa行列とshape=[3, 2]のb行列の掛け算 tf.matmul(a, b)のCPUのみでの計算速度を測定する。
まずは、表記を調べる。
# Constant 2-D tensor populated with scalar value -1.
tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]
[-1. -1. -1.]]
であるから、
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') => [ [1.0, 2.0, 3.0]
[4.0, 5.0, 6.0] ]
0行目が「[1.0, 2.0, 3.0]」、1行目が「[4.0, 5.0, 6.0]」となります。同様に、
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b') => [ [1.0, 2.0]
[3.0,4.0]
[5.0, 6.0] ]
0行目が「[1.0, 2.0]」、1行目が「[3.0,4.0]」、2行目が「[5.0, 6.0]」となります。
c = tf.matmul(a, b)は、これらの掛け算ですから、結果は2行2列になります。
[ [(1x1+2x3+3x5),(1x2+2x4+3x6)] => [ [22., 28.]
[(4x1+5x3+6x5),(4x2+5x4+6x6)] ] [49., 64.] ]
次に、Pythonのお勉強を兼ねて、tf.matmul(a, b)のCPUのみでの計算速度を測定するためのコード追加します。
tf.matmul(a, b)の計算を10000回実行する時間を、10回測定するコードにしました。
import datetime
import tensorflow as tf
# Creates a graph.
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
for j in range(10):
date_start = datetime.datetime.now()
for i in range(10000):
sess.run(c)
date_stop = datetime.datetime.now()
print(j+1,"th: ","Elapsed Time is ",date_stop - date_start)
実行結果は、下記でした。
1 th: Elapsed Time is 0:00:01.076265
2 th: Elapsed Time is 0:00:01.047991
3 th: Elapsed Time is 0:00:01.048166
4 th: Elapsed Time is 0:00:01.043658
5 th: Elapsed Time is 0:00:01.052522
6 th: Elapsed Time is 0:00:01.046874
7 th: Elapsed Time is 0:00:01.053725
8 th: Elapsed Time is 0:00:01.046891
9 th: Elapsed Time is 0:00:01.051101
10 th: Elapsed Time is 0:00:01.101507
約1秒というところでしょうか。
ここまでくると、上の計算は、シロウトがコードを書いた場合に比べてどの程度速いのかという興味が湧いてきます。VisualStudioは入っているし、C/C++の知識が残っていれば検討可能そうですが、最近のコンパイラは賢くなっているだろうし、下手なコードを書くと、最適化で所望の命令コードにならないかも。そして、どんどん脇道に逸れてしまい、AIの道に進めなくなりそうです。
当面は自粛しましょう。
AI 事始め6:ちょっと寄り道:tensorflow ハードウェア条件の確認
tensorflow_gpu-1.11.0もインストールしたので、サポートしていないGPUにどんな反応をするか、しつこく調べてみました。Using GPUsという記事にサンプルコードが記載されており、ご親切にコピーボタンまで付いてます。
早速コピーして、テキストファイルに張り付けて、
import tensorflow as tf という行を先頭に加えて、拡張子を.pyにして、utf-8の文字コードで、名前を例えば、devmapping.pyとして保存する。この作業には、サクラエディタを利用しました。
先に作成したGPU用のenvironment ”tfggg”から、Terminalを起動し、下記で実行しました。
>python devmapping.py
2018-10-09 15:56:25.944437: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1411] Found device 0 with properties:
name: GeForce GT 710 major: 3 minor: 5 memoryClockRate(GHz): 0.954
pciBusID: 0000:01:00.0
totalMemory: 2.00GiB freeMemory: 1.67GiB
2018-10-09 15:56:25.948722: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1461] Ignoring visible gpu device (device: 0, name: GeForce GT 710, pci bus id: 0000:01:00.0, compute capability: 3.5) with Cuda compute capability 3.5. The minimum required Cuda capability is 3.7.
2018-10-09 15:56:25.953086: I tensorflow/core/common_runtime/gpu/gpu_device.cc:971] Device interconnect StreamExecutor with strength 1 edge matrix:
2018-10-09 15:56:25.955495: I tensorflow/core/common_runtime/gpu/gpu_device.cc:977] 0
2018-10-09 15:56:25.956933: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990] 0: N
Device mapping: no known devices.
2018-10-09 15:56:25.959448: I tensorflow/core/common_runtime/direct_session.cc:291] Device mapping:
MatMul: (MatMul): /job:localhost/replica:0/task:0/device:CPU:0
2018-10-09 15:56:25.962255: I tensorflow/core/common_runtime/placer.cc:922] MatMul: (MatMul)/job:localhost/replica:0/task:0/device:CPU:0
a: (Const): /job:localhost/replica:0/task:0/device:CPU:0
2018-10-09 15:56:25.965878: I tensorflow/core/common_runtime/placer.cc:922] a: (Const)/job:localhost/replica:0/task:0/device:CPU:0
b: (Const): /job:localhost/replica:0/task:0/device:CPU:0
2018-10-09 15:56:25.968120: I tensorflow/core/common_runtime/placer.cc:922] b: (Const)/job:localhost/replica:0/task:0/device:CPU:0
[[22. 28.]
[49. 64.]]
やはり、GeForce GT 710は使えませんでしたが、理由はThe minimum required Cuda capability is 3.7.でした。
tensorflowに使用できるハード条件では、NVIDIA® GPU card は Compute Capability 3.5以上とあるのに、いつの間にか変わっています。
NvidiaのToolkitの情報では、5.x以上となっていますので、これとも違います。進化の激しい分野では、この辺の確認が作業が極めて大変そうですね。注意1秒ケガ一生ではないですが、普段の注意が肝要ですね。
それでも、CPUを使って、計算結果の出力まで実行してくれ、途中でハングすることは無いようなので、自分が何をしているかを、常に把握していれば、問題無いようです。
AI 事始め5:やっとTensorflowのインストール開始
windowsPC用のインストールpackage("windows")が無く、windowsPCにPythonをインストールして使うらしいです。Create a virtual environment (recommended)などややこしそうなので、先人の知恵を借りることにします。
WEB検索すると、多くの先人達の記事が見つかります。どうやら、Anacondaというアプリを使うらしいという事がわかります。比較的最近の記事を参考に、Anacondaをインストールしていきます。まずはAnacondaのダウンロードです。Anaconda 5.3 For Windows Installerが見つかりましたが、Python 3.7 version しかありません。Tesorflowは、Python 3.6までしか使えませんので、古いversionの使用法を調べました。最新のAnacondaをインストールして、 the root environmentで conda install python=3.6
とすれば良いと書いてあります。
Anaconda 5.3 For Windows Installer -- 64-Bit Graphical Installer (631 MB) をダウンロード、インストールして、Anaconda Navigaterを起動して、the root environmentのTerminalで、上記の操作を実施しました。
さて、いよいよ、tensorflowのインストールです。まずは、Anacondaで新規のenvironmentを作成し、名前を付けます、例えばtfcccとして、作成後のtfcccから、Terminalを起動します。Terminal上で、pip install tensorflowとして、インストールし、画面の最後にSuccessfullyで、tensorflow-1.11.0が出てくれば成功です。
GPUを導入するときに備えて準備をしておきましょう。
AI 事始め1の記事を参照して、NvidiaのCUDA Toolkit 9.0. (Sept 2017)とcuDNN v7.3.1 (Sept 28, 2018), for CUDA 9.0を先にインストールします。cuDNN v7.3.1は解凍して、それぞれのファイルを、CUDA Toolkit 9.0. の対応する場所にコピーするだけです。
Anacondaで新規のenvironmentを作成し、名前を付けます、例えばtfgggとして、作成後のtfgggから、Terminalを起動します。Terminal上で、pip install tensorflow-gpuとして、インストールし、画面の最後にSuccessfullyで、tensorflow_gpu-1.11.0が出てくれば成功です。
AI 事始め4:Windows PC:中古でも凄い性能です。
ネットオークションで中古の安いPCを買いました。
笑われるかもしれませんが、20年前だったら、ん億円はする、システムと感じました。個別の独立空調を必要とし、ディスクアレイのために、広大な床面積と、膨大な配線(SCSI)が必要で、専任の管理部署がある企業でしか使えなかった規模のシステムです。それが、個人のこづかいで買えて、自分ひとりで使える、夢のような時代になっていたと、あらためて感じてしまいました。
感傷はこのぐらいにして、性能をMEMOします。
SSDは240GB, HDDは1TBでした。PC電源は240Wで、Nvidia グラフィクボード(Compute Capability 5.x 以上)の追加は難しいかな。
Windows OSの立ち上がりは、さすがに速く、もっと前に買えばよかったですが、中古はなかったか、オークションの値段も落ちてなかったはずと自己弁解と自己満足です。