Elasticsearch:运用向量搜索通过图像搜索找到你的小狗

这篇具有很好参考价值的文章主要介绍了Elasticsearch:运用向量搜索通过图像搜索找到你的小狗。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

作者:ALEX SALGADO

你是否曾经遇到过这样的情况:你在街上发现了一只丢失的小狗,但不知道它是否有主人? 了解如何使用向量搜索或图像搜索来做到这一点。

Elasticsearch:运用向量搜索通过图像搜索找到你的小狗,Elasticsearch,AI,Elastic,elasticsearch,大数据,搜索引擎,全文检索,python,人工智能

通过图像搜索找到你的小狗

您是否曾经遇到过这样的情况:你在街上发现了一只丢失的小狗,但不知道它是否有主人? 在 Elasticsearch 中通过图像处理使用向量搜索,此任务可以像漫画一样简单。

想象一下这个场景:在一个喧闹的下午,路易吉,一只活泼的小狗,在 Elastic 周围散步时不小心从皮带上滑落,发现自己独自在繁忙的街道上徘徊。 绝望的主人正在各个角落寻找他,用充满希望和焦虑的声音呼唤着他的名字。 与此同时,在城市的某个地方,一位细心的人注意到这只小狗表情茫然,决定提供帮助。 很快,他们给路易吉拍了一张照片,并利用所在公司的向量图像搜索技术,开始在数据库中进行搜索,希望能找到有关这只小逃亡者主人的线索。

如果你想在阅读时跟踪并执行代码,请访问在 Jupyter Notebook (Google Collab) 上运行的文件 Python 代码。

架构

我们将使用 Jupyter Notebook 来解决这个问题。 首先,我们下载要注册的小狗的图像,然后安装必要的软件包。

Elasticsearch:运用向量搜索通过图像搜索找到你的小狗,Elasticsearch,AI,Elastic,elasticsearch,大数据,搜索引擎,全文检索,python,人工智能

注意:要实现此示例,我们需要在使用图像数据填充向量数据库之前在 Elasticsearch 中创建索引。

  • 首先部署 Elasticsearch(我们为你提供 14 天的免费试用期)。
  • 在此过程中,请记住存储要在 Python 代码中使用的凭据(用户名、密码)。
  • 为简单起见,我们将使用在 Jupyter Notebook (Google Colab) 上运行的 Python 代码。

下载代码 zip 文件并安装必要的软件包

!git clone https://github.com/salgado/image-search-01.git
!pip -q install Pillow sentence_transformers elasticsearch

让我们创建 4 个类来帮助我们完成这项任务,它们是:

  • Util 类:负责处理前期任务和 Elasticsearch 索引维护。
  • Dog 类:负责存储我们小狗的属性。
  • DogRepository 类:负责数据持久化任务。
  • DogService 类:它将成为我们的服务层。

Util class

Util 类提供了用于管理 Elasticsearch 索引的实用方法,例如创建和删除索引。

方法

  • create_index():在 Elasticsearch 中创建一个新索引。
  • delete_index():从 Elasticsearch 中删除现有索引。
### Util class
from elasticsearch import Elasticsearch, exceptions as es_exceptions
import getpass

class Util:
    @staticmethod
    def get_index_name():
      return "dog-image-index"

    @staticmethod
    def get_connection():
        es_cloud_id = getpass.getpass('Enter Elastic Cloud ID:  ')
        es_user = getpass.getpass('Enter cluster username:  ')
        es_pass = getpass.getpass('Enter cluster password:  ')

        es = Elasticsearch(cloud_id=es_cloud_id,
                          basic_auth=(es_user, es_pass)
                          )
        es.info() # should return cluster info
        return es


    @staticmethod
    def create_index(es: Elasticsearch, index_name: str):
        # Specify index configuration
        index_config = {
          "settings": {
            "index.refresh_interval": "5s",
            "number_of_shards": 1
          },
          "mappings": {
            "properties": {
              "image_embedding": {
                "type": "dense_vector",
                "dims": 512,
                "index": True,
                "similarity": "cosine"
              },
              "dog_id": {
                "type": "keyword"
              },
              "breed": {
                "type" : "keyword"
              },
              "image_path" : {
                "type" : "keyword"
              },
              "owner_name" : {
                "type" : "keyword"
              },
              "exif" : {
                "properties" : {
                  "location": {
                    "type": "geo_point"
                  },
                  "date": {
                    "type": "date"
                  }
                }
              }
            }
          }
        }

        # Create index
        if not es.indices.exists(index=index_name):
            index_creation = es.indices.create(index=index_name, ignore=400, body=index_config)
            print("index created: ", index_creation)
        else:
            print("Index  already exists.")


    @staticmethod
    def delete_index(es: Elasticsearch, index_name: str):
        # delete index
        es.indices.delete(index=index_name, ignore_unavailable=True)

