【Paddle-CLIP】使用 CLIP 模型进行图像识别
引入
上回介绍了如何搭建模型并加载参数进行模型测试本次就详细介绍一下 CLIP 模型的各种使用CLIP 模型的用途
可通过模型将文本和图像进行编码
免费影视、动漫、音乐、游戏、小说资源长期稳定更新! 👉 点此立即查看 👈
然后通过计算相似度得出文本与图像之间的关联程度
模型大致的架构图如下:
项目说明
项目 GitHub:【Paddle-CLIP】有关模型的相关细节,请看上一个项目:【Paddle2.0:复现 OpenAI CLIP 模型】安装 Paddle-CLIP
In [ ]!pip install paddleclip登录后复制
加载模型
首次加载会自动下载预训练模型,请耐心等待In [ ]import paddlefrom PIL import Imagefrom clip import tokenize, load_modelmodel, transforms = load_model('ViT_B_32', pretrained=True)登录后复制 图像识别
使用预训练模型输出各种候选标签的概率In [ ]# 设置图片路径和标签img_path = "apple.webp"labels = ['apple', 'fruit', 'pear', 'peach']# 准备输入数据img = Image.open(img_path)display(img)image = transforms(Image.open(img_path)).unsqueeze(0)text = tokenize(labels)# 计算特征with paddle.no_grad(): logits_per_image, logits_per_text = model(image, text) probs = paddle.nn.functional.softmax(logits_per_image, axis=-1)# 打印结果for label, prob in zip(labels, probs.squeeze()): print('该图片为 %s 的概率是:%.02f%%' % (label, prob*100.))登录后复制 登录后复制
该图片为 apple 的概率是:83.19%该图片为 fruit 的概率是:1.25%该图片为 pear 的概率是:6.71%该图片为 peach 的概率是:8.84%登录后复制 In [ ]
# 设置图片路径和标签img_path = "fruit.webp"labels = ['apple', 'fruit', 'pear', 'peach']# 准备输入数据img = Image.open(img_path)display(img)image = transforms(Image.open(img_path)).unsqueeze(0)text = tokenize(labels)# 计算特征with paddle.no_grad(): logits_per_image, logits_per_text = model(image, text) probs = paddle.nn.functional.softmax(logits_per_image, axis=-1)# 打印结果for label, prob in zip(labels, probs.squeeze()): print('该图片为 %s 的概率是:%.02f%%' % (label, prob*100.))登录后复制 登录后复制
该图片为 apple 的概率是:8.52%该图片为 fruit 的概率是:90.30%该图片为 pear 的概率是:0.98%该图片为 peach 的概率是:0.21%登录后复制
Zero-Shot
使用 Cifar100 的测试集测试零次学习In [1]import paddlefrom clip import tokenize, load_modelfrom paddle.vision.datasets import Cifar100# 加载模型model, transforms = load_model('ViT_B_32', pretrained=True)# 加载 Cifar100 数据集cifar100 = Cifar100(mode='test', backend='pil')classes = [ 'apple', 'aquarium_fish', 'baby', 'bear', 'beaver', 'bed', 'bee', 'beetle', 'bicycle', 'bottle', 'bowl', 'boy', 'bridge', 'bus', 'butterfly', 'camel', 'can', 'castle', 'caterpillar', 'cattle', 'chair', 'chimpanzee', 'clock', 'cloud', 'cockroach', 'couch', 'crab', 'crocodile', 'cup', 'dinosaur', 'dolphin', 'elephant', 'flatfish', 'forest', 'fox', 'girl', 'hamster', 'house', 'kangaroo', 'keyboard', 'lamp', 'lawn_mower', 'leopard', 'lion', 'lizard', 'lobster', 'man', 'maple_tree', 'motorcycle', 'mountain', 'mouse', 'mushroom', 'oak_tree', 'orange', 'orchid', 'otter', 'palm_tree', 'pear', 'pickup_truck', 'pine_tree', 'plain', 'plate', 'poppy', 'porcupine', 'possum', 'rabbit', 'raccoon', 'ray', 'road', 'rocket', 'rose', 'sea', 'seal', 'shark', 'shrew', 'skunk', 'skyscraper', 'snail', 'snake', 'spider', 'squirrel', 'streetcar', 'sunflower', 'sweet_pepper', 'table', 'tank', 'telephone', 'television', 'tiger', 'tractor', 'train', 'trout', 'tulip', 'turtle', 'wardrobe', 'whale', 'willow_tree', 'wolf', 'woman', 'worm']# 准备输入数据image, class_id = cifar100[3637]display(image)image_input = transforms(image).unsqueeze(0)text_inputs = tokenize(["a photo of a %s" % c for c in classes])# 计算特征with paddle.no_grad(): image_features = model.encode_image(image_input) text_features = model.encode_text(text_inputs)# 筛选 Top_5image_features /= image_features.norm(axis=-1, keepdim=True)text_features /= text_features.norm(axis=-1, keepdim=True)similarity = (100.0 * image_features @ text_features.t())similarity = paddle.nn.functional.softmax(similarity, axis=-1)values, indices = similarity[0].topk(5)# 打印结果for value, index in zip(values, indices): print('该图片为 %s 的概率是:%.02f%%' % (classes[index], value*100.))登录后复制 Cache file /home/aistudio/.cache/paddle/dataset/cifar/cifar-100-python.tar.gz not found, downloading https://dataset.bj.bcebos.com/cifar/cifar-100-python.tar.gz Begin to downloadDownload finished登录后复制
登录后复制
该图片为 snake 的概率是:65.31%该图片为 turtle 的概率是:12.29%该图片为 sweet_pepper 的概率是:3.83%该图片为 lizard 的概率是:1.88%该图片为 crocodile 的概率是:1.75%登录后复制
逻辑回归
使用模型的图像编码和标签进行逻辑回归训练使用的数据集依然是 Cifar100In [ ]import osimport paddleimport numpy as npfrom tqdm import tqdmfrom paddle.io import DataLoaderfrom clip import tokenize, load_modelfrom paddle.vision.datasets import Cifar100from sklearn.linear_model import LogisticRegression# 加载模型model, transforms = load_model('ViT_B_32', pretrained=True)# 加载数据集train = Cifar100(mode='train', transform=transforms, backend='pil')test = Cifar100(mode='test', transform=transforms, backend='pil')# 获取特征def get_features(dataset): all_features = [] all_labels = [] with paddle.no_grad(): for images, labels in tqdm(DataLoader(dataset, batch_size=100)): features = model.encode_image(images) all_features.append(features) all_labels.append(labels) return paddle.concat(all_features).numpy(), paddle.concat(all_labels).numpy()# 计算并获取特征train_features, train_labels = get_features(train)test_features, test_labels = get_features(test)# 逻辑回归classifier = LogisticRegression(random_state=0, C=0.316, max_iter=1000, verbose=1, n_jobs=-1)classifier.fit(train_features, train_labels)# 模型评估predictions = classifier.predict(test_features)accuracy = np.mean((test_labels == predictions).astype(np.float)) * 100.# 打印结果print(f"Accuracy = {accuracy:.3f}")登录后复制 /home/aistudio/Paddle-CLIPAccuracy = 79.900登录后复制
相关攻略
Pywinrm 通过Windows远程管理(WinRM)协议,让Python能够像操作本地一样执行远程Windows命令,真正打通了跨平台管理的最后一公里。 在混合IT环境中,Linux机器管理Wi
早些时候,聊过 Python 领域那场惊心动魄的供应链攻击。当时我就感叹,虽然我们 JavaScript 开发者对这类套路烂熟于心,但亲眼目睹这种规模的“投毒”还是头一次。 早些时候,聊过 Pyth
Toga 是 BeeWare 家族的核心成员,号称“写一次,跑遍所有平台”,而且用的是系统原生控件,不是那种一看就是网页套壳的界面 。 写了这么多年 Python,你是不是也想过:要是能一套代码跑
异常处理的核心:让错误在正确的地方被有效处理。正确的地方,就是别在底层就把异常吞了,也别在顶层还抛裸奔的 Exception。 异常处理写得好,半夜不用起来改 bug。1 你是不是也这么干过?tr
1 Skills机制概述 提起OpenClaw的Skills机制,不少人可能会把它想象成传统意义上的可执行插件。其实,它的内涵要更精妙一些。 简单说,Skills本质上是一套基于提示驱动的能力扩展机制。它并不是一个可以独立“跑”起来的程序模块,而是通过一份结构化描述文件(核心就是那个SKILL m
热门专题
热门推荐
加密货币行业翘首以盼的监管里程碑,终于有了实质性进展。美国证券交易委员会(SEC)主席保罗·阿特金斯(Paul Atkins)近日证实,那份允许加密项目在早期获得注册豁免权的“安全港”框架提案,已经正式送抵白宫,进入了最终审查阶段。 在范德堡大学与区块链协会联合举办的数字资产峰会上,阿特金斯透露了这
微策略Strategy报告:第一季录得144 6亿美元浮亏 再斥资约3 3亿美元买进4871枚比特币 市场震荡的威力有多大?看看Strategy的最新季报就明白了。根据其最新向美国证管会(SEC)提交的8-K报告,受市场剧烈波动影响,这家公司所持的比特币在第一季度录得了一笔惊人的数字——144 6亿
稳定币巨头Tether的动向,向来是加密世界的风向标。这不,它向Web3基础设施的版图扩张,又迈出了关键一步。公司执行长Paolo Ardoino在社交平台X上透露,其工程团队正在全力“烹制”一个新项目——去中心化搜索引擎 “Hypersearch”。这个消息一出,立刻引发了行业的广泛猜想。 采用D
基地位于Coinbase旗下以太坊Layer2网络Base的Seamless Protocol,日前正式宣告了服务的终结。这个曾经吸引了超过20万用户的原生DeFi借贷协议,在运营不到三年后,终究没能跑赢时间。它主打的核心产品是Integrated Leverage Markets(ILMs)——一
PAAL代币揭秘:深度解析Web3社区治理的核心钥匙 在去中心化自治组织的浪潮中,谁真正掌握了项目的话语权?PAAL代币提供了一套系统化的答案。它不仅是生态内流转的价值媒介,更是开启链上治理大门的核心凭证。通过持有并质押PAAL代币,用户能够对协议升级、资金分配乃至战略方向等关键事务投出决定性的一票





