我试图实现一个KNN模型,使用Mahalanobis作为距离度量,但是当我执行代码时,我得到了一个错误:
值错误:“V的大小不匹配
其中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上查看了sklearn的距离度量码 (从第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。
有人能帮忙纠正这个错误吗?
谢谢
发布于 2021-05-10 09:24:11
将参数rowvar=False传递给np.cov,它应该可以工作。您的knn构造函数应该如下所示:
knn2=KNeighborsClassifier(n_neighbors=20, metric='mahalanobis', metric_params={'V': np.cov(X_train, rowvar=False)})发布于 2020-05-12 18:49:19
见这里。我认为这是要求特征之间的协方差,而不是样本。
https://stackoverflow.com/questions/59862791
复制相似问题