メインコンテンツへスキップ

Python初心者が画像認識をやってみた

    はじめに

    いわゆる「AI」を利用するためのスタートとして、Aidemyさんの講座を受講しました。講座を通して作成した画像認識アプリの作成過程をブログにしました。

    本記事の概要

    実装環境、Pythonで実装したコード内容の一部などを書いていきます。

    実装環境

    • Google Colaboratory

    • Python3

    作成したプログラム

    犬、猫それぞれ5種類を判定するプログラムを実装します。
    モデルはVGG16を転移学習させることにします。
    (プログラムは部分的に掲載するため、掲載部分だけでは実装できず、辻褄のあっていない部分もあります。また、ブログのために一部変更しています。)

    データセット

    スクレイピングはせず、「The Oxford-IIIT Pet Dataset」の一部を利用します(1カテゴリ200枚)。今回は水増しはせず、そのまま使用します。

    インポート

    使用するライブラリ類をインポートします。
    一部の定数、関数はデプロイ側でも使用するため、commonに定義しています。最後の行はそのインポートになります(これはマストではありません)。

    import cv2
    import numpy as np
    import matplotlib.pyplot as plt
    from tensorflow.keras.utils import to_categorical
    from tensorflow.keras.layers import Dense, Dropout, Flatten, Input
    from tensorflow.keras.applications.vgg16 import VGG16
    from tensorflow.keras.models import Model, Sequential
    from tensorflow.keras import optimizers
    
    import pandas as pd
    from sklearn.model_selection import train_test_split
    
    import os
    from google.colab import files
    
    from keras.preprocessing.image import load_img, img_to_array
    from keras.applications.vgg16 import preprocess_input
    
    #common
    from common import dog_cat_breed_list, NUM_CLASS, IMG_WIDTH, IMG_HEIGHT, input_img_process_cv2, input_img_process
    

    common

    一部の定数、関数はデプロイ側でも使用するため、commonに定義しています。犬種・猫種のラベルのリスト、判定する種類の数、入力画像の前処理関数などを定義しています。

    #!/usr/bin/python3.11
    
    #
    #import
    #
    import cv2
    import numpy as np
    from keras.preprocessing.image import load_img, img_to_array
    from keras.applications.vgg16 import preprocess_input
    
    
    #
    #犬種、猫種のリスト
    #
    dog_cat_breed_list = ['beagle', 
                      'boxer',
                      'chihuahua',
                      'english_cocker_spaniel',
                      'shiba_inu',
                      'Abyssinian', 
                      'Bengal',
                      'Bombay',
                      'British_Shorthair',
                      'Ragdoll']
    
    NUM_CLASS = 10
    
    IMG_WIDTH  = 200
    IMG_HEIGHT = 200
    
    #
    #入力画像の処理関数(cv2)
    #
    def input_img_process_cv2(img_path,
                              img_width,
                              img_height,
                              sw_np_array,
                              sw_dim_add,
                              sw_vgg16_preprocess) :
        img = cv2.imread(img_path)                    #image read
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)    #BGR to RGB
        img = cv2.resize(img, (img_width,img_height)) #resize
        
        if sw_np_array == 1:
            img = np.array( img )                     #Numpy配列に変換
        
        if sw_dim_add == 1:
            img = np.expand_dims(img, axis=0)         #バッチ次元の追加
            if sw_vgg16_preprocess == 1 :
                img = preprocess_input(img)           #VGG16用の前処理
        
        return img
        pass
    
    
    #
    #入力画像の処理関数(keras.preprocessing.image)
    #
    def input_img_process(img_path,
                          img_width,
                          img_height,
                          sw_np_array,
                          sw_dim_add,
                          sw_vgg16_preprocess) :
        img = load_img(img_path, target_size=(img_width,img_height)) #image read, resize
        
        if sw_np_array == 1:
            img = img_to_array(img)              #Numpy配列に変換
        
        if sw_dim_add == 1:
            img = np.expand_dims(img, axis=0)    #バッチ次元の追加
            if sw_vgg16_preprocess == 1 :
                img = preprocess_input(img)      #VGG16用の前処理
        
        return img
        pass

    入力データ、ラベルの準備

    犬、猫のラベル名のフォルダに入っている画像ファイル名を取得し、commonで定義した入力画像の処理関数を用いて、入力データを準備していきます。同時にラベルに該当するインデックスも格納していきます。
    モデルの入力形式に合わせるため、最後にNumpy形式に変換し、ラベルもone-hot形式にします。

    data  = []
    label = []
    
    #入力画像のあるフォルダパス
    root_path = #割愛します
    
    for i in dog_cat_breed_list:
        file_list = os.listdir(root_path + str(i) + '/')
       
        for j in range(len(file_list)):
    
            img_path = root_path + str(i) + '/' + file_list[j]
            
            if SW_CV2 == 1 :
                x = input_img_process_cv2( img_path, IMG_WIDTH, IMG_HEIGHT, 0, 0 ,0 )
            else :
                x = input_img_process(     img_path, IMG_WIDTH, IMG_HEIGHT, 0, 0 ,0 )
    
            data.append( x )
            label.append( dog_cat_breed_list.index(i) )
    
    
    X = np.array( data )     #Numpy配列に変換
    Y = to_categorical(label)  #one-hot

    訓練データと検証データに分ける

    train_test_split関数を用いて、訓練データ(80%)、検証データ(20%)に分配します。

    X_train, X_test, Y_train, Y_test = train_test_split(X, 
                                                        Y, 
                                                        test_size=0.2, 
                                                        random_state=42, 
                                                        stratify=Y)

    モデルのインスタンス

    VGG16の出力に2層(①256ノード+②出力10ノード)を追加したモデルとします。層数やノード数をいくつにするのが適当であるかは、基本的に試行してみないと分からない認識でいます。過学習を抑制するため、ドロップアウトのレートを0.5としていますが、こちらもどの程度が最適かはやってみないと分かりません。

    input_tensor = Input(shape=(IMG_WIDTH, IMG_HEIGHT, 3))
    vgg16 = VGG16(include_top=False, weights='imagenet', input_tensor=input_tensor)
    
    top_model = Sequential()
    top_model.add(Flatten(input_shape=vgg16.output_shape[1:]))
    
    top_model.add(Dense(256, activation='relu'))
    top_model.add(Dropout(0.5))
    
    top_model.add(Dense(NUM_CLASS, activation='softmax'))
    
    model = Model(inputs=vgg16.input, outputs=top_model(vgg16.output))

    VGG16 重み固定範囲の指定

    VGG16の重みをどの層まで固定させるかを設定します(FIX_LAYER = 19で再学習をしない設定)。FIX_LAYERを小さい値にするほど、再学習させる層数が増えるため、今回のデータに特化したモデルになります。

    FIX_LAYER = 15
    for layer in model.layers[:FIX_LAYER]:
        layer.trainable = False

    モデルのコンパイル、学習

    下記の通り、モデルのコンパイル、学習を実施します。
    今回は多クラス分類のため「categorical_crossentropy」を指定しています。
    エポック数は100としました。

    model.compile(loss='categorical_crossentropy',
                  optimizer=optimizers.SGD(learning_rate=1e-4, momentum=0.9),
                  metrics=['accuracy'])
    
    model.summary()
    
    BATCH_SIZE = 100
    EPOCHS = 100
    history = model.fit(X_train,
                        Y_train,
                        batch_size=BATCH_SIZE,
                        epochs=EPOCHS)

    精度の評価

    正解率での評価を実施しました。

    scores = model.evaluate(X_test, Y_test, verbose=1)
    print('Test loss    :', scores[0])
    print('Test accuracy:', scores[1])

    検証データでの結果は約66%でした。1カテゴリ200枚と学習させる枚数としてはかなり少ないので、最初としてはこの程度でしょうか。
    また、モデルの設定の調整次第では、正解率はまだあがると思われます。

    13/13 [==============================] - 11s 379ms/step - loss: 1.5986 - accuracy: 0.6625
    Test loss    : 1.5986193418502808
    Test accuracy: 0.6625000238418579

    デプロイ

    最終的にwebアプリの実装まで行いましたが、ブログとしては割愛いたします。

    おわりに

    今回はどのようなモデル設定がリーズナブルかを突き詰めるところまで到達できませんでしたが、今後そのあたりをアップデートしていけたらと思います。
    まだ入り口の入り口あたりにいる状態ですが、AI, Pythonに対する理解を深めていけたらと思います。

    補足

    このブログはAidemy Premiumのカリキュラムの一環で、受講修了条件を満たすために公開しています。