什么值得买App下载 App ›
连续签到专享现金活动

新手入门!10分钟吃透CLIP多模态核心:从公式拆解到手写数字零样本分类(附服务器可跑全代码)

在AI多模态领域,OpenAI的CLIP(Contrastive Language-Image Pre-training)凭借“零微调就能跨场景匹配图文”的能力,成为DALL·E、Stable Diffusion等生成式模型的地基。CLIP旨在打破传统图像分类模型“死记硬背”的封闭牢笼,实现零样本能力,即无需任何微调,仅凭文本提示即可识别从未训练过的类别。其核心逻辑在于通过图文对比学习,让模型学会“看图识文、看文识图”的通用关联。
01CLIP架构与核心原理
CLIP的架构包含两个核心编码器和一个匹配机制。图像编码器和文本编码器分别负责将图像和文本转换为特征向量。由于原始特征维度不同(如图像特征768维,文本特征512维),无法直接计算相似度,CLIP引入了投影层,将两者映射到同一维度的多模态空间(默认512维),并进行L2归一化处理。
公式层面,图像嵌入 $I_e$ 和文本嵌入 $T_e$ 的计算方式如下:
$$\begin{align*} I_e &= \frac{I_f \cdot W_i}{\|I_f \cdot W_i\|_2} \\ T_e &= \frac{T_f \cdot W_t}{\|T_f \cdot W_t\|_2} \end{align*}$$
其中,$I_f$ 和 $T_f$ 分别为图像和文本的原始特征,$W_i$ 和 $W_t$ 为可学习的投影矩阵。
CLIP的训练目标是最大化正确图文对的相似度,同时最小化错误对的相似度。假设一个训练批次包含N对图文,模型会计算N×N的相似度矩阵,利用交叉熵损失函数进行优化。训练完成后,推理过程无需微调,只需将图片与文本标签集进行特征匹配,计算余弦相似度即可实现分类。
02代码实操:手写数字零样本分类
基于上述原理,以下代码实现了对手写数字的零样本分类。项目使用Sklearn内置的Digits数据集(1797个8×8样本),无需额外下载数据。环境配置推荐使用清华源安装依赖,代码运行后将自动保存4合1结果图。
1. 环境配置:
在服务器端执行以下命令安装所需库:
pip install torch torchvision scikit-learn matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple
2. 核心代码(clip_digits.py):
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import numpy as np

# 1. 简易图像编码器 (模拟CNN)
class SimpleImageEncoder(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 16, 3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.fc = nn.Linear(16 * 4 * 4, 128) # 8x8 -> 4x4

def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = x.view(-1, 16 * 4 * 4)
return self.fc(x)

# 2. 简易文本编码器 (模拟随机投影+简单MLP,实际CLIP用Transformer)
class SimpleTextEncoder(nn.Module):
def __init__(self, embed_dim=512):
super().__init__()
self.embedding = nn.Embedding(10, 32) # 假设词表大小10(0-9)
self.fc = nn.Linear(32, 128)

def forward(self, x):
x = self.embedding(x).mean(dim=1) # 简单平均池化
return self.fc(x)

# 3. 模拟CLIP模型
class SimpleCLIP(nn.Module):
def __init__(self):
super().__init__()
self.image_encoder = SimpleImageEncoder()
self.text_encoder = SimpleTextEncoder()
# 投影层到同一维度
self.image_projection = nn.Linear(128, 64)
self.text_projection = nn.Linear(128, 64)
self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))

def forward(self, image, text):
image_features = self.image_encoder(image)
text_features = self.text_encoder(text)

# 归一化并投影
image_embeds = F.normalize(self.image_projection(image_features), dim=1)
text_embeds = F.normalize(self.text_projection(text_features), dim=1)

# 计算相似度
logit_scale = self.logit_scale.exp()
logits_per_image = logit_scale * image_embeds @ text_embeds.t()
logits_per_text = logits_per_image.t()
return logits_per_image, logits_per_text

# 数据准备
digits = load_digits()
X = digits.images.reshape(-1, 1, 8, 8).astype('float32') / 16.0
# 简单的文本标签映射:数字0-9
y_text = torch.arange(10).repeat(len(X) // 10 + 1)[:len(X)]

# 模拟训练(实际CLIP是大规模预训练)
model = SimpleCLIP()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

# 这里仅演示推理流程(Zero-Shot),跳过耗时的大规模训练步骤
# 假设模型已经具备了通用匹配能力
model.eval()

# 构建文本提示词集合 (0-9)
text_prompts = torch.arange(10)
with torch.no_grad():
text_features = model.text_encoder(text_prompts)
text_embeds = F.normalize(model.text_projection(text_features), dim=1)

# 随机选4张图进行测试
indices = np.random.choice(len(X), 4, replace=False)
test_images = torch.tensor(X[indices])

fig, axs = plt.subplots(2, 2, figsize=(8, 8))
axs = axs.ravel()

with torch.no_grad():
image_features = model.image_encoder(test_images)
image_embeds = F.normalize(model.image_projection(image_features), dim=1)

# 计算相似度
similarities = (image_embeds @ text_embeds.t()).cpu().numpy()

for i, idx in enumerate(indices):
axs[i].imshow(digits.images[idx], cmap='gray')
probs = similarities[i]
predicted = probs.argmax()
confidence = probs[predicted]
axs[i].set_title(f"Pred: {predicted} ({confidence:.2f})")
axs[i].axis('off')

plt.tight_layout()
plt.savefig('clip_digits_result.png')
print("结果图已保存为 clip_digits_result.png")
03总结与拓展
CLIP的核心价值在于通过简单的对比学习逻辑实现了跨模态的通用理解。通过上述手写数字项目,可以直观掌握CLIP从特征映射到相似度计算的完整流程。对于进一步的研究,可尝试更换不同的数据集、调整文本提示词的构造方式,或者探索更复杂的编码器结构以提升模型性能。

评论

评论区空态插画

当前文章无评论,是时候发表评论了