【问题标题】:Nearest Neighbor using customized weights on Python scikit-learn在 Python scikit-learn 上使用自定义权重的最近邻
【发布时间】: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


    【解决方案1】:

    我对这种类型的回归了解不多,但传递给它的距离肯定有可能是一个二维数据结构,这对所有成对距离都是有意义的。

    你为什么不在你的自定义函数中放一个小预告打印语句来打印distancesdistances.shape

    【讨论】:

      【解决方案2】:

      @Jeff H 的提示将我引向了答案。

      这个函数的输入参数是一个二维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')
      # create a new array 'weights' with the same dimension of  'distances' and fill 
      # the array with 0 element.
          for i in range(distances.shape[0]): # for each prediction:
              if distances[i, 0] >= 100: # if the smaller distance is greather than 100, 
                                         # consider the nearest neighbor's weight as 1 
                                         # and the neighbor weights will stay zero
                  weights[i, 0] = 1
                                         # than continue to the next prediction
                  continue
      
              for j in range(distances.shape[1]): # aply the weight function for each distance
      
                  if (distances[i, j] >= 100):
                      continue
      
                  weights[i, j] = 1 - distances[i, j]/100
      
          return weights
      

      【讨论】:

        猜你喜欢
        • 2018-09-06
        • 2021-11-04
        • 2016-06-01
        • 1970-01-01
        • 2016-09-26
        • 2013-06-24
        • 2014-05-01
        • 2017-12-11
        • 2019-09-10
        相关资源
        最近更新 更多