使用向量数据库pinecone构建应用01:相似语义检索 Semantic Search

news2024/9/22 17:30:14

Building Applications with Vector Databases

下面是DeepLearning.AI上面这门课的学习笔记:https://www.deeplearning.ai/short-courses/building-applications-vector-databases/

Learn to create six exciting applications of vector databases and implement them using Pinecone.

Build a hybrid search app that combines both text and images for improved multimodal search results.

Learn how to build an app that measures and ranks facial similarity.

文章目录

  • Building Applications with Vector Databases
    • Lesson 1 - Semantic Search
      • Import the Needed Packages
      • Load the Dataset
      • Check cuda and Setup the model
      • Setup Pinecone
      • Create Embeddings and Upsert to Pinecone
      • Run Your Query

ChatGPT对Pinecone的介绍

Pinecone 是一个专门用于快速高效地进行向量索引和检索的托管服务。它主要用于存储和查询大规模的向量数据,例如文本嵌入、图像特征等。Pinecone 提供了一个简单易用的 API,使开发人员能够轻松地构建和部署基于向量的应用程序,而无需担心底层的基础架构。

使用 Pinecone,开发人员可以将向量数据加载到 Pinecone 的索引中,然后通过查询接口快速地检索相似向量。这种快速检索的能力使 Pinecone 在许多应用场景下都非常有用,如推荐系统、相似性搜索、聚类分析等。

总的来说,Pinecone 提供了一个高性能、可扩展且易于使用的平台,使开发人员能够利用向量数据来构建更智能和响应更快的应用程序。

Lesson 1 - Semantic Search

相似语义检索:检索相似的问题

在这里插入图片描述

requirements.txt

# requirements file
# note which revision of python, for example 3.9.6
# in this file, insert all the pip install needs, include revision

#for example:
#torch==2.0.1
#matplotlib==3.7.2

python-dotenv==1.0.0

numpy==1.25.2
pandas==2.1.3
scikit-learn==1.3.2
sentence-transformers==2.2.2
matplotlib==3.8.2
torch==2.1.1

langchain==0.0.346
openai==0.28.1 ## From the notebooks

pinecone-client==3.0.0dev4
pinecone-datasets==0.5.0rc11
pinecone-text==0.7.1

tiktoken==0.5.2
tqdm==4.66.1

datasets==2.15.0
deepface==0.0.79

Import the Needed Packages

import warnings
warnings.filterwarnings('ignore')
from datasets import load_dataset
from sentence_transformers import SentenceTransformer
from pinecone import Pinecone, ServerlessSpec
from DLAIUtils import Utils
import DLAIUtils

import os
import time
import torch
from tqdm.auto import tqdm

其中DLAIUtils.py文件如下所示:

import os
import sys
from dotenv import load_dotenv, find_dotenv

class Utils:
  def __init__(self):
    pass
  
  def create_dlai_index_name(self, index_name):
    openai_key = ''
    if self.is_colab(): # google colab
      from google.colab import userdata
      openai_key = userdata.get("OPENAI_API_KEY")
    else: # jupyter notebook
      openai_key = os.getenv("OPENAI_API_KEY")
    return f'{index_name}-{openai_key[-36:].lower().replace("_", "-")}'
    
  def is_colab(self):
    return 'google.colab' in sys.modules

  def get_openai_api_key(self):
    _ = load_dotenv(find_dotenv())
    return os.getenv("OPENAI_API_KEY")
    
  def get_pinecone_api_key(self):
    _ = load_dotenv(find_dotenv())
    return os.getenv("PINECONE_API_KEY")

Load the Dataset

dataset = load_dataset('quora', split='train[240000:290000]')
dataset[:5]

output

{'questions': [{'id': [207550, 351729],
   'text': ['What is the truth of life?', "What's the evil truth of life?"]},
  {'id': [33183, 351730],
   'text': ['Which is the best smartphone under 20K in India?',
    'Which is the best smartphone with in 20k in India?']},
  {'id': [351731, 351732],
   'text': ['Steps taken by Canadian government to improve literacy rate?',
    'Can I send homemade herbal hair oil from India to US via postal or private courier services?']},
  {'id': [37799, 94186],
   'text': ['What is a good way to lose 30 pounds in 2 months?',
    'What can I do to lose 30 pounds in 2 months?']},
  {'id': [351733, 351734],
   'text': ['Which of the following most accurately describes the translation of the graph y = (x+3)^2 -2 to the graph of y = (x -2)^2 +2?',
    'How do you graph x + 2y = -2?']}],
 'is_duplicate': [False, True, False, True, False]}

