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

问题描述 投票:0回答:1

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

值错误:“ 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的距离metric code(从628行开始是马哈拉诺比斯,并且可以看到由于以下原因引起的错误:

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是什么。

有人可以帮助解决此错误吗?

谢谢

python knn mahalanobis
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.