如果你是自构建的集群,你可以参考文章 “Elasticsearch:关于在 Python 中使用 Elasticsearch 你需要知道的一切 - 8.x” 来了解如何使用客户端来连接 Elasticsearch 集群。

Dog class

Dog 类代表一只狗及其属性,例如 ID、图像路径、品种、所有者姓名和图像嵌入。

属性

  • dog_id:狗的 ID。
  • image_path:狗图像的路径。
  • breed:狗的品种。
  • owner_name:狗的主人的名字。
  • image_embedding:狗的图像嵌入。

方法:

  • __init__():初始化一个新的 Dog 对象。
  • generate_embedding():生成狗的图像嵌入。
  • to_dict():将 Dog 对象转换为字典。
import os
from sentence_transformers import SentenceTransformer
from PIL import Image

# domain class
class Dog:
    model = SentenceTransformer('clip-ViT-B-32')

    def __init__(self, dog_id, image_path, breed, owner_name):
        self.dog_id = dog_id
        self.image_path = image_path
        self.breed = breed
        self.image_embedding = None
        self.owner_name = owner_name

    @staticmethod
    def get_embedding(image_path: str):
        temp_image = Image.open(image_path)
        return Dog.model.encode(temp_image)

    def generate_embedding(self):
        self.image_embedding = Dog.get_embedding(self.image_path)

    def __repr__(self):
        return (f"Image(dog_id={self.dog_id}, image_path={self.image_path}, "
                f"breed={self.breed}, image_embedding={self.image_embedding}, "
                f"owner_name={self.owner_name})")

    def to_dict(self):
        return {
            'dog_id': self.dog_id,
            'image_path': self.image_path,
            'breed': self.breed,
            'image_embedding': self.image_embedding,
            'owner_name': self.owner_name
        }

DogRepository class

DogRepository 类提供了从 Elasticsearch 保存和检索狗数据的方法。

方法

  • insert():将一条新狗插入 Elasticsearch。
  • bulk_insert():将多条狗批量插入到Elasticsearch中。
  • search_by_image():通过图像搜索相似的狗。
from typing import List, Dict
# persistence layer
class DogRepository:
    def __init__(self, es_client: Elasticsearch, index_name: str = "dog-image-index"):
        self.es_client = es_client
        self._index_name = index_name
        Util.create_index(es_client, index_name)

    def insert(self, dog: Dog):
        dog.generate_embedding()
        document = dog.__dict__
        self.es_client.index(index=self._index_name, document=document)

    def bulk_insert(self, dogs: List[Dog]):
        operations = []
        for dog in dogs:
            operations.append({"index": {"_index": self._index_name}})
            operations.append(dog.__dict__)
        self.es_client.bulk(body=operations)

    def search_by_image(self, image_embedding: List[float]):
      field_key = "image_embedding"

      knn = {
          "field": field_key,
          "k": 2,
          "num_candidates": 100,
          "query_vector": image_embedding,
          "boost": 100
      }

      # The fields to retrieve from the matching documents
      fields = ["dog_id", "breed", "owner_name","image_path", "image_embedding"]

      try:
          resp = self.es_client.search(
              index=self._index_name,
              body={
                  "knn": knn,
                  "_source": fields
              },
              size=1
          )
          # Return the search results
          return resp
      except Exception as e:
          print(f"An error occurred: {e}")
          return {}

DogService Class

DogService 类提供管理狗数据的业务逻辑,例如插入和搜索狗。

方法

  • insert_dog():将一条新狗插入 Elasticsearch。
  • search_dogs_by_image():通过图像搜索相似的狗。