把问题都保存在questions列表中

questions = []
for record in dataset['questions']:
    questions.extend(record['text'])
question = list(set(questions))
print('\n'.join(questions[:10]))
print('-' * 50)
print(f'Number of questions: {len(questions)}')
  1. question = list(set(questions)): 使用 set() 函数去除 questions 列表中的重复项,然后将其转换为集合。再将集合转换回列表,得到一个去重后的问题列表,存储在 question 变量中。
  2. print('\n'.join(questions[:10])): 将去重前的前十个问题打印出来,join() 函数用于将列表中的元素连接成一个字符串,并使用换行符 \n 分隔。

Output:输出前10个问题

What is the truth of life?
What's the evil truth of life?
Which is the best smartphone under 20K in India?
Which is the best smartphone with in 20k in India?
Steps taken by Canadian government to improve literacy rate?
Can I send homemade herbal hair oil from India to US via postal or private courier services?
What is a good way to lose 30 pounds in 2 months?
What can I do to lose 30 pounds in 2 months?
Which of the following most accurately describes the translation of the graph y = (x+3)^2 -2 to the graph of y = (x -2)^2 +2?
How do you graph x + 2y = -2?
--------------------------------------------------
Number of questions: 100000

Check cuda and Setup the model

Note: “Checking cuda” refers to checking if you have access to GPUs (faster compute). In this course, we are using CPUs. So, you might notice some code cells taking a little longer to run.

We are using all-MiniLM-L6-v2 sentence-transformers model that maps sentences to a 384 dimensional dense vector space.

device = 'cuda' if torch.cuda.is_available() else 'cpu'
if device != 'cuda':
    print('Sorry no cuda.')
model = SentenceTransformer('all-MiniLM-L6-v2', device=device)

这行代码使用了 SentenceTransformer 库中的 SentenceTransformer 类来加载一个预训练的文本嵌入模型。具体地,它加载了一个名为 ‘all-MiniLM-L6-v2’ 的预训练模型,并指定了一个设备(可能是 GPU 或 CPU)来运行模型。

通过加载这个预训练的文本嵌入模型,可以将文本转换为高维向量表示,这些向量可以用于各种自然语言处理任务,如文本相似度计算、文本分类、聚类等。

query = 'which city is the most populated in the world?'
xq = model.encode(query)
xq.shape

Output维度为384维

(384,)

Setup Pinecone

utils = Utils()
PINECONE_API_KEY = utils.get_pinecone_api_key()
pinecone = Pinecone(api_key=PINECONE_API_KEY)
INDEX_NAME = utils.create_dlai_index_name('dl-ai')

if INDEX_NAME in [index.name for index in pinecone.list_indexes()]:
    pinecone.delete_index(INDEX_NAME)
print(INDEX_NAME)
pinecone.create_index(name=INDEX_NAME, 
    dimension=model.get_sentence_embedding_dimension(), 
    metric='cosine',
    spec=ServerlessSpec(cloud='aws', region='us-west-2'))

index = pinecone.Index(INDEX_NAME)
print(index)

这段代码使用 Pinecone 库中的 create_index() 函数创建了一个新的索引。下面是对每个参数的解释:

  • name=INDEX_NAME: 这个参数指定了要创建的索引的名称。INDEX_NAME 是一个变量,用于存储索引的名称。

  • dimension=model.get_sentence_embedding_dimension(): 这个参数指定了向量的维度。在这里,使用了一个叫做 model 的对象的 get_sentence_embedding_dimension() 方法来获取向量的维度。这通常是一个预训练模型返回的嵌入向量的维度。

  • metric='cosine': 这个参数指定了用于衡量向量相似性的距离度量。在这里,使用的是余弦相似度作为度量标准,它用于衡量两个向量之间的夹角余弦值,常用于文本和图像等嵌入向量的相似性比较。

  • spec=ServerlessSpec(cloud='aws', region='us-west-2'): 这个参数指定了索引的部署规格,即在哪个云提供商的哪个地区部署索引。在这里,使用了一个名为 ServerlessSpec 的规格对象,其中 cloud 参数指定了云提供商,这里是 AWS,region 参数指定了部署的地区,这里是美国西部的 us-west-2 区域。

