晚安,
我想使用非均匀权重的最近邻模型进行回归。我在用户指南中看到,可以在模型声明中使用weights='distance'
,这样权重将与距离成反比,但我得到的结果并不是我想要的。
我在文档中看到,可以使用一个函数来根据距离设定权重用于预测,所以我创建了以下函数:
from sklearn.neighbors import KNeighborsRegressorimport numpynparray = numpy.arraydef 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()
我不明白我哪里做错了。在文档中写到,我的函数应该有一个距离数组作为参数,并返回相应的权重。我哪里做错了?
提前感谢。
回答:
@***的提示让我找到了答案。
这个函数的输入参数是一个二维的numpy数组distances
,其形状为(predictions, neighbors)
,其中:
- predictions 是所需预测的数量(当你调用
knn.predict(X_1, X_2, X_3, ...)
时); - neighbors 是使用的邻居数量(在我这里,n_neighbors=50)。
每个元素distances[i, j]
代表第i
个预测与第j
个最近邻居的距离(j
值越小,距离越小)。
该函数必须返回一个与输入数组相同维度的数组,其中包含每个距离对应的权重。
我不知道这是不是最快的方法,但我找到了这个解决方案:
def customized_weights(distances: nparray)->nparray: weights: nparray = nparray(numpy.full(distances.shape, 0), dtype='float')# 创建一个与'distances'相同维度的新的'weights'数组,并用0填充。 for i in range(distances.shape[0]): # 对每个预测: if distances[i, 0] >= 100: # 如果最小的距离大于100, # 则将最近邻居的权重设为1 # 其他邻居的权重保持为零 weights[i, 0] = 1 # 然后继续下一个预测 continue for j in range(distances.shape[1]): # 对每个距离应用权重函数 if (distances[i, j] >= 100): continue weights[i, j] = 1 - distances[i, j]/100 return weights