【機械学習】AutoGluonの使い方・クイックスタートの解説(画像認識)
AutoGluonの「画像認識」のクイックスタートについて紹介・解説します。
各画像に描かれた衣類のカテゴリーを分類するという内容です。カテゴリはBabyPants, BabyShirt, womencasualshoes, womenchiffontopの4種類です。
Image Prediction - Quick Start — AutoGluon Documentation 0.2.0 documentation
表形式データについては別記事で紹介しています。
[1] データセットのダウンロード
$ curl -OL 'https://autogluon.s3.amazonaws.com/datasets/shopee-iet.zip' $ unzip shopee-iet.zip
[2] 学習データの確認
学習用データは800枚の画像です。
import autogluon.core as ag from autogluon.vision import ImagePredictor train_dataset, _, test_dataset = ImagePredictor.Dataset.from_folders('./data') print(train_dataset) # image label # 0 /home/jupyter/data/train/BabyPants/BabyPants_1... 0 # 1 /home/jupyter/data/train/BabyPants/BabyPants_1... 0 # 2 /home/jupyter/data/train/BabyPants/BabyPants_1... 0 # 3 /home/jupyter/data/train/BabyPants/BabyPants_1... 0 # 4 /home/jupyter/data/train/BabyPants/BabyPants_1... 0 # .. ... ... # 795 /home/jupyter/data/train/womenchiffontop/women... 3 # 796 /home/jupyter/data/train/womenchiffontop/women... 3 # 797 /home/jupyter/data/train/womenchiffontop/women... 3 # 798 /home/jupyter/data/train/womenchiffontop/women... 3 # 799 /home/jupyter/data/train/womenchiffontop/women... 3 # # [800 rows x 2 columns]
[3] 学習の実行
学習を実行すると、ハイパーパラメータと最適なモデルの選定が自動でおこなれます。 ソース中のコメントにもある通り、学習用データのうち1割が検証用データとして使われます。また、ここでは学習回数(epochs)を2回に制限していますが、制限しない方が良いです。
predictor = ImagePredictor() # since the original dataset does not provide validation split, the `fit` function splits it randomly with 90/10 ratio predictor.fit(train_dataset, hyperparameters={'epochs': 2}) # you can trust the default config, we reduce the # epoch to save some build time
学習と検証の予測精度は以下のコードで確認できます。
fit_result = predictor.fit_summary() print('Top-1 train acc: %.3f, val acc: %.3f' %(fit_result['train_acc'], fit_result['valid_acc'])) # Top-1 train acc: 0.623, val acc: 0.806
[4] 評価の実行
テストデータで評価を行います。
test_acc, _ = predictor.evaluate(test_dataset) print('Top-1 test acc: %.3f' % test_acc) # Top-1 test acc: 0.713
[5] 新たな画像のカテゴリを予測
以下は1枚の画像を入力し、どのカテゴリかを確認しています。
image_path = test_dataset.iloc[0]['image'] result = predictor.predict(image_path) print(result) # 0 0 # Name: label, dtype: int64
predict_proba
で、各カテゴリの予測結果を確認できます。
proba = predictor.predict_proba(image_path) print(proba) # 0 1 2 3 # 0 0.498938 0.486701 0.012103 0.002259
複数の画像を入力とし、予測を行うことも可能です。
bulk_result = predictor.predict(test_dataset) print(bulk_result) # 0 0 # 1 0 # 2 2 # 3 2 # 4 1 # .. # 75 3 # 76 3 # 77 3 # 78 3 # 79 2 # Name: label, Length: 80, dtype: int64
[6] 分類器のセーブ・ロード
以下のように分類器のセーブ・ロードが可能です。
filename = 'predictor.ag' predictor.save(filename) predictor_loaded = ImagePredictor.load(filename) # use predictor_loaded as usual result = predictor_loaded.predict(image_path) print(result) # 0 0 # Name: label, dtype: int64
終わりに
精度がどの程度なのかは分かりませんが、ソースコードはかなり簡単に書くことが出来ました。
出典
- アイキャッチはGerd AltmannによるPixabayからの画像