본문 바로가기
Study (Data Science)/Paper Research

NNCLR) Nearest-Neighbor Contrastive Learning of Visual Representations (InfoNCE / 2021.10)

by 콜라찡 2023. 3. 15.

Keyword

  • NNCLR
  • InfoNCE

https://arxiv.org/pdf/2104.14548.pdf

 

Paper

With a Little Help from My Friends: Nearest-Neighbor Contrastive Learning of Visual Representations

Debidatta Dwibedi / Google / 2021.10

https://arxiv.org/pdf/2104.14548.pdf

https://github.com/MalteEbner/NNCLR

 

Points

  • Self-supervised learning algorithm
  • NNCLR(NearestNeighbor Contrastive Learning of visual Representations) 을 제시함
  • 같은 데이터에서 추출한 점을 positive라고 하는 것이 아니라, 이에 근접한 이웃점을 positive로 넣기 때문에, 기존의 방법보다 잠재 공간에서의 더 많은 의미를 내포할 수 있음.
  • SimCLR가 베이스인 모델들은 증강이 중요했으나 NNCLR은 데이터 증강이 필요 없는 편. NN instances가 많아서 이로 충분함.
  • 자기지도,준지도,전이 등 여러 방면에 성과가 좋음.

NNCLR은 "Unsupervised Representation Learning by Predicting Image Rotations" 논문에서 제안된 Contrastive Learning 알고리즘 중 하나입니다. 이 알고리즘은 rotation prediction task를 통해 unsupervised representation learning을 수행합니다. 예를 들어, 이미지를 회전시켜 두 개의 이미지 쌍을 만든 뒤, 두 이미지가 같은 이미지인지 다른 이미지인지 판단하는 이진 분류 문제를 학습합니다. 이를 통해, 이미지의 다양한 변형에 대한 일반화 능력을 갖는 표현을 학습할 수 있습니다. NNCLR은 이러한 contrastive learning 알고리즘 중 하나로, SimCLR과 같은 다른 알고리즘과 유사한 구조를 갖고 있습니다.

Abstract

NNCLR은 성능이 좋다는 점을 강조하는 중.

ImageNet : 71.7 >> 75.6%

semi-supervised learning로는 ImageNet의 1% 라벨링 데이터로 53.8 >> 56.5% 향상

transfer learning로는 12개 데이터셋 중 8개가 state-of-art-method로 등극

random crop만 사용해도 ImageNet Top-1 정확도보다 2.1% 밖에 떨어지지 않으므로, 데이터 증강에 덜 의존적임.

 

 

Model

Nearest-Neighbor CLR (NNCLR)

  • SimCLR와 달리 support embedding set (=queue)을 이용하는데, 이 set은 전체 데이터 분포를 대표하는 set이자 모델 학습에 사용되는 데이터 샘플들의 집합이 된다.
  • 큐는 먼저 들어온 데이터가 먼저 나가는 구조이다. (m,d) = (큐의크기, 임베딩차원) 의 행렬로 초기화해서 출발하지만, 모델 학습의 각 단계에서 현재 학습 단계에서의 n (batch size)개의 임베딩이 큐에 붙게 되면서 n만큼의 제일 오래된 데이터는 큐에서 제거된다. 

 

 

  • 인코더에서 임베딩되는 기준은 코사인 유사도.

we maintain an explicit support set of  prior embeddings to increase diversity.

we propose  using nearest- Neighbours to obtain more diverse positive  pairs. This requires keeping a support set of embeddings  which is representative of the full data distribution.  SimCLR uses two augmentations (zi  , z     i  ) to form the  positive pair. Instead, we propose using zi’s nearestneighbor in the support set Q to form the positive pair.

Loss Function

 

infoNCE Loss 공식
SimCLR loss 공식

