OpenAI——CLIPs(代码使用示例)

这篇具有很好参考价值的文章主要介绍了OpenAI——CLIPs(代码使用示例)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

OpenAI——CLIPs(打通NLP与CV)

Open AI在2021年1月份发布Contrastive Language-Image Pre-training(CLIP),基于对比文本-图像对对比学习的多模态模型,通过图像和它对应的文本描述对比学习,模型能够学习到文本-图像对的匹配关系。它开源、多模态、zero-shot、few-shot、监督训练均可。
原文原理图:
OpenAI——CLIPs(代码使用示例)
原文算法思想伪代码:
OpenAI——CLIPs(代码使用示例)

OpenAI CLIP 原项目:

https://github.com/openai/CLIP

使用

(一)原版
安装:

$ conda install --yes -c pytorch pytorch=1.7.1 torchvision cudatoolkit=11.0
$ pip install ftfy regex tqdm
$ pip install git+https://github.com/openai/CLIP.git

当然没有GPU和cuda,直接CPU也可以
源码:

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("cat.png")).unsqueeze(0).to(device)  # CLIP.png为本文中图一,即CLIP的流程图
text = clip.tokenize( ["cat in basket", "python", "a cute cat","pytorch","code of CLIP","code of pytorch ","code"]).to(device)  # 将这三句话向量化

with torch.no_grad():
    image_features = model.encode_image(image) # 将图片进行编码
    text_features = model.encode_text(text)    # 将文本进行编码
    # print("image_features shape:",image_features.shape,image_features.size(),image_features.ndim)
    # print("text_features shape:", text_features.shape)

    logits_per_image, logits_per_text = model(image, text)
    # print("logits_per_image shape:",logits_per_image.shape)
    # print("logits_per_text shape:", logits_per_text.shape)
    probs = logits_per_image.softmax(dim=-1).cpu().numpy()


print("Label probs:", probs)  # prints: [[0.9927937  0.00421068 0.00299572]] # 图片"CLIP.png",text["a diagram", "a dog", "a cat"] 对应"a diagram"的概率为0.9927937


####(2)接前:矩阵相乘分类
import pandas as pd
with torch.no_grad():
    score = []
    image_features = model.encode_image(image) # 将图片进行编码
    image_features /= image_features.norm(dim=-1, keepdim=True)
    text_features = model.encode_text(text)    # 将文本进行编码
    text_features /= text_features.norm(dim=-1, keepdim=True)
    # texts = ["cat in basket", "python", "a cute cat","pytorch","code of CLIP","code of pytorch ","code"]
    texts = ["cat in basket", "python", "a cat","pytorch","code","pytorch code"]

    for text in texts:
        textp = clip.tokenize(text)
        # 问题文本编码
        textp_embeddings = model.encode_text(textp)
        textp_embeddings /= textp_embeddings.norm(dim=-1, keepdim=True)

        # 计算图片和问题之间的匹配分数(矩阵相乘)
        sc = float((image_features  @ textp_embeddings.T).cpu().numpy())
        score.append(sc)


    print(pd.DataFrame({'texts': texts, 'score': score}).sort_values('score', ascending=False))
    print('')
    print('-------------------------')
    print('')

(二)transformer库版本
Transformers 库的基本使用:
https://blog.csdn.net/benzhujie1245com/article/details/125279229
安装:

pip install transformers

CLIP源码:

####基本用法二:利用transformer库
from PIL import Image
from transformers import CLIPProcessor,CLIPModel

model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
#这里加入自己图片的地址就行
image = Image.open('cat.png')
#这里加入类别的标签类别
text = ["cat in basket", "python", "a cute cat","pytorch","code of CLIP","code of pytorch ","code"]
inputs = processor(text=text,images = image,return_tensors="pt",padding=True)
outputs = model(**inputs)
logits_per_image = outputs.logits_per_image
probs = logits_per_image.softmax(dim=1)

for i in range(len(text)):
    print(text[i],":",probs[0][i])

输入图片:
OpenAI——CLIPs(代码使用示例)
结果:
OpenAI——CLIPs(代码使用示例)

但是CLIP对于有些比较抽象的图片或任务效果并不一定好,例如:
图片code.png:
OpenAI——CLIPs(代码使用示例)

PLUS:

贴几个其他的使用示例链接:
https://zhuanlan.zhihu.com/p/493489688?utm_id=0
https://zhuanlan.zhihu.com/p/472448018
https://zhuanlan.zhihu.com/p/511460120
https://www.kaggle.com/code/moeinshariatnia/openai-clip-simple-implementation/notebook
https://distill.pub/2021/multimodal-neurons/
CLIP feature改进版:https://github.com/jianjieluo/OpenAI-CLIP-Feature

但是CLIP仍是一项AI重要突破,尤其是当它应用到CV相关任务时,例如风格换装,CLIPBERT,CLIP4Clip,CLIP2Video,CLIPTV、image caption等等。文章来源地址https://www.toymoban.com/news/detail-459549.html