from typing import List, Dict
# persistence layer
class DogRepository:
    def __init__(self, es_client: Elasticsearch, index_name: str = "dog-image-index"):
        self.es_client = es_client
        self._index_name = index_name
        Util.create_index(es_client, index_name)

    def insert(self, dog: Dog):
        dog.generate_embedding()
        document = dog.__dict__
        self.es_client.index(index=self._index_name, document=document)

    def bulk_insert(self, dogs: List[Dog]):
        operations = []
        for dog in dogs:
            operations.append({"index": {"_index": self._index_name}})
            operations.append(dog.__dict__)
        self.es_client.bulk(body=operations)

    def search_by_image(self, image_embedding: List[float]):
      field_key = "image_embedding"

      knn = {
          "field": field_key,
          "k": 2,
          "num_candidates": 100,
          "query_vector": image_embedding,
          "boost": 100
      }

      # The fields to retrieve from the matching documents
      fields = ["dog_id", "breed", "owner_name","image_path", "image_embedding"]

      try:
          resp = self.es_client.search(
              index=self._index_name,
              body={
                  "knn": knn,
                  "_source": fields
              },
              size=1
          )
          # Return the search results
          return resp
      except Exception as e:
          print(f"An error occurred: {e}")
          return {}

上面介绍的类(classes)为构建狗数据管理系统奠定了坚实的基础。 Util 类提供了用于管理 Elasticsearch 索引的实用方法。 Dog 类代表狗的属性。 DogRepository 类提供了从 Elasticsearch 保存和检索狗数据的方法。 DogService 类提供了高效的狗数据管理的业务逻辑。

主要代码

我们的代码基本上有两个主要流程或阶段:

  • 使用基本信息和图像注册狗。
  • 使用新图像执行搜索以在向量数据库中查找狗。

第一阶段:注册小狗

为了存储有关 Luigi 和其他公司的小狗的信息,我们将使用 Dog 类。

为此,我们对序列进行如下的编程:

开始为小狗登记


# Start a connection
es_db = Util.get_connection()
Util.delete_index(es_db, Util.get_index_name())

# Register one dog
dog_repo = DogRepository(es_db, Util.get_index_name())
dog_service = DogService(dog_repo)

# Visualize the inserted Dog
from IPython.display import display
from IPython.display import Image as ShowImage

filename = "/content/image-search-01/dataset/dogs/Luigi.png"
display(ShowImage(filename=filename, width=300, height=300))

输出:

Elasticsearch:运用向量搜索通过图像搜索找到你的小狗,Elasticsearch,AI,Elastic,elasticsearch,大数据,搜索引擎,全文检索,python,人工智能

登记 Luigi

dog = Dog('Luigi', filename, 'Jack Russel/Rat Terrier', 'Ully')

dog_service.register_dog(dog)

登记所有其他小狗

import json

# JSON data
data = '''
{
  "dogs": [
    {"dog_id": "Buddy", "image_path": "", "breed": "Labrador Retriever", "owner_name": "Berlin Red"},
    {"dog_id": "Bella", "image_path": "", "breed": "German Shepherd", "owner_name": "Tokyo Blue"},
    {"dog_id": "Charlie", "image_path": "", "breed": "Golden Retriever", "owner_name": "Paris Green"},
    {"dog_id": "Bigu", "image_path": "", "breed": "Beagle", "owner_name": "Lisbon Yellow"},
    {"dog_id": "Max", "image_path": "", "breed": "Bulldog", "owner_name": "Canberra Purple"},
    {"dog_id": "Luna", "image_path": "", "breed": "Poodle", "owner_name": "Wellington Brown"},
    {"dog_id": "Milo", "image_path": "", "breed": "Rottweiler", "owner_name": "Hanoi Orange"},
    {"dog_id": "Ruby", "image_path": "", "breed": "Boxer", "owner_name": "Ottawa Pink"},
    {"dog_id": "Oscar", "image_path": "", "breed": "Dachshund", "owner_name": "Kabul Black"},
    {"dog_id": "Zoe", "image_path": "", "breed": "Siberian Husky", "owner_name": "Cairo White"}
  ]
}
'''

# Convert JSON string to Python dictionary
dogs_data = json.loads(data)

# Traverse the list and print dog_id of each dog
image_dogs = "/content/image-search-01/dataset/dogs/"
for dog_info in dogs_data["dogs"]: 
    dog = Dog(dog_info["dog_id"], image_dogs + dog_info["dog_id"] + ".png" , dog_info["breed"], dog_info["owner_name"])
    dog_service.register_dog(dog)

可视化新狗

# visualize new dogs
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import math

