Transfer Learning 識別狗貓品種
匯入需要的包
from fastai import * from fastai.vision import *
準備資料
資料集含 7393 張圖片,37 個不同貓狗品種
bs = 64 # batch-size # 下載資料集 path = untar_data(URLs.PETS) path_anno = path/'annotations' path_img = path/'images' fnames = get_image_files(path_img) # 利用正則表示式獲得類別,組裝成訓練集和驗證集 pat = re.compile(r'/([^/]+)_\d+.jpg$') data = ImageDataBunch.from_name_re(path_img, fnames, pat, ds_tfms=get_transfrom(), size=224, bs=bs, num_workers=0).normalize(imagenet_stats) # 檢視 data.show_batch(rows=3, figsize=(7,6))
使用 ResNet34 遷移學習
使用本地 CPU 迭代 4 次需大約 2 hours,使用 GCP 僅需 2 mins
# 使用 ResNet34 learn = create_cnn(data, models.resnet34, metrics=error_rate) # 訓練 learn.fit_one_cycle(4)
Total time: 02:10
epoch | train_loss | valid_loss | error_rate |
---|---|---|---|
1 | 1.363533 | 0.374314 | 0.110961 |
2 | 0.551215 | 0.287073 | 0.094723 |
3 | 0.346619 | 0.271395 | 0.081867 |
4 | 0.249408 | 0.254900 | 0.079838 |
# 儲存模型 learn.save('stage-1')
評估
losses
interp = ClassficationInterpretation.from_learner(learn) # losses 從大到小存至 list losses, idxs = interp.top_losses() # losses 最大的 9 張圖 interp.plot_top_losses(9, fjgsize=(15, 11))
confusion matrix
# 繪製 confusion matrix interp.plot_confusion_matrix(figsize=(12, 12), dpi=60)
# 混淆次數最多的幾個品種 interp.most_confused(min_val=2)
[(‘american_pit_bull_terrier’, ‘staffordshire_bull_terrier’, 10),(‘Russian_Blue’, ‘British_Shorthair’, 5),(‘american_pit_bull_terrier’, ‘american_bulldog’, 5),(‘american_pit_bull_terrier’, ‘miniature_pinscher’, 4),(‘Egyptian_Mau’, ‘Bengal’, 3),(‘american_bulldog’, ‘staffordshire_bull_terrier’, 3),(‘english_cocker_spaniel’, ‘english_setter’, 3)]
看來斯塔福郡鬥牛梗和美國位元鬥牛犬最難分辨,是有點像
美國位元鬥牛犬 | 斯塔福郡鬥牛梗 |
---|---|
![]() |
![]() |