总的来说,这段代码创建了一个新的 Pinecone 索引,指定了索引的名称、向量维度、相似性度量和部署规格。

Output

dl-ai-z7nf9tjs3lswddk6jinpkrukpb7cjfq0mwts
<pinecone.data.index.Index object at 0x7ff8e7697970>

Create Embeddings and Upsert to Pinecone

batch_size=200
vector_limit=10000

questions = question[:vector_limit] # 从问题列表中选择前 10000 个问题

import json
# 使用 tqdm 函数创建一个进度条,循环处理问题列表中的每个批次,每次处理 batch_size 个问题
for i in tqdm(range(0, len(questions), batch_size)): 
    # find end of batch
    i_end = min(i+batch_size, len(questions))
    # create IDs batch
    ids = [str(x) for x in range(i, i_end)]
    # create metadata batch
    metadatas = [{'text': text} for text in questions[i:i_end]] # 每个元数据包含一个问题的文本信息
    # create embeddings
    xc = model.encode(questions[i:i_end]) #  使用预训练的模型将当前批次的问题文本转换为嵌入向量。
    # create records list for upsert
    records = zip(ids, xc, metadatas) # `zip()` 函数将 `ids`、`xc` 和 `metadatas` 中对应位置的元素组合成一个元组
    # upsert to Pinecone
    index.upsert(vectors=records)

解释zip函数

zip() 函数是 Python 中的一个内置函数,它接受任意数量的可迭代对象作为参数,并返回一个由这些可迭代对象的元素组成的元组序列,同时会截断到最短的可迭代对象的长度。

下面是 zip() 函数的基本语法:

zip(iterable1, iterable2, ...)
  • iterable1, iterable2, …:表示一个或多个可迭代对象,比如列表、元组、集合等。

zip() 函数会将每个可迭代对象中相同位置的元素组合成一个元组,然后返回一个由这些元组组成的迭代器。

例如:

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
result = zip(list1, list2)
print(list(result))

输出结果为:

[(1, 'a'), (2, 'b'), (3, 'c')]

在给定的示例中:

records = zip(ids, xc, metadatas)

zip() 函数将 idsxcmetadatas 中对应位置的元素组合成一个元组,并返回一个由这些元组组成的迭代器。这样可以方便地将多个列表中对应位置的元素一起处理,通常用于迭代处理多个列表或集合。

index.describe_index_stats()

Output

index.describe_index_stats()
{'dimension': 384,
 'index_fullness': 0.0,
 'namespaces': {'': {'vector_count': 10000}},
 'total_vector_count': 10000}

Run Your Query

# small helper function so we can repeat queries later
def run_query(query):
  embedding = model.encode(query).tolist()
  results = index.query(top_k=10, vector=embedding, include_metadata=True, include_values=False)
  for result in results['matches']:
    print(f"{round(result['score'], 2)}: {result['metadata']['text']}")

测试run_query:输出10条最相近的问题

run_query('which city has the highest population in the world?')

Output

0.67: Which city in the world is the most beautiful to live in?
0.62: How many cities are on Earth?
0.58: Which country has the highest per capita income?
0.55: What is the recent population of India?
0.54: What is the most remote place in the world?
0.54: What are the largest slums in the world?
0.53: What is the least known country in the world?
0.53: Which is the coldest country in the world?
0.52: Which are the worst cities of India?
0.49: Which are the most dangerous places on the earth to live? Why?

另一个query进行测试

query = 'how do i make chocolate cake?'
run_query(query)

Output

0.58: What's a good recipe for cake featuring Ciroc?
0.56: How do you bake cakes in a convection oven?
0.55: How do I bake a cake in a microwave oven?
0.54: How do you make homemade frosting without powdered sugar?
0.54: How do you make a crispy batter?
0.53: How do you make a perfume out of Skittles?
0.49: What is the difference between chocolate and truffles?
0.49: How can I make a banana pudding without bananas?
0.46: Where can I get custom decorated cakes for any occasion at Gold Coast?
0.46: How can one make the Mint Mojito coffee at home similar to the one at Phillz?

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1468230.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

