使用向量数据库pinecone构建应用05:人脸相似度查询Facial Similarity Search

news2024/9/20 0:54:49

Building Applications with Vector Databases

下面是这门课的学习笔记: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 5 - Facial Similarity Search
      • Import the Needed Packages
      • Load the Dataset
      • Setup Pinecone
      • Create Embeddings Using DeepFace
      • Plot the Data of Images
      • Store the Embeddings in Pinecone
      • Calculate the Similarity Scores
      • Check the Matching Images

Lesson 5 - Facial Similarity Search

人脸相似度查询:看看孩子更像母亲还是父亲

在这里插入图片描述

Import the Needed Packages

import warnings
warnings.filterwarnings('ignore')

from deepface import DeepFace
from pinecone import Pinecone, ServerlessSpec
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from tqdm import tqdm
from DLAIUtils import Utils


import contextlib
import glob
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import time

# get api key
utils = Utils()
PINECONE_API_KEY = utils.get_pinecone_api_key()

Load the Dataset

def show_img(f):
  img = plt.imread(f)
  plt.figure(figsize=(4,3))
  plt.imshow(img)

show_img('family/dad/P06260_face5.jpg')

Output

在这里插入图片描述

Setup Pinecone

MODEL = "Facenet"
INDEX_NAME = utils.create_dlai_index_name('dl-ai')

pinecone = Pinecone(api_key=PINECONE_API_KEY)

Create Embeddings Using DeepFace

def generate_vectors():
  VECTOR_FILE = "./vectors.vec"

  with contextlib.suppress(FileNotFoundError):
    os.remove(VECTOR_FILE)
  with open(VECTOR_FILE, "w") as f:
    for person in ["mom", "dad", "child"]:
      files = glob.glob(f'family/{person}/*')
      for file in tqdm(files):
        try:
          embedding = DeepFace.represent(img_path=file, model_name=MODEL, enforce_detection=False)[0]['embedding']
          f.write(f'{person}:{os.path.basename(file)}:{embedding}\n')
        except (ValueError, UnboundLocalError, AttributeError) as e:
          print(e)

generate_vectors()
!head -10 vectors.vec

Plot the Data of Images

如下两步:
在这里插入图片描述
PCA介绍

在这里插入图片描述

t-SNE plot介绍
在这里插入图片描述

def gen_tsne_df(person, perplexity):
    vectors =[]
    with open('./vectors.vec', 'r') as f:
      for line in tqdm(f):
        p, orig_img, v = line.split(':')
        if person == p:
            vectors.append(eval(v))
    pca = PCA(n_components=8)
    tsne = TSNE(2, perplexity=perplexity, random_state = 0, n_iter=1000,
        verbose=0, metric='euclidean', learning_rate=75)
    print(f'transform {len(vectors)} vectors')
    pca_transform = pca.fit_transform(vectors)
    embeddings2d = tsne.fit_transform(pca_transform)
    return pd.DataFrame({'x':embeddings2d[:,0], 'y':embeddings2d[:,1]})
def plot_tsne(perplexity, model):
    (_, ax) = plt.subplots(figsize=(8,5))
    #plt.style.use('seaborn-whitegrid')
    plt.grid(color='#EAEAEB', linewidth=0.5)
    ax.spines['top'].set_color(None)
    ax.spines['right'].set_color(None)
    ax.spines['left'].set_color('#2B2F30')
    ax.spines['bottom'].set_color('#2B2F30')
    colormap = {'dad':'#ee8933', 'child':'#4fad5b', 'mom':'#4c93db'}

    for person in colormap:
        embeddingsdf = gen_tsne_df(person, perplexity)
        ax.scatter(embeddingsdf.x, embeddingsdf.y, alpha=.5, 
                   label=person, color=colormap[person])
    plt.title(f'Scatter plot of faces using {model}', fontsize=16, fontweight='bold', pad=20)
    plt.suptitle(f't-SNE [perplexity={perplexity}]', y=0.92, fontsize=13)
    plt.legend(loc='best', frameon=True)
    plt.show()
plot_tsne(44, 'facenet')

Output

在这里插入图片描述

Store the Embeddings in Pinecone

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

