使用OpenAI CLIP链接图像和文本

使用OpenAI CLIP链接图像和文本

介绍

尽管深度学习给计算机视觉和自然语言处理带来了革命性的变化,但它仍然很难使用最先进的方法,并且需要相当多的专业知识。

[En]

Although deep learning has revolutionized computer vision and natural language processing, it is still difficult to use the most advanced methods and requires considerable expertise.

诸如对比语言图像预训练(CLIP)等OpenAI方法旨在降低这种复杂性,从而使开发人员能够专注于实际案例。

CLIP是一种在大量图像和文本对上训练的神经网络。作为这种多模态训练的结果,CLIP可用于查找最能代表图像的文本片段,或查找给定文本查询的最合适图像。

这使得CLIP在图像和文本搜索中非常有用。

它是如何工作的?

对CLIP进行训练,以便给定一幅图像,它可以预测该图像与训练数据集中32768个随机采样的文本片段中的哪一个配对。其思想是,为了解决任务,模型需要从图像中学习多个概念。

这种方法与传统的图像任务有很大不同,在传统的图像任务中,通常需要使用模型从大量的类(例如ImageNet)中识别一个类。

总之,CLIP联合训练图像编码器(如ResNet50)和文本编码器(如BERT),以预测一批图像和文本的正确配对。

使用OpenAI CLIP链接图像和文本

如果希望使用该模型进行分类,可以通过文本编码器嵌入这些类并与图像匹配。此过程通常称为ZERO-SHOT学习。

开始

以下部分介绍如何在Google Colab中设置CLIP,以及如何使用CLIP进行图像和文本搜索。

安装

要使用CLIP,我们首先需要安装一组依赖项。为了促进这一点,我们将通过Conda安装它们。此外,Google Colab还将用于简化复制。

1.打开谷歌Colab

在浏览器中打开以下URL:https://research.google.com/colaboratory/

然后,单击屏幕底部的新Python3笔记本链接。

正如你可能注意到的,笔记本电脑界面与Jupyter提供的界面类似。有一个代码窗口,你可以在其中输入Python代码。

2.在Colab中检查Python

要安装正确的Conda版本以与Colab协同工作,我们首先需要知道Colab使用的是哪个Python版本。在colab类型的第一个单元格中执行此操作

%%bash

which python
python --version

这应该返回类似于

/usr/local/bin/python 
Python 3.7.10

3.安装 Conda

在浏览器中打开以下URL:https://repo.anaconda.com/miniconda/

然后复制与上面输出中指示的主要Python版本相对应的miniconda版本名。miniconda版本应该类似于”Miniconda3-py{VERSION}-Linux-x86_64.sh”。

最后,在colab的新单元格中键入以下代码段,确保conda_version变量设置正确。

%%bash

# 确保conda路径是清晰的,所以它不会与conda冲突
export PYTHONPATH=""

# 下载并安装miniconda
conda_version='Miniconda3-py37_4.9.2-Linux-x86_64.sh'
wget https://repo.anaconda.com/miniconda/${conda_version}
chmod +x ${conda_version}
./${conda_version} -b -f -p /usr/local

# 更新miniconda
conda install --channel defaults conda python=3.7 --yes
conda update --channel defaults --all --yes

再次确认Python主版本仍然相同

%%bash

which python
python --version

这应该返回类似于

/usr/local/bin/python 
Python 3.7.10

4.安装CLIP+依赖

Conda现在应该准备好了。下一步是使用Conda将依赖项安装到CLIP模型(pytorch、torchvision和cudatoolkit),然后安装CLIP库本身。

为此,将以下代码段复制到Colab中。

%%bash

# 安装依赖
conda install --yes -c pytorch pytorch=1.7.1 torchvision cudatoolkit=11.0
pip install ftfy regex tqdm

# 安装clip
pip install git+https://github.com/openai/CLIP.git

由于所需的库很大,此步骤可能需要一些时间。

[En]

Due to the large library required, this step may take some time.

5.将conda路径附加到sys

使用CLIP之前的最后一步是将conda site-packages路径附加到sys。否则,在Colab环境中可能无法正确识别已安装的软件包。

import sys

# 确保在这里可以识别conda库
_ = sys.path.append("/usr/local/lib/python3.7/site-packages")

文本和图像

我们的环境现在可以使用了。

[En]

Our environment is now ready for use.

1.导入CLIP模型

要使用CLIP,请先导入所需的库并加载模型。为此,请将以下代码段复制到Colab。

import torch
import clip

