模型訓練技巧 CutMix

2021-10-05 21:37:09 字數 2425 閱讀 9323

**:

官方**:

簡單來講,就是從a圖中隨機擷取乙個矩形區域,用該矩形區域的畫素替換掉b圖中對應的矩形區域,從而形成一張新的組合。同時,把標籤按照一定的比例(矩形區域所佔整張圖的面積)進行線性組合計算損失。

**中的表達形式如下:

將和標籤進行了線性組合。

def cutmix_criterion(criterion, pred, y_a, y_b, lam):

return lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)

def cutmix_data(x, y, alpha=1.0, use_cuda=true):

'''returns mixed inputs, pairs of targets, and lambda'''

assert alpha > 0

lam = np.random.beta(alpha, alpha)

batch_size = x.size()[0]

if use_cuda:

index = torch.randperm(batch_size).cuda()

else:

index = torch.randperm(batch_size)

y_a, y_b = y, y[index]

bbx1, bby1, bbx2, bby2 = rand_bbox(x.size(), lam)

x[:, :, bbx1:bbx2, bby1:bby2] = x[index, :, bbx1:bbx2, bby1:bby2]

# adjust lambda to exactly match pixel ratio

lam = 1 - ((bbx2 - bbx1) * (bby2 - bby1) / (x.size()[-1] * x.size()[-2]))

return x, y_a, y_b, lam

def rand_bbox(size, lam):

w = size[2]

h = size[3]

cut_rat = np.sqrt(1. - lam)

cut_w = np.int(w * cut_rat)

cut_h = np.int(h * cut_rat)

# uniform

cx = np.random.randint(w)

cy = np.random.randint(h)

bbx1 = np.clip(cx - cut_w // 2, 0, w)

bby1 = np.clip(cy - cut_h // 2, 0, h)

bbx2 = np.clip(cx + cut_w // 2, 0, w)

bby2 = np.clip(cy + cut_h // 2, 0, h)

return bbx1, bby1, bbx2, bby2

# 在train函式中做以下修改, 其他地方不做任何修改

for (inputs, targets) in tqdm(trainloader):

inputs, targets = inputs.to(device), targets.to(device)

r = np.random.rand(1)

if r < 0.5: # 做cutmix的概率為0.5

inputs, targets_a, targets_b, lam = cutmix_data(inputs, targets)

inputs, targets_a, targets_b = map(variable, (inputs, targets_a, targets_b))

outputs = net(inputs)

loss = cutmix_criterion(criterion, outputs, targets_a.long(), targets_b.long(), lam)

else:

outputs = net(inputs)

loss = criterion(outputs, targets.long())

官方**都寫在train函式裡,博主覺得函式過長,於是把核心功能cutmix封裝成函式,看起來更簡潔。

從作者的實驗資料來看,cutmix的效果比mixup和cutout都好,並且在影象識別和目標檢測任務上都漲點明顯。

end博主應用該trick正在訓練模型,明天測試結果。

模型訓練技巧(待續)

批訓練 batch trainning 一次訓練一批 比如50個 樣本,在nn或cnn中,對一批樣本在同相同引數的網路上進行前向過程和誤差傳導過程,然後把梯度求和加更新網路引數。優點 訓練速度可也更快,同批中的各樣本可並行訓練。dropout 模型訓練的時候隨機讓某些權重不更新。優點 為了防止過擬合...

網路模型訓練技巧

事先對影象資料進行處理。比如有10萬的資料,現在對這些資料都進行一次變換,那麼就有了20萬資料。最常見的操作就是對資料進行翻倍,翻10 20倍都是有可能的。水平翻轉,這種操作最常見也最實用,因為沒有任何瑕疵。當出現例如人臉被部分遮住的情況,為了讓計算機識別這種,我們可以人為的加上這種遮蔽現象。這種處...

caffe模型訓練小技巧

一 學習率調整 乙個對於排程學習率的建議 如果在驗證集上效能不再增加就讓學習率除以2或者5,然後繼續,學習率會一直變得很小,到最後就可以停止訓練了 二 finetun微調 finetune的過程相當於繼續訓練,跟直接訓練的區別是初始化的時候 a.直接訓練是按照網路定義指定的方式初始化 如高斯隨機初始...