infoNCE : positive pair와 negative pair을 얼마나 잘 구별할 수 있는지 측정함.

  • instance discrimination 에서 잘 쓰이는 loss
  • T = softmax temperature
  • zi, zi+ : Positive pair
  • zi, zi- : Negative pair
  • SimCLR와 비교했을 때, SimCLR은 동일한 샘플에서 증강시킨 데이터에만 의존하기 때문에 잠재적인 semantic class에 속하는 샘플들과 연관을 지을 수가 없음.

For any given embedded sample zi , we also have another positive embedding z + i (often a random augmentation of the sample), and many negative embeddings z − ∈ Ni .

As SimCLR solely relies on transformations introduced  by pre-defined data augmentations on the same sample, it  cannot link multiple samples potentially belonging to the  same semantic class, which in turn might decrease its capacity to be invariant to large intra-class variations.

infoNCE(Information Noise Contrastive Estimation)는 self-supervised learning에서 사용되는 loss function 중 하나입니다.

이 loss function은 contrastive learning에서 영감을 받았으며, 데이터의 불완전한 버전을 사용하여 모델이 노이즈를 제거하고 정보를 보존하는 방법을 학습합니다.

이를 위해 모델은 원래 데이터와 노이즈가 추가된 데이터를 구분해야합니다. 따라서, infoNCE는 contrastive learning에서 사용되는 loss function 중 하나인 triplet loss와 비슷한 형태를 가지고 있습니다.

# Contrastive Estimation Loss 함수 정의
class InfoNCELoss(nn.Module):
    def __init__(self, temperature):
        super(InfoNCELoss, self).__init__()
        self.temperature = temperature

    def forward(self, x, y):
        x = nn.functional.normalize(x, dim=1)
        y = nn.functional.normalize(y, dim=1)
        batch_size = x.shape[0]
        x = torch.cat((x, y), dim=0)
        labels = torch.arange(0, batch_size, dtype=torch.long)
        labels = torch.cat((labels, labels), dim=0)
        mask = torch.eye(batch_size * 2, dtype=torch.bool)
        loss_fn = nn.CrossEntropyLoss(reduction='sum')
        logits = torch.matmul(x, x.T) / self.temperature
        loss = loss_fn(logits.masked_fill(mask, -float('inf')), labels)
        return loss / (2 * batch_size)

temperature는 InfoNCE loss에서 사용하는 하이퍼파라미터입니다. softmax 함수의 분모에 사용되며, 높을수록 출력이 더 평평하고 낮을수록 더 뾰족해집니다. 이는 학습시 생성된 representation이 더 분리된 형태로 학습될 수 있도록 도와줍니다. 따라서, temperature 값을 실험을 통해 최적의 값으로 결정해야 합니다.

 

 

memory banks와 queues는 샘플링한 일부 데이터를 저장하는 곳입니다. 보통 memory banks는 학습 데이터셋에서 무작위로 샘플링된 K개의 샘플을 저장하며, K는 일반적으로 batch size와 비슷한 값으로 설정됩니다.

Memory banks는 positive examples을 선택하는 데 사용되며, queues는 negative examples을 선택하는 데 사용됩니다. 두 개념 모두 모델 학습의 안정성과 성능에 매우 중요한 역할을 합니다.

 

Result of experiment

  • 실험결과들은 모두 전반적으로 좋았음. Abstract 내용과 중복
  • 라벨이 없어도 되고, 복잡도가 높지 않기 때문에 downstream tasks가 다양할 것으로 예상.

Overall these results demonstrate the effectiveness of nearest neighbor contrastive learning for visual representation without relying heavily on complex augmentations during training which can be computationally expensive or difficult to implement in practice

Limitation

  • NNCLR의 queue의 각 인스턴스에 대한 가장 가까운 이웃들을 저장하려면 많은 양의 메모리가 필요함.
  • 증강이 완전이 안필요한 것은 아님

The paper does not explicitly mention any limitations of the proposed NNCLR method. However, it is worth noting that while their approach reduces reliance on complex data augmentations during training, there may still be some degree of augmentation required to achieve optimal performance in certain scenarios.

728x90

댓글