1、準備

對比學習入門 A Primer on Contrastive Learning

近幾年,對比學習在CV和NLP中掀起了一股熱潮,其學習到的表徵向量在多個下游任務上取得了state of art的效果。 本文討論的重心是自監督對比學習,由於不依賴標註資料,其實際上是一種無監督學習方法,在工業中有廣闊的應用場景。同時,本文也會討論監督對比學習,其和自監督對比學習的主要差異在於標註樣本,並且能獲得更好的效果。深入分析後發現,對比學習和多分類學習有著切不斷的聯絡,不管是contrastive loss和softmax loss還是二者背後的motivation,都緊密相關。

因此,本文會先從softmax loss出發,推導softmax loss並討論其性質;再介紹contrastive loss;最後回到監督對比學習和自監督對比學習。

1。1 、多分類監督學習 Multiclass Classification

多分類是機器學習中最常見的學習任務,多分類任務的損失函式一般為softmax loss。下面這篇文章推導了softmax loss的公式,並介紹了它的一些改進形式。

Softmax Loss推導及擴充套件

1。2、監督對比學習 Supervised Contrastive Learning

監督對比學習是一種機器學習技術,透過同時教模型哪些資料點相似或不同,來學習資料集的一般特徵。監督對比學習是一種監督學習方法,對樣本質量要求較高。相比於一般監督學習,監督對比學習通常能獲得更好的效果。

對比學習視覺化

1。3、自監督學習 Self-Supervised Learning

在大多數實際場景中,我們沒有為每個樣本新增標籤。以醫學成像為例,獲取樣本的難度很大,為了建立標籤,專業人士不得不花費無數的時間來手動分類、分割影象。

雖然生成帶有乾淨標籤的資料集是昂貴的,但是我們時時刻刻都在生成大量的未標記的資料。自監督學習是讓我們能夠從這些未標記的資料中學習知識的一種方法。要利用這些大量的未標記資料,一種方法是適當地設定學習目標,以便從資料本身獲得監督。

在NLP中,word2vec, Mask Language Model就是典型的自監督學習。在CV中也有很多自監督學習的例子,比如:將一張圖片切成小的blocks,預測blocks之間的關係、將小的blocks拼圖成原圖等。

對比學習入門 A Primer on Contrastive Learning

1。4、自監督對比學習 Self-Supervised Contrastive Learning

自監督對比學習和監督對比學習整體上是相似的,不同之處在於:自監督對比學習透過資料增強來構建有標籤的樣本,而監督對比學習的有人工標註的對比樣本。因此,自監督對比學習的核心和難點是構建優質的對比樣本。在CV中,一般透過剪下、旋轉、高斯噪聲、遮掩、染色等操作生成正樣本。在NLP中一般透過回譯、對字元的增、刪、改來新增噪聲,從而生成正樣本。由於文字的離散性質,一般較難生成好的標籤不變的增強樣本。

2、監督對比學習 Supervised Contrastive Learning

2。1、對比損失V0 Contrastive Loss

Dimensionality Reduction by Learning an Invariant Mapping(2006)

這篇文章介紹了把樣本從高維空間對映到低維空間的一種通用方法。模型僅依賴於樣本的近鄰關係,不需要在輸入空間中進行任何距離度量。該方法使用基於能量的模型,模型使用給定的近鄰關係學習對映函式。設對映函式為

G

,引數為

W

,學習的目標是找到一個

W

值,使得投影歐幾里得流形上點之間的距離

D_W(X_1,X_2)=|| G_W(X_1)− G_W(X2_)||_ 2

近似輸入空間中的近鄰關係。其損失函式為:

L(W, Y, X_1, X_2) = (1−Y)\frac{1}{2}(D_W)^2 +(Y)\frac{1}{2}{max(0,m−D_W)}^2 \\

其中,

Y=1

表示兩個樣本是近鄰關係,

Y=0

表示兩個樣本不是近鄰關係。

m>0

是margin引數。對於不相似的樣本pair,兩個樣本離的越近,損失越大。當

D_W>m

時候,loss為零,此時兩個樣本位於彼此的margin半徑外。對於相似的樣本pair,兩個樣本離的越遠,損失越大。

