KMeans 的不平衡因子?
Unbalanced factor of KMeans?
编辑:这个问题的答案在以下地方被大量讨论:
在 中,我们了解了如何计算 KMeans 模型的成本。我想知道我们是否能够计算出不平衡因子?
如果Spark没有提供这样的功能,有什么简单的方法可以实现吗?
我找不到不平衡因素的参考,但它应该类似于 Yael 的 unbalanced_factor(我的评论):
// @hist: the number of points assigned to a cluster
// @n: the number of clusters
double ivec_unbalanced_factor(const int *hist, long n) {
int vw;
double tot = 0, uf = 0;
for (vw = 0 ; vw < n ; vw++) {
tot += hist[vw];
uf += hist[vw] * (double) hist[vw];
}
uf = uf * n / (tot * tot);
return uf;
}
我找到了 here。
所以想法是 tot
(对于总计)将等于分配给集群的点数(即等于我们数据集的大小),而 uf
(对于不平衡factor) 保存分配给集群的点数的平方。
最后他用uf = uf * n / (tot * tot);
来计算。
在 python
中可能是这样的:
# I suppose you are passing an RDD of tuples, where the key is the cluster and the value is a vector with the features.
def unbalancedFactor(rdd):
pdd = rdd.map(lambda x: (x[0], 1)).reduceByKey(lambda a, b: a + b) # you can obtain the number of points per cluster
n = pdd.count()
total = pdd.map(lambda x: x[1]).sum()
uf = pdd.map(lambda x: x[1] * float(x[1])).sum()
return uf * n / (total * total)
编辑:这个问题的答案在以下地方被大量讨论:
在
如果Spark没有提供这样的功能,有什么简单的方法可以实现吗?
我找不到不平衡因素的参考,但它应该类似于 Yael 的 unbalanced_factor(我的评论):
// @hist: the number of points assigned to a cluster
// @n: the number of clusters
double ivec_unbalanced_factor(const int *hist, long n) {
int vw;
double tot = 0, uf = 0;
for (vw = 0 ; vw < n ; vw++) {
tot += hist[vw];
uf += hist[vw] * (double) hist[vw];
}
uf = uf * n / (tot * tot);
return uf;
}
我找到了 here。
所以想法是 tot
(对于总计)将等于分配给集群的点数(即等于我们数据集的大小),而 uf
(对于不平衡factor) 保存分配给集群的点数的平方。
最后他用uf = uf * n / (tot * tot);
来计算。
在 python
中可能是这样的:
# I suppose you are passing an RDD of tuples, where the key is the cluster and the value is a vector with the features.
def unbalancedFactor(rdd):
pdd = rdd.map(lambda x: (x[0], 1)).reduceByKey(lambda a, b: a + b) # you can obtain the number of points per cluster
n = pdd.count()
total = pdd.map(lambda x: x[1]).sum()
uf = pdd.map(lambda x: x[1] * float(x[1])).sum()
return uf * n / (total * total)