🚀 免費嘗試 Zilliz Cloud,完全托管的 Milvus,體驗速度提升 10 倍!立即嘗試

milvus-logo
LFAI
主頁
  • 整合

使用 Milvus 和 SentenceTransformers 搜尋電影

在這個範例中,我們將使用 Milvus 和 SentenceTransformers 函式庫搜尋電影劇情摘要。我們要使用的資料集是 HuggingFace 上託管的Wikipedia Movie Plots with Summaries

讓我們開始吧!

所需的函式庫

在這個範例中,我們將使用pymilvus 連線使用 Milvus,使用sentence-transformers 產生向量嵌入,使用datasets 下載範例資料集。

pip install pymilvus sentence-transformers datasets tqdm
from datasets import load_dataset
from pymilvus import MilvusClient
from pymilvus import FieldSchema, CollectionSchema, DataType
from sentence_transformers import SentenceTransformer
from tqdm import tqdm

我們將定義一些全局參數、

embedding_dim = 384
collection_name = "movie_embeddings"

下載與開啟資料集

在單一行中,datasets 允許我們下載和開啟資料集。資料庫會在本機快取資料集,並在下次執行時使用該副本。每一行都包含一部電影的詳細資料,該電影附有一篇 Wikipedia 文章。我們使用Title,PlotSummary,Release YearOrigin/Ethnicity 列。

ds = load_dataset("vishnupriyavr/wiki-movie-plots-with-summaries", split="train")
print(ds)

連接至資料庫

此時,我們要開始設定 Milvus。步驟如下:

  1. 在本地檔案中建立一個 Milvus Lite 資料庫。(將此 URI 改為 Milvus Standalone 和 Milvus Distributed 的伺服器位址)。
client = MilvusClient(uri="./sentence_transformers_example.db")
  1. 建立資料模式。這將指定組成元素的欄位,包括向量嵌入的維度。
fields = [
    FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True),
    FieldSchema(name="title", dtype=DataType.VARCHAR, max_length=256),
    FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=embedding_dim),
    FieldSchema(name="year", dtype=DataType.INT64),
    FieldSchema(name="origin", dtype=DataType.VARCHAR, max_length=64),
]

schema = CollectionSchema(fields=fields, enable_dynamic_field=False)
client.create_collection(collection_name=collection_name, schema=schema)
  1. 定義向量搜尋索引演算法。Milvus Lite 支援 FLAT 索引類型,而 Milvus Standalone 和 Milvus Distributed 則實施多種方法,例如 IVF、HNSW 和 DiskANN。對於本範例中的小型資料,任何搜尋索引類型都已經足夠,因此我們在此使用最簡單的 FLAT 索引類型。
index_params = client.prepare_index_params()
index_params.add_index(field_name="embedding", index_type="FLAT", metric_type="IP")
client.create_index(collection_name, index_params)

完成這些步驟後,我們就可以將資料插入資料庫並執行搜尋。任何新增的資料都會自動建立索引,並立即可供搜尋。如果資料非常新,搜尋速度可能會較慢,因為會對仍在建立索引過程中的資料使用暴力搜尋。

插入資料

在這個範例中,我們要使用 SentenceTransformers miniLM 模型來建立繪圖文字的嵌入。這個模型會傳回 384 個維度的嵌入。

model = SentenceTransformer("all-MiniLM-L12-v2")

我們在資料的行上循環,嵌入圖面摘要欄位,並將實體插入向量資料庫。一般而言,您應該在成批的資料項目上執行此步驟,以最大化嵌入模型的 CPU 或 GPU 吞吐量,就像我們在這裡所做的一樣。

for batch in tqdm(ds.batch(batch_size=512)):
    embeddings = model.encode(batch["PlotSummary"])
    data = [
        {"title": title, "embedding": embedding, "year": year, "origin": origin}
        for title, embedding, year, origin in zip(
            batch["Title"], embeddings, batch["Release Year"], batch["Origin/Ethnicity"]
        )
    ]
    res = client.insert(collection_name=collection_name, data=data)

上述操作相對耗時,因為嵌入需要時間。在 2023 MacBook Pro 上使用 CPU 執行此步驟約需 2 分鐘,使用專用 GPU 執行此步驟則會更快。休息一下,喝杯咖啡吧!

將所有資料插入 Milvus 後,我們就可以開始執行搜尋。在這個範例中,我們要根據 Wikipedia 的劇情摘要搜尋電影。由於我們進行的是批次搜尋,因此搜尋時間會在電影搜尋中共享。(您能猜到我心目中根據查詢描述文字要檢索哪部電影嗎?)

queries = [
    'A shark terrorizes an LA beach.',
    'An archaeologist searches for ancient artifacts while fighting Nazis.',
    'Teenagers in detention learn about themselves.',
    'A teenager fakes illness to get off school and have adventures with two friends.',
    'A young couple with a kid look after a hotel during winter and the husband goes insane.',
    'Four turtles fight bad guys.'
    ]

# Search the database based on input text
def embed_query(data):
    vectors = model.encode(data)
    return [x for x in vectors]


query_vectors = embed_query(queries)

res = client.search(
    collection_name=collection_name,
    data=query_vectors,
    filter='origin == "American" and year > 1945 and year < 2000',
    anns_field="embedding",
    limit=3,
    output_fields=["title"],
)

for idx, hits in enumerate(res):
    print("Query:", queries[idx])
    print("Results:")
    for hit in hits:
        print(hit["entity"].get("title"), "(", round(hit["distance"], 2), ")")
    print()

結果如下

Query: An archaeologist searches for ancient artifacts while fighting Nazis.
Results:
Love Slaves of the Amazons ( 0.4 )
A Time to Love and a Time to Die ( 0.39 )
The Fifth Element ( 0.39 )

Query: Teenagers in detention learn about themselves.
Results:
The Breakfast Club ( 0.54 )
Up the Academy ( 0.46 )
Fame ( 0.43 )

Query: A teenager fakes illness to get off school and have adventures with two friends.
Results:
Ferris Bueller's Day Off ( 0.48 )
Fever Lake ( 0.47 )
Losin' It ( 0.39 )

Query: A young couple with a kid look after a hotel during winter and the husband goes insane.
Results:
The Shining ( 0.48 )
The Four Seasons ( 0.42 )
Highball ( 0.41 )

Query: Four turtles fight bad guys.
Results:
Teenage Mutant Ninja Turtles II: The Secret of the Ooze ( 0.47 )
Devil May Hare ( 0.43 )
Attack of the Giant Leeches ( 0.42 )

免費嘗試托管的 Milvus

Zilliz Cloud 無縫接入,由 Milvus 提供動力,速度提升 10 倍。

開始使用
反饋

這個頁面有幫助嗎?