初體驗
path = untar_data(URLs.PETS) # 自動下載並解壓數據
fnames = get_image_files(path_img) # 得到路徑下所有的圖片
data.show_batch(rows=3, figsize=(7,6)) # 查看數據3行,顯示尺寸7,6
print(data.classes) # 數據種類
手寫數據集識別:
import torch
from fastai import *
from fastai.vision import *
path = untar_data(URLs.MNIST_SAMPLE)
data = ImageDataBunch.from_folder(path)
learn = cnn_learner(data, models.resnet18, metrics=accuracy)
learn.fit_one_cycle(1)
learn.save('stage-1') # 保存訓練的模型
interp = ClassificationInterpretation.from_learner(learn)
interp.plot_top_losses(9,figsize = (7,7)) # 打印損失最大的九個
interp.plot_confusion_matrix(figsize = (7,7)) # 繪製混淆矩陣
interp.most_confused(min_val=2) # [('3', '7', 50), ('7', '3', 37)]
'''
most_confused
will simply grab out of the confusion matrix the particular
combinations of predicted and actual that got wrong the most often.
簡單地從混亂矩陣中找出預測和實際的特定組合,這些組合是最容易出錯的。
上面的3和7最容易出錯 (實際的,預測的,這種情況發生的次數)上面第一個表示實際上是7,
預測是3,錯了22次
'''
# 微調
'''
我們有時候需要微調,重新加了一些層進去後,如果你不解凍,它只會訓練新加的一些層,
#而不會訓練整個層,這是爲了讓訓練更快,而你要想訓練整個層的話,就要先解凍再訓練
'''
learn.unfreeze()
learn.fit_one_cycle(1)
learn.lr_find() # 尋找最適合的學習率
learn.recorder.plot() # 並且畫圖表示出來
learn.unfreeze()
learn.fit_one_cycle(2, max_lr=slice(1e-6,1e-4)) # 這個學習率區間是看圖得出來的