gpt4 book ai didi

python - 最近邻的距离函数的输入维度

转载 作者:行者123 更新时间:2023-11-28 18:25:54 25 4
gpt4 key购买 nike

在无监督最近邻的情况下 scikit-learn ,我已经实现了自己的距离函数来处理我的不确定点(即一个点表示为正态分布):

def my_mahalanobis_distance(x, y):

'''
x: array of shape (4,) x[0]: mu_x_1, x[1]: mu_x_2,
x[2]: cov_x_11, x[3]: cov_x_22
y: array of shape (4,) y[0]: mu_ y_1, y[1]: mu_y_2,
y[2]: cov_y_11, y[3]: cov_y_22
'''

cov_inv = np.linalg.inv(np.diag(x[:2])+np.diag(y[:2]))
return sp.spatial.distance.mahalanobis(x[:2], y[:2], cov_inv)

但是,当我设置最近的邻居时:

nnbrs = NearestNeighbors(n_neighbors=1, metric='pyfunc', func=my_mahalanobis_distance)
nearest_neighbors = nnbrs.fit(X)

哪里X(N, 4) (n_samples, n_features)数组,如果我打印 xy在我的 my_mahalanobis_distance , 我得到 (10,) 的形状而不是 (4,)正如我所料。

例子:

我将以下行添加到 my_mahalanobis_distance :

print(x.shape)

然后在我的主要部分:

n_features = 4
n_samples = 10
# generate X array:
X = np.random.rand(n_samples, n_features)
nnbrs = NearestNeighbors(n_neighbors=1, metric='pyfunc', func=my_mahalanobis_distance)
nearest_neighbors = nnbrs.fit(X)

结果是:

(10,)
ValueError: shapes (2,) and (8,8) not aligned: 2 (dim 0) != 8 (dim 0)

我完全理解这个错误,但我不明白为什么我的 x.shape(10,)而我的功能数量是 4X .

我正在使用 Python 2.7.10scikit-learn 0.16.1

编辑:

替换 return sp.spatial.distance.mahalanobis(x[:2], y[:2], cov_inv)通过 return 1仅用于测试返回:

(10,)
(4,)
(4,)
(4,)
(4,)
(4,)
(4,)
(4,)
(4,)
(4,)
(4,)

所以只有第一次调用 my_mahalanobis_distance是错的。看着 xy第一次迭代的值,我的观察是:

  • xy是一样的

  • 如果我多次运行我的代码,xy仍然相同,但与上一次运行相比它们的值发生了变化。

  • 这些值似乎来自 numpy.random功能。

我会得出结论,这样的第一次调用是一段尚未删除的调试代码。

最佳答案

这不是一个答案,但对于评论来说太长了。我无法重现错误。

使用:

Python 3.5.2 和sklearn 0.18.1

代码:

from sklearn.neighbors import NearestNeighbors
import numpy as np
import scipy as sp
n_features = 4
n_samples = 10
# generate X array:
X = np.random.rand(n_samples, n_features)


def my_mahalanobis_distance(x, y):
cov_inv = np.linalg.inv(np.diag(x[:2])+np.diag(y[:2]))
print(x.shape)
return sp.spatial.distance.mahalanobis(x[:2], y[:2], cov_inv)

n_features = 4
n_samples = 10
# generate X array:
X = np.random.rand(n_samples, n_features)
nnbrs = NearestNeighbors(n_neighbors=1, metric=my_mahalanobis_distance)
nearest_neighbors = nnbrs.fit(X)

输出是

(4,)
(4,)
(4,)
(4,)
(4,)
(4,)
(4,)
(4,)
(4,)
(4,)

关于python - 最近邻的距离函数的输入维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41504493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com