系列文章目錄
pytorch學習筆記(一)-- pytorch深度學習框架基本知識了解
pytorch學習筆記(二)-- pytorch模型開發步驟詳解
pytorch學習筆記(三)-- TensorBoard的介紹
pytorch學習筆記(四)-- TorchVision 物體檢測微調教程
pytorch學習筆記(五)-- 計算機視覺的遷移學習
文章目錄
系列文章目錄
文章目錄
前言
一、加載數據?
二、訓練模型
三、可視化模型預測
四、卷積網絡微調
???微調 ConvNet:
ConvNet 作為固定特征提取器:
五、自定義圖像的推理
總結
前言
????????在本章節,您將學習如何使用遷移學習訓練卷積神經網絡進行圖像分類。您可以在 cs231n notes 筆記中閱讀有關遷移學習的更多信息。
????????一般來說,大家都不會從頭開始訓練卷積神經網絡,而是先在較大的數據集上做預訓練,差不多成熟了,然后再把卷積網絡在自己的任務上做初始化,或者特征提取器。
這兩種主要的遷移學習場景如下:
- 微調 ConvNet:我們不是使用隨機初始化,而是使用預訓練網絡(例如在 imagenet 1000 數據集上訓練的網絡)來初始化網絡。其余訓練看起來與往常一樣。
- ConvNet 作為固定特征提取器:在這里,我們將凍結除最終全連接層之外的所有網絡的權重。最后一個全連接層將被替換為具有隨機權重的新層,并且只訓練這一層。
一、加載數據?
????????我們使用torchvision 和 torch.utils.data數據包進行數據加載,今天的任務是訓練一個模型用來分辨螞蟻和蜜蜂,我們有120張螞蟻和蜜蜂的照片用于訓練,以及75張用于測試蜜蜂和螞蟻的照片。
數據集下載路徑:MyDataset: 數據集倉庫,包括各種網站搜刮的,以及一些自定義的數據。方便后續神經網絡的訓練 - Gitee.com
????????通常,如果從頭開始訓練,這個數據集太小了,無法進行推廣。由于我們使用遷移學習,我們就可以相當好地進行推廣。
# Data augmentation and normalization for training
# Just normalization for validation
data_transforms = {'train': transforms.Compose([transforms.RandomResizedCrop(224),transforms.RandomHorizontalFlip(),transforms.ToTensor(),transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]),'val': transforms.Compose([transforms.Resize(256),transforms.CenterCrop(224),transforms.ToTensor(),transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]),
}data_dir = 'data/hymenoptera_data'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),data_transforms[x])for x in ['train', 'val']}
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=4,shuffle=True, num_workers=4)for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_names = image_datasets['train'].classesdevice = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")#可視化部分圖片,確認下效果
def imshow(inp, title=None):"""Display image for Tensor."""inp = inp.numpy().transpose((1, 2, 0))mean = np.array([0.485, 0.456, 0.406])std = np.array([0.229, 0.224, 0.225])inp = std * inp + meaninp = np.clip(inp, 0, 1)plt.imshow(inp)if title is not None:plt.title(title)plt.pause(0.001) # pause a bit so that plots are updated# Get a batch of training data
inputs, classes = next(iter(dataloaders['train']))# Make a grid from batch
out = torchvision.utils.make_grid(inputs)
imshow(out, title=[class_names[x] for x in classes])
二、訓練模型
編寫一個通用函數來訓練模型。
- 安排這個learning rate
- 保存模型
???????參數 scheduler 是來自 torch.optim.lr_scheduler 的 LR 調度程序對象,關于這個scheduler在后續模型優化的章節會講到,也是一個非常強大的功能,這里就先不贅述了。
def train_model(model, criterion, optimizer, scheduler, num_epochs=25):since = time.time()# Create a temporary directory to save training checkpointswith TemporaryDirectory() as tempdir:best_model_params_path = os.path.join(tempdir, 'best_model_params.pt')torch.save(model.state_dict(), best_model_params_path)best_acc = 0.0for epoch in range(num_epochs):print(f'Epoch {epoch}/{num_epochs - 1}')print('-' * 10)# Each epoch has a training and validation phasefor phase in ['train', 'val']:if phase == 'train':model.train() # Set model to training modeelse:model.eval() # Set model to evaluate moderunning_loss = 0.0running_corrects = 0# Iterate over data.for inputs, labels in dataloaders[phase]:inputs = inputs.to(device)labels = labels.to(device)# zero the parameter gradientsoptimizer.zero_grad()# forward# track history if only in trainwith torch.set_grad_enabled(phase == 'train'):outputs = model(inputs)_, preds = torch.max(outputs, 1)loss = criterion(outputs, labels)# backward + optimize only if in training phaseif phase == 'train':loss.backward()optimizer.step()# statisticsrunning_loss += loss.item() * inputs.size(0)running_corrects += torch.sum(preds == labels.data)if phase == 'train':scheduler.step()epoch_loss = running_loss / dataset_sizes[phase]epoch_acc = running_corrects.double() / dataset_sizes[phase]print(f'{phase} Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')# deep copy the modelif phase == 'val' and epoch_acc > best_acc:best_acc = epoch_acctorch.save(model.state_dict(), best_model_params_path)print()time_elapsed = time.time() - sinceprint(f'Training complete in {time_elapsed // 60:.0f}m {time_elapsed % 60:.0f}s')print(f'Best val Acc: {best_acc:4f}')# load best model weightsmodel.load_state_dict(torch.load(best_model_params_path, weights_only=True))return model
三、可視化模型預測
? ? ? ? 經過上一節的訓練,我們現在看看模型的預測結果怎么樣。作為傳統的程序開發者,我們習慣通過打印來驗證結果,但是這玩意兒只有開發兄弟能懂哈。Pytorch畢竟是基于Python的深度學習框架,工具包是應用盡有,所以我們可以以可視化的圖形來顯示預測的效果。說個題外話,將工作結果可視化這個習慣,各位開發兄弟得學起來,以后就可以一手抓開發,一手抓產品,既可以跟開發同事一起奮斗,又可以跟老板以及客戶吹牛逼,路就走寬了。
def visualize_model(model, num_images=6):was_training = model.trainingmodel.eval()images_so_far = 0fig = plt.figure()with torch.no_grad():for i, (inputs, labels) in enumerate(dataloaders['val']):inputs = inputs.to(device)labels = labels.to(device)outputs = model(inputs)_, preds = torch.max(outputs, 1)for j in range(inputs.size()[0]):images_so_far += 1ax = plt.subplot(num_images//2, 2, images_so_far)ax.axis('off')ax.set_title(f'predicted: {class_names[preds[j]]}')imshow(inputs.cpu().data[j])if images_so_far == num_images:model.train(mode=was_training)returnmodel.train(mode=was_training)
四、卷積網絡微調
? ? ? ? 上三節都是準備工作,這一節,我們就講一下兩種遷移學習的使用。
???微調 ConvNet:
#加載一個預訓練的模型并且重置全連接層
model_ft = models.resnet18(weights='IMAGENET1K_V1')
num_ftrs = model_ft.fc.in_features
# Here the size of each output sample is set to 2.
# Alternatively, it can be generalized to ``nn.Linear(num_ftrs, len(class_names))``.
model_ft.fc = nn.Linear(num_ftrs, 2)
model_ft = model_ft.to(device)
criterion = nn.CrossEntropyLoss()# Observe that all parameters are being optimized
optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)# Decay LR by a factor of 0.1 every 7 epochs
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,num_epochs=25)
visualize_model(model_ft)
ConvNet 作為固定特征提取器:
? ? ? ? 注意:這里,我們需要凍結除最后一層之外的所有網絡。我們需要設置requires_grad = False來凍結參數,這樣梯度就不會在backward()中計算。
model_conv = torchvision.models.resnet18(weights='IMAGENET1K_V1')
for param in model_conv.parameters():param.requires_grad = False# Parameters of newly constructed modules have requires_grad=True by default
num_ftrs = model_conv.fc.in_features
model_conv.fc = nn.Linear(num_ftrs, 2)model_conv = model_conv.to(device)
criterion = nn.CrossEntropyLoss()# Observe that only parameters of final layer are being optimized as
# opposed to before.
optimizer_conv = optim.SGD(model_conv.fc.parameters(), lr=0.001, momentum=0.9)# Decay LR by a factor of 0.1 every 7 epochs
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)model_conv = train_model(model_conv, criterion, optimizer_conv, exp_lr_scheduler, num_epochs=25)
visualize_model(model_conv)
plt.ioff()
plt.show()
五、自定義圖像的推理
????????使用訓練的模型進行自定義圖片的預測并且顯示預測圖片對應的標簽
def visualize_model_predictions(model,img_path):was_training = model.trainingmodel.eval()img = Image.open(img_path)img = data_transforms['val'](img)img = img.unsqueeze(0)img = img.to(device)with torch.no_grad():outputs = model(img)_, preds = torch.max(outputs, 1)ax = plt.subplot(2,2,1)ax.axis('off')ax.set_title(f'Predicted: {class_names[preds[0]]}')imshow(img.cpu().data[0])model.train(mode=was_training)visualize_model_predictions(model_conv,img_path='data/hymenoptera_data/val/bees/72100438_73de9f17af.jpg'
)plt.ioff()
plt.show()
總結
? ? 遷移學習其實是實際工作中用的非常多的一種神經網絡開發方法,對于開發者來說,從頭構建一個模型,開發難度很大,并且個人很難去實現它的訓練,這個需要龐大的數據集以及場景測試。? ??????????