Python k表示使用numpy-计算每次迭代的误差

Python k表示使用numpy-计算每次迭代的误差,python,numpy,scipy,k-means,Python,Numpy,Scipy,K Means,我正在尝试使用numpy/scipy的k-means算法之一为学校项目执行图像量化(减少图像的颜色数量)。algirithm工作正常,但我还想计算算法每次迭代的误差总和,即样本到最近聚类中心的距离总和(这是项目任务之一)。 我找不到任何kmeans的numpy方法或其他快速、优雅的方法来执行此操作。 是否有这样一种方式或方法,如果没有,执行此任务的最佳方式是什么?我的目标是最小化对现有kmeans算法的任何重新实现 下面我添加了我的代码 import scipy.cluster.vq as vq

我正在尝试使用numpy/scipy的k-means算法之一为学校项目执行图像量化(减少图像的颜色数量)。algirithm工作正常,但我还想计算算法每次迭代的误差总和,即样本到最近聚类中心的距离总和(这是项目任务之一)。 我找不到任何kmeans的numpy方法或其他快速、优雅的方法来执行此操作。 是否有这样一种方式或方法,如果没有,执行此任务的最佳方式是什么?我的目标是最小化对现有kmeans算法的任何重新实现

下面我添加了我的代码

import scipy.cluster.vq as vq

def quantize_rgb(im_orig, n_quant, n_iter):
    """
    A function that performs optimal quantization of a given RGB image.
    :param im_orig: the input RGB image to be quantized (float32 image with values in [0, 1])
    :param n_quant: the number of intensities the output image should have
    :param n_iter: the maximum number of iterations of the optimization procedure (may converge earlier.)
    """
    reshaped_im = im_orig.reshape(im_orig.shape[0] * im_orig.shape[1], 3)
    centroids, label = vq.kmeans2(reshaped_im, n_quant, n_iter)
    reshaped_im = centroids[label]
    im_quant = reshaped_im.reshape(im_orig.shape[0], im_orig.shape[1], 3)

    return im_quant
简单使用

vq.kmeans2(k=previous_centers, iter=1, minit="matrix")

一次只做一次迭代

看看这个:问题是这个类不能告诉我每次迭代的错误,只有最终结果的错误…啊,好的。隐马尔可夫模型。。。对不起,我从来没有这样做过。我相信
scikit
至少可以作为一个起点。如果没有,恐怕没有其他图书馆有。太好了!起初我拒绝了这个解决方案,因为我认为kmeans总是使用随机起始点,但是
minit=“matrix”
很好地解决了这个问题。