css3盒子

盒子模型 一.看透网页布局本质二.认识盒子三.盒子的边框&#xff08;border&#xff09;1.概念2.简写及分开写法3.合并问题&#xff08;会相加&#xff09;4.边框会影响盒子实际大小 四.盒子的内边距&#xff08;padding&#xff09;1.概念2.简写3.内边距会影响盒子实际大小4.特…

【Linux】docker构建环境编译运行linux内核

文章目录 1. 使用docker构建linux内核编译运行环境1.1. 为普通用户安装docker并验证是否安装成功1.1.1. 安装docker稳定版1.1.2. 启动docker1.1.3. 将当前用户加入docker用户组1.1.4. 验证docker是否安装成功 1.2. docker基本使用 环境说明 操作系统&#xff1a;ubuntu 22.04.4…

Unity(第四部)新手组件

暴力解释就是官方给你的功能&#xff1b;作用的对象上面如&#xff1a; 创建一个球体&#xff0c;给这个球体加上重力 所有物体都是一个空物体&#xff0c;加上一些组件才形成了所需要的GameObject。 这是一个空物体&#xff0c;在Scene场景中没有任何外在表现&#xff0c;因为…

【数据分享】不同共享社会经济路径下中国未来280个城市土地数量数据集(免费获取)

了解未来城市土地数量对于城市规划、社会经济发展和气候变化研究具有重要意义。通过分析不同共享社会经济路径下中国未来城市土地数量的数据&#xff0c;可以为未来城市发展趋势和可持续规划提供科学依据。 本次我们给大家带来的是不同共享社会经济路径下中国未来城市土地数量…

【Docker 的安装:centos】

文章目录 1 :peach:各版本平台支持情况:peach:2 :peach:CentOS 安装:peach:2.1 :apple:安装依赖:apple:2.2 :apple:安装 Docker:apple:2.3 :apple:实战经验:apple:2.3.1 :lemon:Docker 镜像源修改:lemon:2.3.2 :lemon:Docker 目录修改:lemon: 1 &#x1f351;各版本平台支持情况…

高通 Android 12 Settings不显示版本号问题

1、最近项目遇到一个奇葩问题&#xff0c;编译系统版本号不见了&#xff1f; 2、一开始我想着可能是自己代码没有make clean结果编译几个小时&#xff0c;然后烧录固件发现还是未生效。 3、然后这时候我又去看git log review最近修改也没有太大发现&#xff08;待定&#xff…

模型 金字塔原理

系列文章 分享 模型&#xff0c;了解更多&#x1f449; 模型_总纲目录。清晰逻辑&#xff0c;有效沟通。 1 金字塔原理的应用 1.1 应用金字塔原理提出一个新产品的市场推广策略 确认结论&#xff1a;我们应该采取在线社交媒体广告和口碑营销的策略来推广新产品。 构建层级1&…

python-mysql协程并发常用操作封装

目录 前言封装代码测试代码参考 前言 协程异步操作MYSQL是常用的&#xff0c;博主这里在GitHub上找了两个包&#xff0c;databases和aiomysql&#xff0c;第一个包除了mysql外还支持其他的数据库&#xff0c;且操作MYSQL时底层也是使用的aiomysql&#xff0c;但文档内容比较少…

C#上位机与三菱PLC的通信11---开发自己的通讯工具软件(WPF版)

1、先看颜值 2、开始干 1、创建项目 2、引入前面的通讯库 创建目录将前面生成的通讯库dll文件复制到项目的目录 本项目引入dll文件 3、创建命令基类 RelayCommand.cs代码 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Syst…

HEVC视频编解码标准学习笔记-1

视频编解码标准H.265/HEVC&#xff08;High Efficiency Video Coding&#xff09;通过将视频数据编码为更高效格式&#xff0c;大幅改善了视频流的压缩效率。这里主要介绍Tile、Slice和CTU的定义&#xff0c;以及介绍这些技术组件之间的相互关系。 CTU&#xff08;编码树单元&…