到了这里,关于OpenAI——CLIPs(代码使用示例)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 全网最详细中英文ChatGPT-GPT-4示例文档-从0到1快速入门自然语言指令创建调用OpenAI代码——官网推荐的48种最佳应用(附python/node.js/curl命令源代码,小白也能学)

    ChatGPT是目前最先进的AI聊天机器人,它能够理解图片和文字,生成流畅和有趣的回答。如果你想跟上AI时代的潮流,你一定要学会使用ChatGPT。如果你想了解OpenAI最新发布的GPT-4模型,以及它如何为ChatGPT聊天机器人带来更强大的功能,那么你一定不要错过OpenAI官网推荐的48种最

    2023年04月19日
    浏览(43)
  • Linux使用HTTP代码示例

    以下是使用Linux命令行发送HTTP请求的示例: 1. 使用curl命令发送GET请求: ``` curl Example Domain ``` 2. 使用curl命令发送POST请求: ``` curl -X POST -d \\\"param1=value1param2=value2\\\" Example Domain ``` 3. 使用wget命令发送GET请求: ``` wget Example Domain ``` 4. 使用wget命令发送POST请求: ``` wget --post-data

    2024年02月11日
    浏览(31)
  • C语言使用HTTP代码示例

    这里提供一个C语言使用HTTP请求代码示例: 以上代码实现了一个使用C语言发送HTTP GET请求的程序,需要通过命令行传入目标主机的IP地址和请求路径。程序中,首先创建一个TCP套接字并连接到目标主机的80端口,然后构造GET请求发送到目标主机,并接受目标主机返回的响应并输

    2024年02月11日
    浏览(30)
  • Python使用HTTP代码示例模版

    以下是一个使用Python发送HTTP请求的示例代码模板: ```python import requests # 发送GET请求 def send_get_request(url, params=None, headers=None): response = requests.get(url, params=params, headers=headers) return response # 发送POST请求 def send_post_request(url, data=None, headers=None): response = requests.post(url, data=data, hea

    2024年02月11日
    浏览(40)
  • 示例代码:使用golang进行flink开发

    以下是一个使用 Golang 进行 Flink 开发的简单示例代码: 以上示例代码使用 Flink 的 REST API 连接到 Flink 作业集群,并定义了一个输入数据流和一个输出数据流。然后,使用 Map 操作对输入数据进行处理,并将处理后的数据写入输出数据流。最后,执行作业并等待作业结束。 请注

    2024年02月12日
    浏览(35)
  • 示例代码:使用python进行flink开发

    以下是一个使用 Python 进行 Flink 开发的简单示例代码: 以上示例代码使用 PyFlink 库连接到 Flink 作业集群,并定义了一个输入流和一个输出流。然后,使用 UDF (User Defined Function)对输入数据进行处理,并将处理后的数据写入输出流。最后,执行作业并等待作业结束。 请注意

    2024年02月13日
    浏览(41)
  • PHP使用嵌入HTTP代理代码示例

    以下是使用 PHP 嵌入 HTTP 代理的示例代码: ```php ?php // 设置代理服务器地址和端口 $proxy = \\\'127.0.0.1:8080\\\'; // 设置代理服务器用户名和密码(如果需要验证) $proxyAuth = \\\'username:password\\\'; // 创建 cURL 句柄 $ch = curl_init(); // 设置 cURL 选项 curl_setopt($ch, CURLOPT_URL, \\\'Example Domain\\\'); curl_setopt

    2024年02月06日
    浏览(30)
  • C Sharp使用HTTP代码示例

    以下是使用C#发送HTTP请求的示例代码: ```csharp using System; using System.Net; using System.IO; class Program { static void Main(string[] args) { // 创建一个Web请求对象 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(\\\"Example Domain\\\"); // 设置请求方法为GET request.Method = \\\"GET\\\"; // 发送请求并获取响应 HttpW

    2024年02月06日
    浏览(30)
  • python使用HTTP隧道代理代码示例模板

    以下是使用HTTP隧道代理的Python代码示例模板: ```python import requests # 设置代理服务器地址和端口号 proxy_host = \\\"your_proxy_host\\\" proxy_port = \\\"your_proxy_port\\\" # 设置代理服务器的用户名和密码(如果需要) proxy_username = \\\"your_proxy_username\\\" proxy_password = \\\"your_proxy_password\\\" # 构造代理服务器的认

    2024年02月08日
    浏览(32)
  • Linux使用HTTP隧道代理代码示例模版

    以下是一个使用HTTP隧道代理的示例代码模板: ```python import requests def send_request(url, proxy_host, proxy_port): # 设置代理 proxies = { \\\'http\\\': f\\\'http://{proxy_host}:{proxy_port}\\\', \\\'https\\\': f\\\'http://{proxy_host}:{proxy_port}\\\' } try: # 发送请求 response = requests.get(url, proxies=proxies) # 处理响应 if response.status_code =

    2024年02月12日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包