File size: 3,125 Bytes
b321188 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "6bdb67d9",
"metadata": {},
"outputs": [],
"source": [
"from pymilvus import MilvusClient\n",
"\n",
"\n",
"client = MilvusClient(uri=\"./db/Amazon_electronics.db\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "cd7440ec",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['image_embeddings', 'metadata_embeddings', 'rating_embeddings']"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"client.list_collections()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5ef468e8",
"metadata": {},
"outputs": [],
"source": [
"def query_image_similarity(client, asin, top_k=50):\n",
" \"\"\"\n",
" 查询指定 asin 对应的图片向量,并在 Milvus 中搜索相似商品(图片相似度)。\n",
"\n",
" 返回:\n",
" 字典格式 {asin: sim_score}\n",
" 其中 sim_score 采用 COSINE 指标,计算方式: sim_score = 1 - hit.distance\n",
" \"\"\"\n",
" try:\n",
" query_expr = f\"asin == '{asin}'\"\n",
" query_res = client.query(\n",
" collection_name=\"image_embeddings\",\n",
" filter=query_expr,\n",
" output_fields=[\"embedding\"],\n",
" )\n",
" if not query_res:\n",
" return {}\n",
"\n",
" target_embedding = query_res[0][\"embedding\"]\n",
" search_params = {\"metric_type\": \"COSINE\", \"params\": {\"nprobe\": 10}}\n",
" search_results = client.search(\n",
" collection_name=\"image_embeddings\",\n",
" data=[target_embedding],\n",
" anns_field=\"embedding\",\n",
" search_params=search_params, \n",
" limit=top_k,\n",
" filter=f\"asin != '{asin}'\", # 排除自身\n",
" )\n",
"\n",
" sim_dict = {}\n",
" for hit in search_results[0]:\n",
" sim_asin = hit[\"id\"]\n",
" sim_score = 1 - hit[\"distance\"]\n",
" sim_dict[sim_asin] = sim_score\n",
" return sim_dict\n",
" except Exception as e:\n",
" print(f\"图片相似度查询失败: {e}\")\n",
" return {}"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3bec7aa1",
"metadata": {},
"outputs": [],
"source": [
"query_image_similarity(client, \"B07X2Y3Z5F\", top_k=10)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv (3.12.3)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|