【数据结构】C语言实现二叉树的相关操作

树 定义 树&#xff08;Tree&#xff09;是 n (n > 0) 个结点的有限集 若 n 0&#xff0c;称为空树 若 n > 0&#xff0c;则它满足如下两个条件&#xff1a; 有且仅有一个特定的称为根&#xff08;Root&#xff09;的结点其余结点可分为 m(m>0) 个互不相交的有限…

云原生超融合八大核心能力|ZStack Edge云原生超融合产品技术解读

企业数字化转型的焦点正在发生变化&#xff0c;云基础设施由资源到应用&#xff0c;数据中心从核心到边缘。面向云原生趋势&#xff0c;围绕应用升级&#xff0c;新一代超融合产品——云原生超融合应运而生。 ZStackEdge云原生超融合是基于云原生架构研发的新一代IT基础设施 …

Docker基础篇(四) 容器数据卷 容器间传递共享(--volumes-from)

容器间传递共享 当前没有运行的容器 两个数据卷&#xff1a; containVolum-01 containVolum-02 docker run -it --name zenA zen/centos 上面生成了容器 zenA ctrl P Q docker run -it --name zenB1 --volumes-from zenA zen/centos ctrl P Q docker run -it --name zen…

07 Redis之持久化(RDB(Redis DataBase) + 写时复制 + AOF(Append Only File)+混合持久化)

4 Redis持久化 Redis 是一个内存数据库&#xff0c;然而内存中的数据是不持久的&#xff0c;若主机宕机或 Redis 关机重启&#xff0c;则内存中的数据全部丢失。 当然&#xff0c;这是不允许的。Redis 具有持久化功能&#xff0c;其会按照设置以快照或操作日志的形式将数据持…

GEE入门篇|遥感专业术语(实践操作2):空间分辨率(Spatial Resolution)

目录 空间分辨率&#xff08;Spatial Resolution&#xff09; 1.MODIS&#xff08;搭载在Aqua 和 Terra 卫星上&#xff09; 2. TM&#xff08;搭载在早期LandSat卫星上&#xff09; 3.MSI&#xff08;搭载在在Sentinel-2 卫星上&#xff09; 4.NAIP 空间分辨率&#xff0…

Unity中.Net与Mono的关系

什么是.NET .NET是一个开发框架&#xff0c;它遵循并采用CIL(Common Intermediate Language)和CLR(Common Language Runtime)两种约定&#xff0c; CIL标准为一种编译标准&#xff1a;将不同编程语言&#xff08;C#, JS, VB等&#xff09;使用各自的编译器&#xff0c;按照统…

C++ STL vector详解

1. vector简介 template<class T, class Alloc allocator<T>> class vector; vector是一个可以动态增长的数组&#xff0c;T是要存储的元素类型。vector可以像数组一样&#xff0c;用下标[]来访问元素&#xff0c;如&#xff1a; int arr[] {1,2,3,4}; for (i…

[极客挑战2019]HTTP

这道题考察的是http请求头字段的含义和使用&#xff1b; 具体如下 Referer:来源地址 User-Agent:客户端配置信息&#xff1a;浏览器类型、版本、系统类型等 X-Forwarded-For:代理地址&#xff0c;即数据发出的地址 开始解题&#xff1a;&#xff08;对我这初学者真的烧脑&a…

【机器学习】特征工程之特征选择

&#x1f388;个人主页&#xff1a;豌豆射手^ &#x1f389;欢迎 &#x1f44d;点赞✍评论⭐收藏 &#x1f917;收录专栏&#xff1a;机器学习 &#x1f91d;希望本文对您有所裨益&#xff0c;如有不足之处&#xff0c;欢迎在评论区提出指正&#xff0c;让我们共同学习、交流进…

抖音视频评论数据提取软件|抖音数据抓取工具

一、开发背景&#xff1a; 在业务需求中&#xff0c;我们经常需要下载抖音视频。然而&#xff0c;在网上找到的视频通常只能通过逐个复制链接的方式进行抓取和下载&#xff0c;这种操作非常耗时。我们希望能够通过关键词自动批量抓取并选择性地下载抖音视频。因此&#xff0c;为…