在k-means中寻找中心的平均值



由于K-means算法容易受列的顺序影响,因此我执行了100次,并将每次迭代的最终中心存储在数组中。

我想计算数组的平均中心,但我只得到一个值使用这个

a =np.mean(center_array)
vmean = np.vectorize(np.mean)
vmean(a)

如何计算中位数?

这是我的centers数组的结构

[[ 1.39450598,  0.65213679,  1.37195399,  0.02577591,  0.17637011,
0.44572744,  1.50699298, -0.02577591, -0.17637011, -0.48222273,
-0.14651225, -0.12975152],
[-0.40910528, -0.18480587, -0.40459059,  1.00860933, -0.91902229,
-0.13536744, -0.45108061, -1.00860933,  0.91902229,  0.11367937,
0.19771608,  0.23722015],
[-0.46264585, -0.23289607, -0.45219009,  0.0290917 ,  1.08811289,
-0.14996175, -0.48998741, -0.0290917 , -1.08811289,  0.19925625,
-0.14748408, -0.1943812 ]]), array([[ 0.20004497, -0.12493111,  0.99146416, -0.91902229, -0.17537297,
0.11154588, -0.41348193, -0.99146416, -0.45307083, -0.4091783 ,
0.18579957,  0.91902229]],

您需要指定包含每次迭代的最终中心的轴,否则将在扁平数组上计算np.mean,从而产生单个值。从文档:

返回数组元素的平均值。默认情况下,平均值将在扁平数组上获取,否则将在指定的轴上获取。

import numpy as np
np.random.seed(42)
x = np.random.rand(5,3)
out1 = x.mean()
print(out1, out1.shape)
# 0.49456456164468965 ()
out2 = x.mean(axis=1) # rows
print(out2, out2.shape)
# [0.68574946 0.30355721 0.50845826 0.56618897 0.40886891] (5,)
out3 = x.mean(axis=0) # columns
print(out3, out3.shape)
# [0.51435949 0.44116654 0.52816766] (3,)

最新更新