對比學習入門 A Primer on Contrastive Learning

下面這張圖能更直觀的看出contrastive的思路:即讓相似的樣本pair越來越近(pull),讓不相似的樣本pair越來越遠(push),直到超過margin。

對比學習入門 A Primer on Contrastive Learning

對於多分類任務,Constractive Loss經常會在訓練集上過擬合。針對該問題的改進方法有Triplet Loss、四元組損失(Quadruplet loss)、難樣本取樣三元組損失(Triplet loss with batch hard mining, TriHard loss) 等。

2。2 三元損失 Triplet Loss

In Defense of the Triplet Loss for Person Re-Identification

(2017)

Triplet loss和quadruplet loss是行人重識別中(Person Re-identification, ReID) 提出的損失函式。行人重識別也稱行人再識別,是利用計算機視覺技術判斷影象或者影片序列中是否存在特定行人的技術。行人重識別的資料特點是:同一個人有不同顏色、角度和姿態的圖片,這些圖片表表示同一個人,因此自然而然有很多正樣本pair。

對比學習入門 A Primer on Contrastive Learning

Triplet Loss是深度學習中的一種損失函式,用於訓練

差異性較小

的樣本,如人臉等。 輸入資料包括錨(Anchor)示例、正(Positive)示例、負(Negative)示例,透過最佳化錨示例與正示例的距離

小於

錨示例與負示例的距離,實現樣本的相似性計算。

輸入是一個三元組

a: anchor

, 錨點樣本

p: positive

, 與

a

是同一類別的樣本

n: negative

, 與

a

是不同類別的樣本

對比學習入門 A Primer on Contrastive Learning

對比學習入門 A Primer on Contrastive Learning

triplet loss的難點是挖掘困難樣本(hard sampling)。比如:同一個人,姿態不同,或者著裝變了,這就是困難正樣本。兩個不同的人,穿著同樣的衣服,拍攝角度相同,就是困難負樣本。對於batch中的每個樣本,在形成三元組以計算損失時,我們可以選擇batch中最hard的正樣本和最hard的負樣本:

使用hard樣本:

對比學習入門 A Primer on Contrastive Learning

使用所有樣本:

對比學習入門 A Primer on Contrastive Learning

Lifted Embedding loss (Soft版本):

對比學習入門 A Primer on Contrastive Learning

Generalization of the Lifted Embedding loss(Soft版本):

對比學習入門 A Primer on Contrastive Learning

2。3 四元損失Quadruplet losses

Beyond Triplet Loss: A Deep Quadruplet Network for Person Re-Identification

(2017)

每次輸入四個資料,這四個資料都是不同的,其中包含了一對相似資料和一對不相似資料。根據四個資料在模型的輸出和對應的相似資訊計算損失。

對比學習入門 A Primer on Contrastive Learning

直觀的看,當讓Ref和Pos靠近的同時讓Neg和Neg2遠離,並且

D(Ref, Pos)<D(Neg, Neg_2)

,其損失函式為:

對比學習入門 A Primer on Contrastive Learning

第一項就是triplet loss,它著重於最佳化同一樣本的正負對之間的相對距離。第二項是新約束,它考慮了具有不同label的樣本的正負對的距離。在此約束的下,最小的類間距離都必須大於最大的類內距離,進一步增加 intra-class discrepancy。實際應用中一般

\alpha_1>\alpha_2

3、自監督對比學習 Self-Supervised Contrastive Learning

3。1、對比損失 Contrastive loss

對比學習入門 A Primer on Contrastive Learning

其中

f:R^n \rightarrow R^m / S^{m-1}

是encoder函式,將樣本對映到低維空間或低維球表面。

(x,y)

是正樣本對,

x_i^-

是從樣本分佈

p_{data}

中取樣的樣本,

(x,x_i^-),i=1,\cdots,M

M

個負樣本對。

對比損失會使學習的positive pair的特徵相互靠近(pull),同時將來自隨機取樣的negative pair的特徵推開(push)。在下面對齊性和均勻性那一節,我們會具體介紹contrastive loss的性質。

contrastive loss 和 softmax loss有什麼關係呢?

