KNN Mahalanobis 错误 - V 的大小不匹配 - Python

KNN Mahalanobis error - size of V does not match - Python

我正在尝试使用 Mahalanobis 作为距离度量来实现 KNN 模型,但是当我执行代码时出现错误:

Value Error: "size of V does not match

其中 V 是特征的协方差矩阵。

下面我的代码的相关部分:

X_train, X_test, y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=10,stratify=y)

knn2=KNeighborsClassifier(n_neighbors=20, metric='mahalanobis', metric_params={'V': np.cov(X_train)})

knn2.fit(X_train,y_train) # this is the line that causes the error. 

我查看了 github 上的 repo,了解 sklearn 的距离 metric code(从第 628 行开始是 Mahalanobis),可以看出错误来自以下内容:

cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2,
                              ITYPE_t size) nogil except -1:
        if size != self.size:
            with gil:
                raise ValueError('Mahalanobis dist: size of V does not match')

我已经弄清楚 self.size 是我的情况,但无法弄清楚 size 是什么。

谁能帮忙解决这个错误?

谢谢

参见 here。我认为它要求的是特征之间的协方差而不是样本之间的协方差。

将参数 rowvar=False 传递给 np.cov,它应该可以工作。您的 knn 构造函数应如下所示:

knn2=KNeighborsClassifier(n_neighbors=20, metric='mahalanobis', metric_params={'V': np.cov(X_train, rowvar=False)})