image_dogs = "/content/image-search-01/dataset/dogs/"
num_dogs = len(dogs_data["dogs"])

cols = int(math.sqrt(num_dogs))
rows = int(math.ceil(num_dogs / cols))

# Configurar o tamanho da figura
plt.figure(figsize=(5, 5))

# Loop para exibir as imagens dos cães
for i, dog_info in enumerate(dogs_data["dogs"]): 
    filename = image_dogs + dog_info["dog_id"] + ".png"
    img = mpimg.imread(filename)
    
    plt.subplot(rows, cols, i+1)  # (número de linhas, número de colunas, índice do subplot)
    plt.imshow(img)
    plt.axis('off')

plt.show()

输出:

Elasticsearch:运用向量搜索通过图像搜索找到你的小狗,Elasticsearch,AI,Elastic,elasticsearch,大数据,搜索引擎,全文检索,python,人工智能

第二阶段:寻找丢失的狗

现在我们已经登记了所有小狗,让我们进行搜索。 我们的开发人员拍了这张丢失小狗的照片。

filename = "/content/image-search-01/dataset/lost-dogs/lost_dog1.png"
display(ShowImage(filename=filename, width=300, height=300))

输出:

Elasticsearch:运用向量搜索通过图像搜索找到你的小狗,Elasticsearch,AI,Elastic,elasticsearch,大数据,搜索引擎,全文检索,python,人工智能

看看我们能找到这只可爱的小狗的主人吗?

# find dog by image
result = dog_service.find_dog_by_image(filename)

获取结果

让我们看看我们发现了什么......

filename = result['hits']['hits'][0]['_source']['image_path']
display(ShowImage(filename=filename, width=300, height=300))

输出:

Elasticsearch:运用向量搜索通过图像搜索找到你的小狗,Elasticsearch,AI,Elastic,elasticsearch,大数据,搜索引擎,全文检索,python,人工智能

瞧! 我们找到了!!!

但谁将是所有者和他们的名字?

# Print credentials
print(result['hits']['hits'][0]['_source']['dog_id'])
print(result['hits']['hits'][0]['_source']['breed'])
print(result['hits']['hits'][0]['_source']['owner_name'])

输出:

  • Luigi
  • Jack Russel/Rat Terrier
  • Ully

好结局

我们找到了路易吉!!! 我们通知 Ully 吧。

filename = "/content/image-search-01/dataset/lost-dogs/Ully.png"
display(ShowImage(filename=filename, width=300, height=300))

输出:

Elasticsearch:运用向量搜索通过图像搜索找到你的小狗,Elasticsearch,AI,Elastic,elasticsearch,大数据,搜索引擎,全文检索,python,人工智能

很快,Ully 和 Luigi 就团聚了。 小狗高兴地摇着尾巴,Ully 紧紧地抱住它,保证再也不会让它离开她的视线。 他们经历了一阵情感旋风,但现在他们在一起了,这才是最重要的。 就这样,Ully 和 Luigi 心中充满了爱和欢乐,从此幸福地生活在一起。

结论

在这篇博文中,我们探索了如何使用 Elasticsearch 通过向量搜索来寻找丢失的小狗。 我们演示了如何生成狗的图像嵌入,在 Elasticsearch 中对其进行索引,然后使用查询图像搜索相似的狗。 该技术可用于寻找丢失的宠物,以及识别图像中其他感兴趣的物体。

向量搜索是一个强大的工具,可用于多种应用。 它特别适合需要根据外观搜索相似对象的任务,例如图像检索和对象识别。

我们希望这篇博文能够提供丰富的信息,并且你会发现我们讨论的技术对你自己的项目很有用。

原文:Finding your puppy with Image Search — Elastic Search Labs文章来源地址https://www.toymoban.com/news/detail-780009.html

