CLIP 论文解读 & 实践总结

1,103 阅读2分钟

在前面的某篇文章中,我们提到了 clip :一个用于做多模态图像文本的匹配模型。刚好近期工作也需要用到,所以来学习一下这个模型。

介绍

以前 sota 的 cv 模型都是基于图片分类监督任务来训练的,而监督数据受限制在特定的图像领域,会导致模型的泛化性、可用性变差。本文直接利用4个亿的image caption数据来学习图片表示,而文本的融入会使得模型快速在 downstream 任务中得以应用,不需要做额外的 finetuning。

方法

模型整体训练思路如下图(1), 训练样本是(image,text)pair对,分别用 文本 encoder(例如 transformer)和图片 encoder(resnet) 抽取文本和图像的特征表示,然后将两者的特征表示做相似度训练。 在测试的时候,利用任意的 encoder 得到label文本表示,然后将图片encoder的特征和label的特征做相似度计算,选择得分最高的,就是这个图片对应的 label 啦。

截屏2023-02-07 下午7.48.53.png

实践

这里,主要介绍一下如何快速在自己的任务中,尝试模型效果。我选择的时候 hugging face 和 ida 研究院联合发布的模型.实践如下:

  • 使用方法如下:
from PIL import Image
import requests
import clip
import torch
from transformers import BertForSequenceClassification, BertConfig, BertTokenizer
from transformers import CLIPProcessor, CLIPModel
import numpy as np

query_texts = ["一只猫", "一只狗",'两只猫', '两只老虎','一只老虎']  # 这里是输入文本的,可以随意替换。
# 加载Taiyi 中文 text encoder
text_tokenizer = BertTokenizer.from_pretrained("IDEA-CCNL/Taiyi-CLIP-Roberta-large-326M-Chinese")
text_encoder = BertForSequenceClassification.from_pretrained("IDEA-CCNL/Taiyi-CLIP-Roberta-large-326M-Chinese").eval()
text = text_tokenizer(query_texts, return_tensors='pt', padding=True)['input_ids']

url = "<http://images.cocodataset.org/val2017/000000039769.jpg>"  # 这里可以换成任意图片的url
# 加载CLIP的image encoder
clip_model = CLIPModel.from_pretrained("openai/clip-vit-large-patch14")  
processor = CLIPProcessor.from_pretrained("openai/clip-vit-large-patch14")
image = processor(images=Image.open(requests.get(url, stream=True).raw), return_tensors="pt")

with torch.no_grad():
    image_features = clip_model.get_image_features(**image)
    text_features = text_encoder(text).logits
    # 归一化
    image_features = image_features / image_features.norm(dim=1, keepdim=True)
    text_features = text_features / text_features.norm(dim=1, keepdim=True)
    # 计算余弦相似度 logit_scale是尺度系数
    logit_scale = clip_model.logit_scale.exp()
    logits_per_image = logit_scale * image_features @ text_features.t()
    logits_per_text = logits_per_image.t()
    probs = logits_per_image.softmax(dim=-1).cpu().numpy()
    print(np.around(probs, 3))
pip install pillow
pip3 install torch torchvision torchaudio --extra-index-url <https://download.pytorch.org/whl/cu116>
pip install transformers

模型下载

在上述页面中,找到 “files and versions” tab 即可下载模型,或者直接 git clone 项目

git clone https://huggingface.co/IDEA-CCNL/Taiyi-CLIP-Roberta-large-326M-Chinese
git clone https://huggingface.co/openai/clip-vit-base-patch32

总结

感觉整个训练思路,就一整个被打开了。把分类任务当做匹配任务来做,以前也接触过,但是像这样,把这种想法用来训练,并且是图片和文本的结合,还是令人耳目一新,并且效果惊人!大道至简,大概就是这样吧。

开启掘金成长之旅!这是我参与 「掘金日新计划 · 2 月更文挑战」的第 7 天,点击查看活动详情