(f(x),f(x_1^-),\cdots,f(x_{M}^-))

(\omega_0, \omega_1,\cdots,\omega_{M})

從而有:

L_{contrastive}(f;\tau,M)=-\log \frac{e^{w_0^Tf(y)}}{e^{w_0^Tf(y)}+\sum_{i=1}^{M}e^{w_i^Tf(y)}} \\

這不就是一個

M+1

的多分類問題麼,

y

要從

(x,x_1^-,\cdots,x_{M}^-)

M+1

個類別中識別出正確的那一個類別

x

,即自己所在的類別。與softmax不同,對於每一個樣本

y

這裡的

(\omega_0, \omega_1,\cdots,\omega_{M})

都是不同的。

3。2、對齊性和均勻性 Alignment and Uniformity

Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere

Alignment

: 一個正對的兩個樣本應該對映成近鄰特徵向量,並且特徵對於噪聲因子是不變的。

Uniformity

: 特徵向量應大致均勻地分佈在單位超球面

S_{m-1}

上,並儘可能保留多的資料資訊。

Alignment

Uniformity

和 softmax loss這篇文章中的

intra-class compactness and inter-class separability

是一致的,並不是一個新的概念,但這篇文章給了這兩個概念更加數學化的表達,並證明了它們是可以實現的。

f:R^n \rightarrow  S^{m-1}

是encoder函式:

\begin{aligned} L_{contrastive}(f;\tau,M) & =-\log \frac{e^{f(x)^Tf(y)}}{e^{f(x)^Tf(y)}+\sum_{i=1}^{M}e^{f(x_i)^Tf(y)}}\\ & = -f(x)^Tf(y)+ \log ({e^{f(x)^Tf(y)}+\sum_{i=1}^{M}e^{f(x_i)^Tf(y)}})\\ &= \frac{1}{2} \Vert f(x)-f(y) \Vert_2^2 -1 + \log ({e^{f(x)^Tf(y)}+\sum_{i=1}^{M}e^{f(x_i)^Tf(y)}}) \end{aligned} \\

將contrastive loss拆成兩項,

\mathcal{L}_{align}

\mathcal{L}_{uniform}

對比學習入門 A Primer on Contrastive Learning

不難看出最佳化

\mathcal{L}_{align}

就是讓相似樣本的歐氏距離儘可能小。文章指出,使得

\mathcal{L}_{uniform}

最小的分佈將弱收斂到球面上的均勻分佈,並且

\mathcal{L}_{contrastive}

有如下漸進性質:

對比學習入門 A Primer on Contrastive Learning

Alignment

Uniformity的視覺化:

對比學習入門 A Primer on Contrastive Learning

文章指出,在下游任務中表現好的模型具有更小的

l_{align}

l_{uniform}

對比學習入門 A Primer on Contrastive Learning

接下來具體介紹幾個CV和NLP中contrastive learning model。

3。3、SimCLR

3。3。1、SimCLR

A Simple Framework for Contrastive Learning of Visual Representations

對比學習入門 A Primer on Contrastive Learning

Data Augmentation:

透過資料增強(crop,resize,recolor)來形成自監督樣本

Encoding

: 將這兩幅影象輸入深度學習模型(Big-CNN,如ResNet),為每幅影象建立向量表示。

Loss Minimization of Representations:

透過最小化對比損失函式來最大化兩個向量表示的相似性。

對比學習入門 A Primer on Contrastive Learning

3。3。2、SimCSE

SimCSE: Simple Contrastive Learning of Sentence Embeddings

SimCSE 是 SimCLR在NLP中的應用,無監督的SimCSE並沒有使用上文提到增、刪、改等資料增強方法,而是使用dropout來給樣本新增噪聲。

We pass the same input sentence to the pre- trained encoder

twice

and obtain two embeddings as “positive pairs”, by applying independently sampled dropout masks。

對比學習入門 A Primer on Contrastive Learning

3。4、CPC

Representation Learning with Contrastive Predictive Coding

CPC用到了 Noise-Contrastive Estimation(NCE) Loss, 在這篇文獻裡定義為InfoNCE:

Given a set