index = pinecone.Index(INDEX_NAME)
def store_vectors():
  with open("vectors.vec", "r") as f:
    for line in tqdm(f):
        person, file, vec = line.split(':')
        index.upsert([(f'{person}-{file}', eval(vec), {"person":person, "file":file})])
store_vectors()
index.describe_index_stats()

Output

{'dimension': 128,
 'index_fullness': 0.0,
 'namespaces': {'': {'vector_count': 319}},
 'total_vector_count': 319}

Calculate the Similarity Scores

def test(vec_groups, parent, child):
  index = pinecone.Index(INDEX_NAME)
  parent_vecs = vec_groups[parent]
  K = 10
  SAMPLE_SIZE = 10
  sum = 0
  for i in tqdm(range(0,SAMPLE_SIZE)):
    query_response = index.query(
      top_k=K,
      vector = parent_vecs[i],
      filter={
        "person": {"$eq": child}
      }
    )
    for row in query_response["matches"]:
      sum  = sum + row["score"]
  print(f'\n\n{parent} AVG: {sum / (SAMPLE_SIZE*K)}')
def compute_scores():
  index = pinecone.Index(INDEX_NAME)
  vec_groups = {"dad":[], "mom":[], "child":[]}
  with open("vectors.vec", "r") as f:
    for line in tqdm(f):
      person, file, vec = line.split(':')
      vec_groups[person].append(eval(vec))
  print(f"DAD {'-' * 20}")
  test(vec_groups, "dad", "child")
  print(f"MOM {'-' * 20}")
  test(vec_groups, "mom", "child")

compute_scores()

Output

dad AVG: 0.41020248437000006
mom AVG: 0.3494142116000002

Check the Matching Images

孩子的照片

child_base = 'family/child/P06310_face1.jpg'
show_img(child_base)

Output

在这里插入图片描述

#Now find closest given we know dad is "most similar"
embedding = DeepFace.represent(img_path=child_base, model_name=MODEL)[0]['embedding']
print(embedding)

在dad文件夹中查找结果

query_response = index.query(
      top_k=3,
      vector = embedding,
      filter={
        "person": {"$eq": "dad"}
      },
      include_metadata=True
)

在这里,filter 参数中的 “$eq” 表示等于运算符(equality operator)。它用于对索引中的特定字段进行过滤,只返回那些字段值等于给定值的条目。

在这个例子中,filter 参数的目的是对索引中的 “person” 字段进行过滤,只返回 “person” 字段值等于 “dad” 的条目。这样可以限制搜索结果,只返回符合指定条件的结果。

print(query_response)

在这里,vector 参数用于指定查询时所使用的向量。具体来说,它表示查询向量,即用于与索引中存储的向量进行相似度比较的向量。

当执行查询时,系统会使用 vector 参数中指定的向量与索引中存储的向量进行相似度计算,从而找到与查询向量最相似的向量,并返回相应的搜索结果。

在这个例子中,vector 参数应该包含了用于查询的嵌入向量,通常是由某个模型生成的表示查询内容的向量。

Output

{'matches': [{'id': 'dad-P06396_face3.jpg',
              'metadata': {'file': 'P06396_face3.jpg', 'person': 'dad'},
              'score': 0.438557684,
              'values': []},
             {'id': 'dad-P11886_face3.jpg',
              'metadata': {'file': 'P11886_face3.jpg', 'person': 'dad'},
              'score': 0.419384569,
              'values': []},
             {'id': 'dad-P04408_face0.jpg',
              'metadata': {'file': 'P04408_face0.jpg', 'person': 'dad'},
              'score': 0.407050818,
              'values': []},
             {'id': 'dad-P11991_face7.jpg',
              'metadata': {'file': 'P11991_face7.jpg', 'person': 'dad'},
              'score': 0.368852,
              'values': []},
             {'id': 'dad-P06265_face2.jpg',
              'metadata': {'file': 'P06265_face2.jpg', 'person': 'dad'},
              'score': 0.36260435,
              'values': []},
             {'id': 'dad-P04407_face3.jpg',
              'metadata': {'file': 'P04407_face3.jpg', 'person': 'dad'},
              'score': 0.357501268,
              'values': []},
             {'id': 'dad-P11995_face2.jpg',
              'metadata': {'file': 'P11995_face2.jpg', 'person': 'dad'},
              'score': 0.336032152,
              'values': []},
             {'id': 'dad-P11975_face0.jpg',
              'metadata': {'file': 'P11975_face0.jpg', 'person': 'dad'},
              'score': 0.317324311,
              'values': []},
             {'id': 'dad-P11984_face2.jpg',
              'metadata': {'file': 'P11984_face2.jpg', 'person': 'dad'},
              'score': 0.310575306,
              'values': []},
             {'id': 'dad-P06260_face5.jpg',
              'metadata': {'file': 'P06260_face5.jpg', 'person': 'dad'},
              'score': 0.30459854,
              'values': []}],
 'namespace': '',
 'usage': {'read_units': 6}}

