20200518のTensorFlowに関する記事は1件です。

MacでTensorflowを動かして任意の画像を判定する

MacのDockerでTensorFlowを起動

https://www.tensorflow.org/install?hl=ja
https://www.tensorflow.org/install/docker?hl=ja#gpu_support

Mac
$ docker images # ダウンロードしたイメージの確認
$ docker ps # コンテナの確認

$ docker pull tensorflow/tensorflow:latest-gpu-py3 # イメージのダウンロード
$ docker run -it tensorflow/tensorflow:latest-gpu-py3 # コンテナの起動

# 起動させたまま抜けるときはctrl+Q
$ docker attach <コンテナID> # 起動中のコンテナに接続する

※エラーが出るだけで、gpu版でなくても動くかも。

Docker上のpythonでMNISTサンプルを動作確認

https://www.tensorflow.org/tutorials/keras/classification?hl=ja

$ apt-get install vim #vimインストール
$ pip install matplotlib #matplotlibがなかったのでインストール。
learn.py
from __future__ import absolute_import, division, print_function, unicode_literals

# TensorFlow と tf.keras のインポート
import tensorflow as tf
from tensorflow import keras

# ヘルパーライブラリのインポート
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']

print(train_images.shape)
print(len(train_labels))

train_images = train_images / 255.0
test_images = test_images / 255.0

# 層の設定
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10, activation='softmax')
])

# モデルのコンパイル
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# モデルの訓練
model.fit(train_images, train_labels, epochs=5)

# 予測のテスト
predictions = model.predict(test_images)
print(np.argmax(predictions[0]))

# 正答率の評価
test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)
print('\nTest accuracy:', test_acc)

# モデルの保存
model.save('my_model.h5');

モデルを保存しておけば、学習なしで判定に使えます。

保存したモデルを使って実行

predict.py
new_model = keras.models.load_model('my_model.h5')

test_loss, test_acc = new_model.evaluate(test_images,  test_labels, verbose=2)
print('\nTest accuracy:', test_acc)

Docker上で任意の画像を判定する

predict.py
# 画像の読み込み
img_path = "/pants.jpg"
img_raw = tf.io.read_file(img_path)
img_tensor = tf.image.decode_image(img_raw)
img_final = tf.image.resize(img_tensor, [28, 28])
img_final = img_final/255.0

# 次元をそろえる
# ここまででshapeは[28, 28, 3]。最後の3はRBGカラーの3つ。
img_gray = tf.image.rgb_to_grayscale(img_final) # [28, 28, 1]
img_squeeze = tf.squeeze(img_gray) # [28, 28]
img_expand = np.expand_dims(img_squeeze, axis=0) # [1, 28, 28]
# これでshapeが[1, 28, 28]になり、predictに食わせられる。

predictions = new_model.predict(img_expand)
print(np.argmax(predictions[0]))
# あれ、、パンツのはずが、バッグと判定された??

参考:https://note.nkmk.me/python-tensorflow-keras-basics/

次元を削減する方法

predict.py
#  以下のsqueezeとreshapeどちらでもいけた。
img_squeeze = tf.squeeze(img_gray)
img_reshape = tf.reshape(img_gray, [28,28])

はまったところ

ファッションmnistのデータは黒背景で学習されているので、白背景の画像を食わせても判定がうまくいかなかった。

x これはだめ。
pants.jpg

○ これはOK
pants_b.jpg

デバッグ

predict.py
print(img_final.shape) # shapeで[28,28,1]などを出力させるか
print(img_final) # 生の行列の中身を出力させるのも有効。白背景NGはこれで気がついた。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む