X = {x_1 , . . . x_N }

of

N

random samples containing one positive sample from

p(x_t+k|c_t)

and

N − 1

negative samples from the ‘proposal’ distribution

p(x_t+k),

we optimize:

對比學習入門 A Primer on Contrastive Learning

模型結構:

對比學習入門 A Primer on Contrastive Learning

Encoder

: First, we compress high-dimensional data into a much more compact latent embedding space in which conditional predictions are easier to model。

Contex

: Secondly, we use powerful autoregressive models in this latent space to make predictions many steps in the future。

Loss

: Finally, we rely on Noise-Contrastive Estimation for the loss function in similar ways that have been used for learning word embeddings in natural language models, allowing for the whole model to be trained end-to-end。

文章指出,最佳化contrastive loss其實是在最佳化互資訊的一個下界 (lower bound):

I(x_{t+k},c_t) \geq log(N)-L_N^{opt} \\

3。5、InfoMax Princle

InfoMax 準則像極大似然準則、最大熵準則一樣,是指導機器學習確定最佳化目標、構建損失函式的一種基本準則。InfoMax 準則透過極大化互資訊來最佳化引數:

maximize_{\theta} ~I(f_{\theta}(x);f_\theta(y)), for~(x,y) \sim p_{pos} \\

3。5。1、CV 中的應用

Learning deep representations by mutual information estimation and maximization

1。 Mutual information maximization: Find the set of parameters, ψ, such that the mutual information,

I(X;Eψ(X))

, is maximized。 Depending on the end-goal, this maximization can be done over the complete input, X, or some

structured

or “local” subset。

2。 Statistical constraints: Depending on the end-goal for the representation, the marginal

U_{ψ,P}

should match a prior distribution, V。 Roughly speaking, this can be used to encourage the output of the encoder to have desired characteristics (e。g。, independence)。

DIM透過影象中的區域性特徵來構造對比學習任務。具體來說,要求模型判別全域性特徵和區域性特徵是否來自於同一幅影象:

全域性特徵為錨點(anchor),

f(x)

正樣本為來自同一張影象的區域性特

f(x+)

負樣本為來自不同影象的區域性特徵,

f(x-)

對比學習入門 A Primer on Contrastive Learning

3。5。2、NLP 中的應用

A Mutual Information Maximization Perspective of Language Representation Learning

DIM透過最大化區域性語義和全域性語義的互資訊來預訓練語言模型。

隨機選擇訓練語料中的n-gram

(x_{(i:j)})

,將其mask,作為一個view(作為全域性語義)

將mask掉的n-gram提取出來,作為另一個view(作為區域性語義)

這兩個view都透過Transformer進行編碼,同時隨機取樣其他文字中的n-gram作為負樣本,要求模型識別出正確的n-gram

4、一些腦洞

4。1、Word2Vec

In addition, we present a simplified variant of Noise Contrastive Estimation (NCE) for training the Skip-gram model that results in faster training and better vector representations for frequent words, compared to more complex hierarchical softmax that was used in the prior work。

The main difference between the Negative sampling(NEG) and NCE is that NCE needs both samples and the numerical probabilities of the noise distribution, while Negative sampling uses only samples。

對比學習入門 A Primer on Contrastive Learning

NEG透過二分類來拉開positive sample和negative samples,如果透過多分類來做這件事,損失函式就成了contrastive loss:

\log \frac{e^{v_{wo}^{

4。2、GAN

對比學習入門 A Primer on Contrastive Learning

將loss改成contrastive loss:

\log \frac{D(x)}{D(x)+\sum_{i=1}^nD(G(z_i))} \\

5、總結

本文會從softmax loss出發,推導了softmax loss的公式、討論其性質、並介紹了一些改進方法。然後,介紹contrastive loss及其早期在降維中的應用。隨著深度學習的發展,contrastive loss有了新的formulation,我們繼續討論了contrastive loss的對齊性和均勻性,並介紹中其在CV和NLP中的具體應用。值得注意的是,對比學習具有久遠的歷史,在近幾年的深度學習中,對比學習先是從CV流行起來的,現在NLP領域正在借鑑、改進相關的方法。