我正在尝试使用 numpy/scipy 的 k 均值算法之一为学校项目执行图像量化(减少图像的颜色数量)。该算法工作正常,但我还想计算算法每次迭代的误差总和,即样本到最近聚类中心的距离总和(这是项目任务之一)。 我找不到任何 numpy 的 kmeans 方法或其他快速、优雅的方法来执行此操作。 是否有这样的方式或方法,如果没有,执行此任务的最佳方法是什么?我的目标是尽量减少现有 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")
一次仅进行一次迭代。
关于python - k 表示使用 numpy - 计算每次迭代的误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40708497/