Osomaki67のブログ

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

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

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

test_images = test_images / 255.0
In [11]:
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 [31]:
# 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)
 
Epoch 1/5
60000/60000 [==============================] - 14s 232us/step - loss: 0.4727 - acc: 0.8321
Epoch 2/5
60000/60000 [==============================] - 14s 225us/step - loss: 0.3605 - acc: 0.8686
Epoch 3/5
60000/60000 [==============================] - 14s 225us/step - loss: 0.3234 - acc: 0.8799
Epoch 4/5
60000/60000 [==============================] - 14s 227us/step - loss: 0.3010 - acc: 0.8897
Epoch 5/5
60000/60000 [==============================] - 14s 227us/step - loss: 0.2808 - acc: 0.8959
10000/10000 [==============================] - 0s 47us/step
Out[31]:
[0.3366610364437103, 0.8792]
In [16]:
predictions = model.predict(test_images)
In [17]:
predictions[0]
Out[17]:
array([2.2103798e-07, 1.3197257e-07, 1.4327797e-07, 1.7504580e-09,
       3.8520842e-08, 2.0662786e-02, 7.2375616e-07, 4.4677880e-02,
       2.1749284e-07, 9.3465793e-01], dtype=float32)
In [18]:
np.argmax(predictions[0])
Out[18]:
9
In [19]:
test_labels[0]
Out[19]:
9
In [20]:
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 [21]:
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 [22]:
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 [23]:
# 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 [24]:
# Grab an image from the test dataset
img = test_images[0]

print(img.shape)
 
(28, 28)
In [25]:
# 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 [27]:
plot_value_array(0, predictions_single, test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)
 
In [28]:
np.argmax(predictions_single[0])
Out[28]:
9
In [29]:
#@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すると、まともに動作しているように見えます。

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.

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が表示されません。使い方が悪いのかもしれませんが、今後も気をつけて見ていきましょう。

f:id:Osomaki67:20181010143933p:plain

 

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という記事にサンプルコードが記載されており、ご親切にコピーボタンまで付いてます。

f:id:Osomaki67:20181009144847p:plain
早速コピーして、テキストファイルに張り付けて、

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)などややこしそうなので、先人の知恵を借りることにします。

f:id:Osomaki67:20181009134815p:plain

 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します。

f:id:Osomaki67:20181006180859p:plain

 SSDは240GB, HDDは1TBでした。PC電源は240Wで、Nvidia グラフィクボード(Compute Capability 5.x 以上)の追加は難しいかな。

Windows OSの立ち上がりは、さすがに速く、もっと前に買えばよかったですが、中古はなかったか、オークションの値段も落ちてなかったはずと自己弁解と自己満足です。