到了这里,关于Elasticsearch:运用向量搜索通过图像搜索找到你的小狗的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • 向量数据库:使用Elasticsearch实现向量数据存储与搜索

    Here’s the table of contents:   Elasticsearch在7.x的版本中支持 向量检索 。在向量函数的计算过程中,会对所有匹配的文档进行线性扫描。因此,查询预计时间会随着匹配文档的数量线性增长。出于这个原因,建议使用查询参数来限制匹配文档的数量(类似二次查找的逻辑,先使

    2024年02月07日
    浏览(41)
  • Elasticsearch:利用向量搜索进行音乐信息检索

    作者:Alex Salgado 欢迎来到音乐信息检索的未来,机器学习、向量数据库和音频数据分析融合在一起,带来令人兴奋的新可能性! 如果你对音乐数据分析领域感兴趣,或者只是热衷于技术如何彻底改变音乐行业,那么本指南适合你。 在这里,我们将带你踏上使用向量搜索方法

    2024年02月09日
    浏览(34)
  • Elasticsearch:向量搜索 (kNN) 实施指南 - API 版

    作者:Jeff Vestal 本指南重点介绍通过 HTTP 或 Python 使用 Elasticsearch API 设置 Elasticsearch 以进行近似 k 最近邻 (kNN) 搜索。 对于主要使用 Kibana 或希望通过 UI 进行测试的用户,请访问使用 Elastic 爬虫的语义搜索入门指南。你也可以参考文章 “ChatGPT 和 Elasticsearch:OpenAI 遇见私有数

    2024年02月04日
    浏览(40)
  • Elasticsearch:如何部署 NLP:文本嵌入和向量搜索

    作为我们自然语言处理 (NLP) 博客系列的一部分,我们将介绍一个使用文本嵌入模型生成文本内容的向量表示并演示对生成的向量进行向量相似性搜索的示例。我们将在 Elasticsearch 上部署一个公开可用的模型,并在摄取管道中使用它来从文本文档生成嵌入。然后,我们将展示如

    2024年02月05日
    浏览(45)
  • Elasticsearch 中的向量搜索:设计背后的基本原理

    作者:ADRIEN GRAND 实现向量数据库有不同的方法,它们有不同的权衡。 在本博客中,你将详细了解如何将向量搜索集成到 Elastisearch 中以及我们所做的权衡。 你有兴趣了解 Elasticsearch 用于向量搜索的特性以及设计是什么样子吗? 一如既往,设计决策有利有弊。 本博客旨在详细

    2024年02月10日
    浏览(33)
  • Elasticsearch:语义搜索、知识图和向量数据库概述

    结合对你自己的私有数据执行语义搜索的概述 语义搜索是一种使用自然语言处理算法来理解单词和短语的含义和上下文以提供更准确的搜索结果的搜索技术。 这种方法基于这样的想法:搜索引擎不仅应该匹配查询中的,还应该尝试理解用户搜索的意图以及所使用的单

    2024年02月16日
    浏览(35)
  • 快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索

    Gemini 是 Google DeepMind 开发的多模态大语言模型家族,作为 LaMDA 和 PaLM 2 的后继者。由 Gemini Ultra、Gemini Pro 和 Gemini Nano 组成,于 2023 年 12 月 6 日发布,定位为 OpenAI 的竞争者 GPT-4。 本教程演示如何使用 Gemini API 创建嵌入并将其存储在 Elasticsearch 中。 Elasticsearch 将使我们能够执

    2024年01月21日
    浏览(31)
  • Elasticsearch:在 Elasticsearch 中使用 NLP 和向量搜索增强聊天机器人功能

    作者:Priscilla Parodi 会话界面已经存在了一段时间,并且作为协助各种任务(例如客户服务、信息检索和任务自动化)的一种方式而变得越来越流行。 通常通过语音助手或消息应用程序访问,这些界面模拟人类对话,以帮助用户更有效地解决他们的查询。 随着技术的进步,聊

    2024年02月07日
    浏览(35)
  • 使用 ElasticSearch 作为知识库,存储向量及相似性搜索

    在当今大数据时代,快速有效地搜索和分析海量数据成为了许多企业和组织的重要需求。 Elasticsearch 作为一款功能强大的分布式搜索和分析引擎,为我们提供了一种优秀的解决方案。除了传统的文本搜索, Elasticsearch 还引入了向量存储的概念,以实现更精确、更高效的相似性

    2024年02月10日
    浏览(34)
  • 使用 ElasticSearch 作为知识库,存储向量及相似性搜索_elasticsearch cosinesimilarity(1)

    下面基于上篇文章使用到的 Chinese-medical-dialogue-data 中文医疗对话数据作为知识内容进行实验。 本篇实验使用 ES 版本为: 7.14.0 二、Chinese-medical-dialogue-data 数据集 GitHub 地址如下: https://github.com/Toyhom/Chinese-medical-dialogue-data 数据分了 6 个科目类型: 数据格式如下所示: 其中

    2024年04月11日
    浏览(34)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包