多模态 AI 实验
从 GitHub 前沿仓库提炼的多模态实验:CLIP 式图文对齐思想、向量检索、OCR 全流程,属于未完成但有研究价值的代码。
项目简介
多模态(Multimodal)指模型同时理解 文本、图像、音频 等信息。本页围绕“图文对齐”给出三个最小实验:特征提取、跨模态检索、OCR 流水线,帮助理解多模态模型的基本数据流。
代码示例:图文特征提取(CLIP 思路)
py
from PIL import Image
import torch
# 需 pip install open_clip_torch
import open_clip
model, _, preprocess = open_clip.create_model_and_transforms(
"ViT-B-32", pretrained="laion2b_s34b_b79k"
)
tokenizer = open_clip.get_tokenizer("ViT-B-32")
def encode_text(texts: list[str]) -> torch.Tensor:
tokens = tokenizer(texts)
with torch.no_grad():
return model.encode_text(tokens)
def encode_image(path: str) -> torch.Tensor:
img = preprocess(Image.open(path)).unsqueeze(0)
with torch.no_grad():
return model.encode_image(img)
# 计算余弦相似度判断“图文是否匹配”
t = encode_text(["一只猫", "一片海"])
i = encode_image("cat.jpg")
print((i @ t.T).softmax(dim=-1))代码示例:跨模态向量检索
py
import numpy as np
# 用 FAISS 建索引:把图片特征存库,用文本特征查询
# pip install faiss-cpu
import faiss
def build_index(vectors: list[np.ndarray]):
d = vectors[0].shape[0]
index = faiss.IndexFlatIP(d) # 内积 = 余弦(归一化后)
mat = np.vstack(vectors).astype("float32")
faiss.normalize_L2(mat)
index.add(mat)
return index
def query(index, text_vec: np.ndarray, k: int = 5):
q = text_vec.astype("float32").reshape(1, -1)
faiss.normalize_L2(q)
scores, idx = index.search(q, k)
return idx[0], scores[0]代码示例:OCR 全流程
py
# pip install paddleocr paddlepaddle
from paddleocr import PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, lang="ch")
def ocr_image(path: str):
result = ocr.ocr(path, cls=True)
lines = []
for line in result:
for item in line:
text = item[1][0]
conf = item[1][1]
lines.append((text, round(conf, 3)))
return lines
# 输出后接正则清洗 + 结构化入库,即为完整文档数字化流水线待完成方向
- 接入真实图文数据集做 zero-shot 分类实验。
- 把 OCR 结果接入命名实体识别(NER),构建知识库。
- 尝试视频帧采样 + 图文对齐做视频检索。
- 评估不同骨干(ViT / ConvNeXt)在中文场景的表现差异。
操作步骤
pip install open_clip_torch faiss-cpu pillow安装依赖。- 准备一张猫的图片运行图文相似度示例,观察匹配分数。
- 把多张图片建索引,再用文字查询返回 Top-K,即完成检索闭环。
来源参考
GitHub 关键词:open_clip、multimodal-retrieval-demo、paddleocr-pipeline(链接可替换为实际仓库地址)。