【发布时间】:2017-04-04 03:49:03
【问题描述】:
我正在尝试使用 numpy/scipy 的 k-means 算法之一为学校项目执行图像量化(减少图像的颜色数量)。算法工作正常,但我也想计算算法每次迭代的误差总和,即样本到它们最近的聚类中心的距离总和(这是项目任务之一)。 我找不到任何 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
【问题讨论】:
-
问题是这个类不能告诉我每次迭代的错误,只能告诉我最终结果的错误...
-
啊,好的。嗯...我很抱歉从来没有这样做过。我确信
scikit至少可以作为一个起点。如果没有,那么恐怕其他图书馆都没有。
标签: python numpy scipy k-means