device = "cuda" if torch.cuda.is_available() else "cpu"

# 加载模型和图像预处理
model, preprocess = clip.load("ViT-B/32", device=device, jit=False)

这应该会显示返回值,如下所示,表示模型已正确加载。

[En]

This should display the return value, as shown below, indicating that the model is loaded correctly.

100%|███████████████████████████████████████| 354M/354M [00:11

2.提取图像嵌入

现在,让我们使用以下示例图像来测试该模型

[En]

Now let’s test the model using the following example image

使用OpenAI CLIP链接图像和文本

为此,将以下代码段复制到Colab。此代码将首先使用PIL加载图像,然后使用CLIP模型对其进行预处理。

from PIL import Image
import requests

# 设置图片的URL
image_name = "pexels-photo-1485637.jpeg"
image_url = f"https://images.pexels.com/photos/1485637/{image_name}?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"

# 加载图片
image = Image.open(requests.get(image_url, stream=True).raw)
print("Image to be processed")
display(image)

# 预处理图像
image = preprocess(image).unsqueeze(0).to(device)
print("\n\nTensor shape:")
print(image.shape)

这应该会显示样本图像,然后显示处理后的图像张量。

[En]

This should display the sample image, and then display the processed image tensor.

Tensor shape: 
torch.Size([1, 3, 224, 224])

现在可以通过调用CLIP模型中的”encode_image”方法提取图像特征,如下所示

with torch.no_grad():
    image_features = model.encode_image(image)
print(image_features.shape)

这将返回图像特征张量的大小。

[En]

This returns the size of the image feature tensor.

torch.Size([1, 512])

3.提取文本嵌入

让我们创建一组文本片段,它们以以下方式嵌入不同的类值:“类的照片”。

[En]

Let’s create a set of text snippets that embed different class values in the following way: “photos of the class.”

然后我们可以运行clip-tokeniser来预处理代码片段。

text_snippets = ["a photo of a dog", "a photo of a cat", "a photo of a tiger"]

# 预处理文本
text = clip.tokenize(text_snippets).to(device)
print(text.shape)

这将返回文本张量形状

torch.Size([3, 77])

现在可以通过从CLIP模型中调用”encode_text”方法来提取文本特征,如下所示

with torch.no_grad():
    text_features = model.encode_text(text)
print(text_features.shape)

4.比较图像嵌入和文本嵌入

因为我们现在嵌入了图像和文本,所以我们可以比较每种组合,并根据相似性对它们进行排序。

[En]

Because we now have image and text embedding, we can compare each combination and sort them according to similarity.

为此,我们只需在两个嵌入上调用模型并计算softmax。

with torch.no_grad():
    logits_per_image, logits_per_text = model(image, text)
    probs = logits_per_image.softmax(dim=-1).cpu().numpy()

print("Label probs:", probs)

这将返回以下输出。

Label probs: [[0.9824866 0.00317319 0.01434022]]

不出所料,我们可以观察到,《狗的照片》的文字片段与样本图像的相似度最高。

[En]

As expected, we can observe that the text fragment of “the photo of the dog” has the highest similarity with the sample image.

现在,您可以使文本查询包含更多上下文,并查看它们之间的比较。举个例子,如果你加上“一只狗在草地上奔跑的图片”,你觉得它会是什么样子?

[En]

Now you can make the text query contain more context and see the comparison between them. For example, if you add “a picture of a dog running on the grass”, what do you think it will look like?

结论

CLIP是一种功能极其强大的图像和文本嵌入模型,可用于查找最能代表给定图像的文本片段(如在经典分类任务中),或查找给定文本查询的最合适图像(如图像搜索)。

它不仅功能强大,而且非常易于使用。该模型可以很容易地嵌入到API中,例如通过AWS lambda函数提供。

[1] Openai. ” CLIP: Connecting Text and Images” https://openai.com/blog/clip/#rf36

[2] Alec Radford, Jong Wook Kim, Chris Hallacy et al. ” Learning Transferable Visual Models From Natural Language Supervision” arXiv:2103.00020(https://arxiv.org/abs/2103.00020)

☆ END ☆

如果看到这里,说明你喜欢这篇文章,请转发、点赞。微信搜索「uncle_pn」,欢迎添加小编微信「 woshicver」,每日朋友圈更新一篇高质量博文。

↓ 扫描二维码添加小编↓

使用OpenAI CLIP链接图像和文本

Original: https://blog.csdn.net/woshicver/article/details/121059321
Author: woshicver
Title: 使用OpenAI CLIP链接图像和文本

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/511544/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球