import numpy as np
import pprint
from tensorflow import keras
from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions
image_path = "images/P1071064.jpeg"
image_size = 224Apple SiliconのMacでは、GPU対応のTensorFlowが使えるということで、TensorFlowを使った機械学習です。Keras組み込みのVGG16で画像の分類をやってみます。
準備
Pythonの準備です。
識別する画像は以下のものです。

VGG16による画像識別実行
imageに画像を読み込み、形式を整えたうえで、preprocess_inputで前処理を実行します。そして、predictで分類実行、decode_predictionsでデコードします。デフォルトでは上位5番目までの結果が返されます。
vgg16 = VGG16(input_shape = (image_size, image_size, 3))
image = keras.utils.load_img(image_path,
                             target_size = (image_size, image_size))
input_arr = keras.utils.img_to_array(image)
input_arr = np.array([input_arr])
preprocessed_image = preprocess_input(input_arr)
predict = vgg16.predict(preprocessed_image)
result = decode_predictions(predict)結果
結果の表示です。pprintで整形しています。
pprint.pprint(result)[[('n01847000', 'drake', 1.0),
  ('n01667778', 'terrapin', 1.5397424e-20),
  ('n01855672', 'goose', 6.006676e-26),
  ('n02056570', 'king_penguin', 6.160868e-31),
  ('n01855032', 'red-breasted_merganser', 6.5141483e-32)]]“drake”は「雄ガモ」の意味ですので、ただしく分類されたようです。