PyTorch 深度度量學習無敵 Buff:九大模塊、隨意調用

Python 視界分享

來源|本文經授權轉載自 PyTorch 開發者社區

作者|ππ


內容導讀

從度量學習到深度度量學習,本文介紹了一個 PyTorch 中的程序包,它可以極大簡化使用深度度量學習的難度。

度量學習(Metric Learning)是機器學習過程中經常用到的一種方法,它可以藉助一系列觀測,構造出對應的度量函數,從而學習數據間的距離或差異,有效地描述樣本之間的相似度。

CUB200 數據集樣本示例

常被用作度量學習的 benchmark

這個度量函數對於相似度高的觀測值,會返回一個小的距離值;對於差異巨大的觀測值,則會返回一個大的距離值。

當樣本量不大時,度量學習在處理分類任務的準確率和高效率上,展現出了顯著優勢。

** DML:爲多類別、小樣本分類而生**

然而,如果要處理的分類任務十分複雜,**具有多類別、小樣本等特徵時,**結合深度學習和度量學習的深度度量學習((Deep Metric Learning,簡稱 DML)),纔是真正的王者。

深度度量學習又被稱爲距離度量學習(Distance Metric Learning)。相較於度量學習,深度度量學習可以對輸入特徵做非線性映射。

通過訓練一個基於 CNN 的非線性特徵提取模塊或編碼器,深度度量學習可以將提取的圖像特徵(Embedding)嵌入到近鄰位置,同時藉助歐氏距離、cosine 等距離度量方法,將不同的圖像特徵區分開來。

接下來,深度度量學習再結合 k 最近鄰、支持向量機等分類算法,就可以在不考慮類別數量的基礎上,利用提取的圖像特徵,來完成目標識別任務了。

import numpy as np
# 隨機定義A, B 兩個向量
A = np.random.randn(10)
B = np.random.randn(10)
# 歐幾里得距離(Euclidean distance)
dist = np.square(np.sum(A - B)**2)
# 曼哈頓距離(Manhattan distance)
dist = np.sum(np.abs(A - B))
# 切比雪夫距離(Chebyshev distance)
dist = np.max(np.abs(A - B))
# cosine距離
similarity = (np.sum(A * B))/(np.linalg.norm(A)) / (np.linalg.norm(A))

深度度量學習中的常用距離函數

深度度量學習在 CV 領域的一些極端分類任務(類別衆多、樣本量不足)中表現優異,應用遍及人臉識別、行人重識別、圖像檢索、目標跟蹤、特徵匹配等場景。

以往要在程序中使用深度度量學習,主要依賴工程師從零到一寫代碼,不光耗時久還容易出 bug。**現在則可以依賴一個封裝了多個常用模塊的開源庫,**直接進行調用,省時省力。

PML:讓深度度量學習易如反掌

pytorch-metric-learning(PML)是一個開源庫,可以讓各種繁瑣複雜的深度度量學習算法,變得更加簡單友好。

** pytorch-metric-learning 具有兩大特點 **

1、易於使用

只需添加 2 行代碼,就可以在程序中使用度量學習;調用單個函數,就可以挖掘 pairs 和 triplets。

2、高度靈活

融合了 loss、miner、trainer 等多個模塊,可以在已有代碼中實現各種算法組合。

PML 包括 9 個模塊,每個模塊既可以單獨使用

也可以組合成一個完整的訓練 / 測試 workflow

** pytorch-metric-learning 中的 9 大模塊 **

**1、Loss:**可以應用的各種損失函數

from pytorch_metric_learning.distances import CosineSimilarity
from pytorch_metric_learning.reducers import ThresholdReducer
from pytorch_metric_learning.regularizers import LpRegularizer
from pytorch_metric_learning import losses
loss_func = losses.TripletMarginLoss(distance = CosineSimilarity(), 
             reducer = ThresholdReducer(high=0.3), 
              embedding_regularizer = LpRegularizer())

自定義損失函數** TripletMarginLoss 代碼示例**

2、Distance: 包括計算 pairwise distance 或輸入 embedding 之間相似性的各種類別

**3、Reducer:**從幾個損失值變爲單個損失值

**4、Regularizer:**對權重和嵌入向量進行正則化

**5、Miner:**PML 提供兩種類型的挖掘函數: 子集批處理 miner 及 tuple miner

from pytorch_metric_learning import miners, losses
miner = miners.MultiSimilarityMiner()
loss_func = losses.TripletMarginLoss()
# your training loop
for i, (data, labels) in enumerate(dataloader):
  optimizer.zero_grad()
  embeddings = model(data)
  hard_pairs = miner(embeddings, labels)
  loss = loss_func(embeddings, labels, hard_pairs)
  loss.backward()
  optimizer.step()

** Tripletmurginloss 損失函數添加挖掘功能**

6、Sampler:torch.utils.data.Sampler 類的擴展,決定樣本的 batch 的組成形態

**7、Trainer:**提供對度量學習算法的訪問,如數據增強、附加網絡等

**8、Tester:**輸入模型和數據集,找到基於最近鄰的準確度指標(使用該模塊需要安裝 faiss 安裝包)

9、Util:

損失函數可以自定義使用 Distance、Reducer 及 Regularizer 三個模塊

PML 上手實踐

** PyTorch 版本要求 **

pytorch-metric-learning v0.9.90 版本及以上:torch ≥ 1.6

pytorch-metric-learning v0.9.90 版本以下:沒有版本要求,但是測試版本 torch ≥ 1.2

** Pip **

pip install pytorch-metric-learning

** 獲得最新版本 **

pip install pytorch-metric-learning --pre

** 在 Windows 上安裝 **

pip install torch===1.6.0 torchvision===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html
pip install pytorch-metric-learning

** 增加評估和日誌功能,需要安裝 faiss-gpu 的非官方 pypi 版本 **

pip install pytorch-metric-learning[with-hooks]

** 或 faiss-CPU **

pip install pytorch-metric-learning[with-hooks-cpu]

** Conda **

conda install pytorch-metric-learning -c metric-learning -c pytorch

GitHub 地址:

https://github.com/KevinMusgrave/pytorch-metric-learning

Google Colab:

https://github.com/KevinMusgrave/pytorch-metric-learning/blob/master/examples/README.md

相關論文:

https://arxiv.org/pdf/2008.09164.pdf

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/NagauCb6zEJMeCEJx3A27w