【发布时间】:2020-10-31 19:44:29
【问题描述】:
晚安,
我想使用最近邻模型进行具有非均匀权重的回归。我在User Guide 中看到我可以在模型的声明中使用weights='distance',然后权重将与距离成反比,但得到的结果并不是我想要的。
我在Documentation 中看到我可以对预测中使用的权重(给定距离)使用函数,因此我创建了以下函数:
from sklearn.neighbors import KNeighborsRegressor
import numpy
nparray = numpy.array
def customized_weights(distances: nparray)->nparray:
for distance in distances:
if (distance >= 100 or distance <= -100):
yield 0
yield (1 - abs(distance)/100)
并声明了这样的方法:
knn: KNeighborsRegressor = KNeighborsRegressor(n_neighbors=50, weights=customized_weights ).fit(X_train, y_train)
在那之前,一切正常。但是当我尝试使用模型进行预测时,我得到了错误:
File "knn_with_weights.py", line 14, in customized_weights
if (distance >= 100 or distance <= -100):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我不明白我做错了什么。在Documentation 上写道,我的函数应该有一个距离数组作为参数,并且应该返回等效的权重。我做错了什么?
提前致谢。
【问题讨论】:
标签: python python-3.x machine-learning scikit-learn nearest-neighbor