本文說明透過 k-near-neighbors 演算法的比對尋找。 您建置程式代碼資源,允許查詢涉及紐約市大都會藝術博物館和阿姆斯特丹 Rijksmuseum 的藝術媒體。
必要條件
- 連結至湖屋的筆記本。 如需詳細資訊 ,請流覽使用筆記本探索 Lakehouse 中的數據 。
BallTree 概觀
k-NN 模型依賴 BallTree 數據結構。 BallTree 是遞歸二進位樹狀結構,其中每個節點(或“ball”) 都包含您想要查詢之數據點的分割區或子集。 若要建置 BallTree,請判斷最接近每個數據點的「球」中心(根據特定指定特徵)。 然後,將每個數據點指派給對應最接近的「球」。這些指派會建立一個結構,允許二進位樹狀周遊,並適合自己在 BallTree 分葉尋找最接近的鄰居。
設定
匯入必要的 Python 連結庫,並準備數據集:
from synapse.ml.core.platform import *
if running_on_binder():
from IPython import get_ipython
from pyspark.sql.types import BooleanType
from pyspark.sql.types import *
from pyspark.ml.feature import Normalizer
from pyspark.sql.functions import lit, array, array_contains, udf, col, struct
from synapse.ml.nn import ConditionalKNN, ConditionalKNNModel
from PIL import Image
from io import BytesIO
import requests
import numpy as np
import matplotlib.pyplot as plt
from pyspark.sql import SparkSession
# Bootstrap Spark Session
spark = SparkSession.builder.getOrCreate()
數據集來自一個數據表,其中包含大都會博物館和 Rijksmuseum 的藝術品資訊。 資料表具有此架構:
-
標識碼:每個特定藝術品的唯一標識符
- 範例符合標識碼: 388395
- 範例 Rijks 識別碼: SK-A-2344
- 標題:藝品標題,如博物館資料庫中所寫
- 藝術家:藝術作品藝術家,如博物館資料庫中所寫
- Thumbnail_Url:藝術作品 JPEG 縮圖位置
- Image_Url 藝術作品影像的網站 URL 位置,裝載於大都會/里克斯網站上
-
文化:藝術作品的文化類別
- 範例文化類別: 拉丁美洲、 埃及等。
-
分類:藝術作品的中等類別
- 範例媒體類別:木工、繪畫等。
- Museum_Page:藝術作品的URL連結,裝載於大都會/里克斯網站上
- Norm_Features:內嵌藝術品影像
- 博物館:舉辦實際藝術品的博物館
# loads the dataset and the two trained conditional k-NN models for querying by medium and culture
df = spark.read.parquet(
"wasbs://publicwasb@mmlspark.blob.core.windows.net/met_and_rijks.parquet"
)
display(df.drop("Norm_Features"))
若要建置查詢,請定義類別
使用兩個 k-NN 模型:一個用於文化特性,另一個用於中型:
# mediums = ['prints', 'drawings', 'ceramics', 'textiles', 'paintings', "musical instruments","glass", 'accessories', 'photographs', "metalwork",
# "sculptures", "weapons", "stone", "precious", "paper", "woodwork", "leatherwork", "uncategorized"]
mediums = ["paintings", "glass", "ceramics"]
# cultures = ['african (general)', 'american', 'ancient american', 'ancient asian', 'ancient european', 'ancient middle-eastern', 'asian (general)',
# 'austrian', 'belgian', 'british', 'chinese', 'czech', 'dutch', 'egyptian']#, 'european (general)', 'french', 'german', 'greek',
# 'iranian', 'italian', 'japanese', 'latin american', 'middle eastern', 'roman', 'russian', 'south asian', 'southeast asian',
# 'spanish', 'swiss', 'various']
cultures = ["japanese", "american", "african (general)"]
# Uncomment the above for more robust and large scale searches!
classes = cultures + mediums
medium_set = set(mediums)
culture_set = set(cultures)
selected_ids = {"AK-RBK-17525-2", "AK-MAK-1204", "AK-RAK-2015-2-9"}
small_df = df.where(
udf(
lambda medium, culture, id_val: (medium in medium_set)
or (culture in culture_set)
or (id_val in selected_ids),
BooleanType(),
)("Classification", "Culture", "id")
)
small_df.count()
定義並調整條件式 k-NN 模型
為中型和文化特性數據行建立條件式 k-NN 模型。 每個模型都需要
- 輸出數據行
- 特徵資料列 (特徵向量)
- 值資料列 (輸出資料列底下的儲存格值)
- 標籤資料列 (個別 k-NN 的條件品質)
medium_cknn = (
ConditionalKNN()
.setOutputCol("Matches")
.setFeaturesCol("Norm_Features")
.setValuesCol("Thumbnail_Url")
.setLabelCol("Classification")
.fit(small_df)
)
culture_cknn = (
ConditionalKNN()
.setOutputCol("Matches")
.setFeaturesCol("Norm_Features")
.setValuesCol("Thumbnail_Url")
.setLabelCol("Culture")
.fit(small_df)
)
定義比對和視覺化方法
初始資料集和類別設定之後,請準備方法來查詢和可視化條件式 k-NN 的結果:
addMatches() 會為每個類別建立具有少數相符項目的資料框架:
def add_matches(classes, cknn, df):
results = df
for label in classes:
results = cknn.transform(
results.withColumn("conditioner", array(lit(label)))
).withColumnRenamed("Matches", "Matches_{}".format(label))
return results
plot_urls() 呼叫 plot_img ,將每個類別的頂端相符項目可視化為網格線:
def plot_img(axis, url, title):
try:
response = requests.get(url)
img = Image.open(BytesIO(response.content)).convert("RGB")
axis.imshow(img, aspect="equal")
except:
pass
if title is not None:
axis.set_title(title, fontsize=4)
axis.axis("off")
def plot_urls(url_arr, titles, filename):
nx, ny = url_arr.shape
plt.figure(figsize=(nx * 5, ny * 5), dpi=1600)
fig, axes = plt.subplots(ny, nx)
# reshape required in the case of 1 image query
if len(axes.shape) == 1:
axes = axes.reshape(1, -1)
for i in range(nx):
for j in range(ny):
if j == 0:
plot_img(axes[j, i], url_arr[i, j], titles[i])
else:
plot_img(axes[j, i], url_arr[i, j], None)
plt.savefig(filename, dpi=1600) # saves the results as a PNG
display(plt.show())
將所有專案放在一起
收看
- 數據
- 條件式 k-NN 模型
- 要查詢的藝術標識碼值
- 儲存輸出視覺效果的檔案路徑
定義稱為的函式 test_all()
媒介和文化模型先前已定型並載入。
# main method to test a particular dataset with two conditional k-NN models and a set of art IDs, saving the result to filename.png
def test_all(data, cknn_medium, cknn_culture, test_ids, root):
is_nice_obj = udf(lambda obj: obj in test_ids, BooleanType())
test_df = data.where(is_nice_obj("id"))
results_df_medium = add_matches(mediums, cknn_medium, test_df)
results_df_culture = add_matches(cultures, cknn_culture, results_df_medium)
results = results_df_culture.collect()
original_urls = [row["Thumbnail_Url"] for row in results]
culture_urls = [
[row["Matches_{}".format(label)][0]["value"] for row in results]
for label in cultures
]
culture_url_arr = np.array([original_urls] + culture_urls)[:, :]
plot_urls(culture_url_arr, ["Original"] + cultures, root + "matches_by_culture.png")
medium_urls = [
[row["Matches_{}".format(label)][0]["value"] for row in results]
for label in mediums
]
medium_url_arr = np.array([original_urls] + medium_urls)[:, :]
plot_urls(medium_url_arr, ["Original"] + mediums, root + "matches_by_medium.png")
return results_df_culture
示範
下列數據格會執行批次查詢,指定所需的影像標識碼和檔名來儲存視覺效果。
# sample query
result_df = test_all(small_df, medium_cknn, culture_cknn, selected_ids, root=".")