【发布时间】:2020-01-21 03:38:44
【问题描述】:
我正在尝试为聚类实现自定义距离度量。代码 sn-p 如下所示:
import numpy as np
from sklearn.cluster import KMeans, DBSCAN, MeanShift
def distance(x, y):
# print(x, y) -> This x and y aren't one-hot vectors and is the source of this question
match_count = 0.
for xi, yi in zip(x, y):
if float(xi) == 1. and xi == yi:
match_count += 1
return match_count
def custom_metric(x, y):
# x, y are two vectors
# distance(.,.) calculates count of elements when both xi and yi are True
return distance(x, y)
vectorized_text = np.stack([[1, 0, 0, 1] * 100,
[1, 1, 1, 0] * 100,
[0, 1, 1, 0] * 100,
[0, 0, 0, 1] * 100] * 100)
dbscan = DBSCAN(min_samples=2, metric=custom_metric, eps=3, p=1).fit(vectorized_text)
vectorized_text 是大小为n_sample x n_features 的单热编码特征矩阵。但是当custom_metric 被调用时,x 或y 中的一个变成了实值向量,而另一个仍然是 one-hot 向量。可以预料,x 和 y 都应该是 one-hot 向量。这导致 custom_metric 在运行时返回错误的结果,因此聚类不正确。
distance(x, y) 方法中的x 和y 示例:
x = [0.5 0.5 0.5 ... 0.5 0.5]
y = [0. 0. 0. 1. 0. 0. ... 1. 0.]
两者都应该是 one-hot 向量。
有没有人想办法解决这种情况?
【问题讨论】:
-
我认为您需要包含 custom_metric 的代码..
-
@PV8:已添加。请检查
-
正如您在我的回答中看到的那样,它正在工作,您能否在运行该函数之前打印 x, y...
-
x 和 y 是函数的 输入;他们怎么能“变成”任何东西?
-
@desertnaut 请尝试运行代码,您应该能够重新生成错误。
标签: python python-3.x scikit-learn cluster-analysis