查询最像孩子的父亲:

photo = query_response['matches'][0]['metadata']['file']
show_img(f'family/dad/{photo}')

Output

在这里插入图片描述

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

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

相关文章

深入探索Linux:ACL权限、特殊位与隐藏属性的奥秘

前言: 在Linux系统中,文件和目录的权限管理是一项至关重要的任务。它决定了哪些用户或用户组可以对文件或目录执行读、写或执行等操作。传统的Linux权限模型基于用户、组和其他的概念,但随着时间的推移,这种模型在某些情况下显得…

SQL库操作

1、创建数据库 概念 创建数据库:根据项目需求创建一个存储数据的仓库 使用create database 数据库名字创建 数据库层面可以指定字符集:charset/character set 数据库层面可以指定校对集:collate 创建数据库会在磁盘指定存放处产生一个文件夹 创建语法 create …

springmvc+mybatis+springboot航空飞机订票售票系统_f48cp

互联网发展的越来越快了,在当下社会节点,人们也开始越来越依赖互联网。通过互联网信息和数据,极大地满足用户要求[5]。飞机订票系统使用了B/S模式,并且不需要安装第三方插件,他们甚至能直接在电脑上随机随地实现飞机订…

Go 中的 init 如何用?它的常见应用场景有哪些呢?

嗨,大家好!我是波罗学。本文是系列文章 Go 技巧第十六篇,系列文章查看:Go 语言技巧。 Go 中有一个特别的 init() 函数,它主要用于包的初始化。init() 函数在包被引入后会被自动执行。如果在 main 包中,它也…

JavaGuide-SQL在mysql中的执行过程

SQL在mysql中的执行过程 原文连接 SQL在mysql中的执行过程 基础架构概览 我们先总结基本组件 连接器: 身份认证 权限相关的,我们连接的时候会验证查询缓存: 8.0之后移除,执行查询的时候,会先查缓存分析器: 分析你的sql语句,包括词法分析 语法分析优化器: 按照mysql认为最…

LED智能互联办公室照明恒流调光IC芯片无频闪H5114

调光高辉度65536级/高精度3% LED降压型恒流驱动器H5114 产品描述 H5114是一款外围电路简单的多功能平 均电流型LED恒流驱动器,适用于5-90V电压范围的非隔离式大功率恒流LED驱动领域。 芯片采用了平均电流模式控制,输出电流精度在3%&#xff…

http相关概念以及apache的功能(最详细讲解!!!!)

概念 互联网:是网络的网络,是所有类型网络的母集 因特网:世界上最大的互联网网络 万维网:www (不是网络,而是数据库)是网页与网页之间的跳转关系 URL:万维网使用统一资源定位符,…

GEE入门篇|遥感专业术语(实践操作1):搜索及查看图像集合信息

Earth Engine 的搜索栏可用于查找影像和定位重要内容有关 Earth Engine 中数据集的信息,让我们使用位于搜索栏上方的Earth Engine代码,用于查找有关 Landsat 7 集合 2 的信息原始场景。首先,在搜索栏中输入“Landsat 7 collection 2”&#x…

【Power Apps】实现一个简单的可编辑列表

简单来说,我们这次是要实现一个可以直接在列表上增加、修改、删除数据的功能。 大概就像这样。 之前我们都是拿列表做一个数据展示的功能,真要增加、修改、删除数据是在另一张表单上做的,我们这回要去掉另一个表单,直接在列表上做…

RabbitMQ学习整理————基于RabbitMQ实现RPC

