多模态模型之CLIP模型简介
创作时间:
作者:
@小白创作中心
多模态模型之CLIP模型简介
引用
CSDN
1.
https://blog.csdn.net/yiqiedouhao11/article/details/136330917
介绍
OpenAI CLIP(Contrastive Language–Image Pretraining)是一种由OpenAI开发的多模态学习模型。它能够同时理解图像和文本,并在两者之间建立联系,实现了图像和文本之间的跨模态理解。
如何工作
CLIP模型的工作原理是将来自图像和文本的数据嵌入到一个共同的语义空间中。在这个语义空间中,相关的图像和文本会靠近彼此,而不相关的则会远离彼此。CLIP模型通过对比学习的方式,在这个共同的语义空间中对图像和文本进行编码,从而实现跨模态理解。
# image_encoder - ResNet or Vision Transformer
# text_encoder - CBOW or Text Transformer
# I[n, h, w, c] - minibatch of aligned images
# T[n, l] - minibatch of aligned texts
# W_i[d_i, d_e] - learned proj of image to embed
# W_t[d_t, d_e] - learned proj of text to embed
# t - learned temperature parameter
# extract feature representations of each modality
I_f = image_encoder(I) #[n, d_i]
T_f = text_encoder(T) #[n, d_t]
# joint multimodal embedding [n, d_e]
I_e = l2_normalize(np.dot(I_f, W_i), axis=1)
T_e = l2_normalize(np.dot(T_f, W_t), axis=1)
# scaled pairwise cosine similarities [n, n]
logits = np.dot(I_e, T_e.T) * np.exp(t)
# symmetric loss function
labels = np.arange(n)
loss_i = cross_entropy_loss(logits, labels, axis=0)
loss_t = cross_entropy_loss(logits, labels, axis=1)
loss = (loss_i + loss_t)/2
模型架构
CLIP模型由一个图像编码器和一个文本编码器组成,它们共享参数。图像编码器负责将图像嵌入到语义空间中,而文本编码器则负责将文本嵌入到同样的语义空间中。CLIP模型使用了Transformer架构来实现这两个编码器,这种架构能够处理长距离的依赖关系,并且在大规模数据上进行预训练。
应用
CLIP模型在多个任务上都表现出色,包括但不限于:
- 图像分类:给定一张图像,预测图像所属的类别。
- 图像检索:给定一段文本描述,检索出与描述相匹配的图像。
- 文本分类:给定一段文本,预测文本所属的类别。
- 文本生成:根据给定的文本描述,生成与描述相匹配的图像。
使用示例1
下面是一个使用CLIP模型进行图像分类的Python代码示例:
import os
import clip
import torch
from torchvision.datasets import CIFAR100
# Load the model
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load('ViT-B/32', device)
# Download the dataset
cifar100 = CIFAR100(root=os.path.expanduser("~/.cache"), download=True, train=False)
# Prepare the inputs
image, class_id = cifar100[3637]
image_input = preprocess(image).unsqueeze(0).to(device)
text_inputs = torch.cat([clip.tokenize(f"a photo of a {c}") for c in cifar100.classes]).to(device)
# Calculate features
with torch.no_grad():
image_features = model.encode_image(image_input)
text_features = model.encode_text(text_inputs)
# Pick the top 5 most similar labels for the image
image_features /= image_features.norm(dim=-1, keepdim=True)
text_features /= text_features.norm(dim=-1, keepdim=True)
similarity = (100.0 * image_features @ text_features.T).softmax(dim=-1)
values, indices = similarity[0].topk(5)
# Print the result
print("\nTop predictions:\n")
for value, index in zip(values, indices):
print(f"{cifar100.classes[index]:>16s}: {100 * value.item():.2f}%")
使用示例2
下面是一个使用CLIP模型进行文本-图像相似度检索的Python代码示例:
import torch
import clip
from PIL import Image
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)
image = preprocess(Image.open("CLIP.png")).unsqueeze(0).to(device)
text = clip.tokenize(["a diagram", "a dog", "a cat"]).to(device)
with torch.no_grad():
image_features = model.encode_image(image)
text_features = model.encode_text(text)
logits_per_image, logits_per_text = model(image, text)
probs = logits_per_image.softmax(dim=-1).cpu().numpy()
print("Label probs:", probs) # prints: [[0.9927937 0.00421068 0.00299572]]
总结
CLIP 模型通过对比学习实现了图像和文本之间的跨模态理解,为多种任务提供了强大的支持。
引用
热门推荐
制药工程专业就业前景:未来十年,这个专业凭什么成为“黄金赛道”?
网络安全技术详解:虚拟专用网络(VPN)与安全信息与事件管理(SIEM)
一氧化碳中毒的处置及预防
初中一年级下学期数学成绩提升挑战大?掌握这些技巧,高效逆袭不是梦!
伤口上撒盐能消毒吗?三甲医院教您如何正确处理烧/烫伤
【问题解决】adb remount 失败或刷机无法连接设备(KaiOS)
全球化语境下的翻译策略:挑战与机遇并存
Cell | 遗传密码中的守护者:胰岛素mRNA降解与1型糖尿病的防御机制
中国文化起源之路——第一张完整的玉文化起源路线图(史前版)
二手车值得买吗?购买二手车需要注意哪些细节问题?
原来药品也有“身份证”!快来了解药品追溯码
点亮童年:如何让孩子们在电影中找到情感的寄托
温江绿道骑行全攻略:路线推荐、景点打卡及实用贴士
补气血食物大揭秘:这些食材助你恢复好气色
如何进行技术面分析?这些分析方法有哪些实际应用?
虚拟化技术深入探索虚拟化技术的奥秘虚拟化技术VT开关
志愿服务与基层治理精准高效供给对痛点问题的回应策略
5大技巧助你优化业务系统接口设计
揭秘人性深处:运用这12个策略让你轻松应对人际交往
心教育:解锁心灵密码,拥抱璀璨光芒
心酸!60岁后不工作,1.2亿农村老人养老困境,专家解读生存挑战
丙寅戊戌癸卯甲寅八字命理深度解析
做短视频带货,正规就能有流量吗?这些关键因素帮你提升自然流量
最新研究:复发小肝癌治疗迎来新突破
如何顺利注销汇丰银行账户:详细流程与注意事项
富士相机怎么查电量
一种LPBF用粉末床的多区域温度控制装置的制作方法
超声检查中空腹的那些事
做一个“真”父亲,而不是“形式”父亲——《如父如子》中的教育启示
职场离职指南:撰写优雅辞职信,彰显专业气质与敬意