使用Pynndescent实现近似最近邻时缺少fit/transform如何计算评估指标
Pynndescent 近似最近邻预测及评估指标计算解决方案
方案1:使用scikit-learn兼容接口直接调用fit/transform
pynndescent官方提供了适配sklearn接口的PyNNDescentTransformer类,原生支持fit和transform方法,可直接对标sklearn的近邻类使用:
from pynndescent import PyNNDescentTransformer import numpy as np # 初始化ANN模型,按需设置邻居数、距离度量等参数 ann_model = PyNNDescentTransformer( n_neighbors=10, metric="euclidean", n_jobs=-1 ) # 等价fit操作:在训练集上拟合索引 ann_model.fit(train_data) # 等价transform操作:返回测试集每个样本的最近邻索引、距离 test_neighbors_indices, test_neighbors_distances = ann_model.transform(test_data)
方案2:使用底层NNDescent类手动实现等价逻辑
如果使用的是底层NNDescent核心类,无需依赖封装接口,通过query方法即可实现transform的等价功能:
from pynndescent import NNDescent # 等价fit操作:用训练集构建ANN索引 index = NNDescent( train_data, n_neighbors=10, metric="euclidean", n_jobs=-1 ) # 等价transform操作:查询测试集的k个最近邻 test_neighbors_indices, test_neighbors_distances = index.query(test_data, k=10)
基于近邻结果计算评估指标
拿到测试集的最近邻索引后,通过k近邻投票得到预测标签,即可计算各类分类评估指标:
from scipy.stats import mode from sklearn.metrics import precision_score, recall_score, f1_score, confusion_matrix # k近邻投票得到预测标签,train_labels为训练集对应标签,y_true为测试集真实标签 y_pred = mode(train_labels[test_neighbors_indices], axis=1, keepdims=False).mode # 计算指标,average参数可根据二分类/多分类需求调整为binary/micro/weighted precision = precision_score(y_true, y_pred, average="macro") recall = recall_score(y_true, y_pred, average="macro") f1 = f1_score(y_true, y_pred, average="macro") conf_mat = confusion_matrix(y_true, y_pred)
注意事项
- 若使用版本较低的pynndescent,可先执行
pip install --upgrade pynndescent升级到最新版本,确保接口可用 - 构建索引的
n_neighbors和查询的k可按需调整,分类任务建议取k为奇数,避免投票平局 - 距离度量
metric可替换为cosine、manhattan等符合任务需求的指标
内容的提问来源于stack exchange,提问作者Syed Shakir
相关产品推荐
相关产品推荐