基于RabbitMQ实现RPC 前言什么是RPCRabbitMQ如何实现RPCRPC简单示例通过Spring AMQP实现RPC 前言 这边参考了RabbitMQ的官网,想整理一篇关于RabbitMQ实现RPC调用的博客,打算把两种实现RPC调用的都整理一下,一个是使用官方提供的一个Java cli…

适用于生物行业的样本管理系统

在生物样本管理系统的应用中,我们首先需要了解生物样本的特点和要求。生物样本具有多样性和易变性,需要被妥善保存和跟踪,以确保其质量和可用性。 因此,一个有效的生物样本管理系统需要具备以下特点: 全面性&#xff1…

测试用例设计方法:招式组合,因果判定出世

1 引言 上篇讲了等价类划分和边界值分析法,而这两种方法只考虑了单个的输入条件,并未考虑输入条件的各种组合、输入条件之间的相互制约关系的场景。基于此短板,因果图法和判定表法应运而生。 2 因果图法 2.1 概念及原理 2.1.1 定义 一种…

外包干了两个月,技术退步明显。。。。。

先说一下自己的情况,本科生,19年通过校招进入广州某软件公司,干了接近4年的功能测试,今年年初,感觉自己不能够在这样下去了,长时间呆在一个舒适的环境会让一个人堕落!而我已经在一个企业干了四年的功能测试…

2024/02/23

使用消息队列完成两个进程间相互通信 A.c #include<myhead.h> struct msgbuf {long mtype;char mtext[1024]; }; //定义表示正文内容大小的宏 #define MSGSIZE sizeof(struct msgbuf)-sizeof(long)int main(int argc, const char *argv[]) {//创建一个key值key_t key;ke…

快速学习安全框架 Springsecurity最新版(6.2)--用户授权模块

简介 上一节Springsecurity 用户认证 Springsecurity 拥有强大的认证和授权功能并且非常灵活&#xff0c;,一来说我们都i有以下需求 可以帮助应用程序实现以下两种常见的授权需求&#xff1a; 用户-权限-资源&#xff1a;例如张三的权限是添加用户、查看用户列表&#xff0c;李…

springboot214基于springboot的多媒体素材库的开发与应用

多媒体素材库的设计与实现 摘要 近年来&#xff0c;信息化管理行业的不断兴起&#xff0c;使得人们的日常生活越来越离不开计算机和互联网技术。首先&#xff0c;根据收集到的用户需求分析&#xff0c;对设计系统有一个初步的认识与了解&#xff0c;确定多媒体素材库的总体功…

CentOS使用Docker搭建Halo网站并实现无公网ip远程访问

&#x1f525;博客主页&#xff1a; 小羊失眠啦. &#x1f3a5;系列专栏&#xff1a;《C语言》 《数据结构》 《C》 《Linux》 《Cpolar》 ❤️感谢大家点赞&#x1f44d;收藏⭐评论✍️ 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&…

阿里云2024年优惠政策合集,你要的阿里云优惠政策都在这!

2024年阿里云优惠活动大全&#xff0c;包括阿里云服务器优惠活动清单、配置价格表、域名优惠活动、阿里云建站活动、阿里云优惠代金券免费领取、对象存储OSS活动、企业邮箱优惠、无影云电脑优惠、CDN特惠等等&#xff0c;阿里云百科aliyunbaike.com分享2024阿里云优惠活动大全_…

Linux RocketMQ 安装及卸载(附控制台搭建)

一、前言 在安装 RocketMQ 前需要确保 JDK 已安装并正确配置环境变量 二、下载安装 1.下载 下载 | RocketMQ 2.安装 # 打开存放目录 cd /usr/local # 创建目录 mkdir rocketMQ # 进入目录 cd rocketMQ # 把下载的压缩包上传到 rocketMQ 目录中 # 解压 $ unzip rocketmq-all-…

Elasticsearch:基于 Langchain 的 Elasticsearch Agent 对文档的搜索

在今天的文章中&#xff0c;我们将重点介绍如何使用 LangChain 提供的基础设施在 Python 中构建 Elasticsearch agent。 该 agent 应允许用户以自然语言询问有关 Elasticsearch 集群中数据的问题。 Elasticsearch 是一个强大的搜索引擎&#xff0c;支持词法和向量搜索。 Elast…