在sklearn的BallTree中使用加权的minkowski度量

时间:2016-12-16 21:55:20

标签: scikit-learn metrics

我一直在玩BallTree及其提供的不同指标。但是,当我使用wminkowski时,权重似乎对结果没有任何影响:

df = pd.DataFrame()
num_features = 4
num_samples = 100
for i in range(num_features):
    df['A_%s'%(i+1)] = np.random.rand(num_samples)
    df['A_%s'%(i+1)] = df['A_%s'%(i+1)].apply(lambda x: 500 - (1000 * x ** 3))
point = np.array([int(1000 * r ** 3) for r in np.random.rand(num_features)]).reshape(1, -1)
weights = [int(10000 * r ** 2) for r in np.random.rand(num_features)]

tree1 = sklearn.neighbors.BallTree(df, metric='minkowski')
tree2 = sklearn.neighbors.BallTree(df, metric='wminkowski', p=2, w=[1] * num_features) # Should be just like tree1
tree3 = sklearn.neighbors.BallTree(df, metric='wminkowski', p=2, w=weights)

d1, i1 = tree1.query(point, k=5)
d2, i2 = tree2.query(point, k=5)
d3, i3 = tree2.query(point, k=5)

print 'Point:'
print point
print 'Weights:'
print weights
print 'Distances:'
print d1
print d2
print d3
print 'Indices:'
print i1
print i2
print i3

输出是:

Point:
[[ 16  58   0 884]]
Weights:
[2869, 46, 1558, 5835]
Distances:
[[ 451.55203926  537.61234492  601.29840519  601.74059138  647.46934474]]
[[ 451.55203926  537.61234492  601.29840519  601.74059138  647.46934474]]
[[ 451.55203926  537.61234492  601.29840519  601.74059138  647.46934474]]
Indices:
[[61 31 86 43 93]]
[[61 31 86 43 93]]
[[61 31 86 43 93]]

我尝试使用不同数量的功能和样本运行上面的代码,每次所有三棵树都返回完全相同的输出,而我期望tree3返回的输出不同。这是为什么?我使用的是sklearn版本0.18.1。

1 个答案:

答案 0 :(得分:1)

我的猜测是因为在示例中您将tree2分配给d3,i3 - 违规行:

d3, i3 = tree2.query(point, k=5)

当你可能意味着:

d3, i3 = tree3.query(point, k=5)

tree2更改为tree3,在tree3中提供了不同的结果。