物体認識を試す

ImageNetにおける物体認識をしたいとする.
通常ならイチからモデルを組み, データを入手し, 学習させ……という作業が必要なわけだが, ディープラーニングフレームワークKearsならこれが簡単にできる.
さらに, VGGやResNet, Xception, MobileNetなど自宅の計算機スペックでは学習が難しそうなモデルでも予め用意されたパラメータを取得することで, 研究所並の精度の予測ができる.

import numpy as np
from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input, decode_predictions
import keras.preprocessing.image as Image

# モデルの宣言
model = VGG16(weights="imagenet")


続いて予測を行う.
画像は次の画像を用いる.

f:id:umashika5555:20190115142604p:plain
アンゴラウサギ

# 予測
image_path = "angora.png"
image = Image.load_img(image_path, target_size=(224, 224))  # ImageNetのサイズ
x = Image.img_to_array(image)
x = np.expand_dims(x, axis=0)  # 次元を追加。(224, 224)->(1, 224, 224)
x = preprocess_input(x) # ImageNetでやってる前処理を同じようにやる

result = model.predict(x)
result = decode_predictions(result, top=3)[0]
print(result)  # show description

結果は以下の通り「この画像がアンゴラである確率は99.99%以上」スゴイッ!!

[('n02328150', 'Angora', 0.9999628), ('n02123394', 'Persian_cat', 1.3111491e-05), ('n02111889', 'Samoyed', 1.070684e-05)]