急求:谁懂Kmeans聚类算法,求一完整的Kmeans聚类的matlab源程序,一定要多维的,最好带图像,不胜感激

急求:谁懂Kmeans聚类算法,求一完整的Kmeans聚类的matlab源程序,一定要多维的,最好带图像,不胜感激,第1张

1 >

我把K-mediods的matlab代码贴出来,你好好学习一下

function label = kmedoids( data,k,start_data )

% kmedoids k中心点算法函数

% data 待聚类的数据集,每一行是一个样本数据点

% k 聚类个数

% start_data 聚类初始中心值,每一行为一个中心点,有cluster_n行

% class_idx 聚类结果,每个样本点标记的类别

% 初始化变量

n = length(data);

dist_temp1 = zeros(n,k);

dist_temp2 = zeros(n,k);

last = zeros(n,1);

a = 0;

b = 0;

if nargin==3

centroid = start_data;

else

centroid = data(randsample(n,k),:);

end

for a = 1:k

temp1 = ones(n,1)centroid(a,:);

dist_temp1(:,a) = sum((data-temp1)^2,2);

end

[~,label] = min(dist_temp1,[],2);

while any(label~=last)

for a = 1:k

temp2 = ones(numel(data(label==a)),1);

temp3 = data(label==a);

for b = 1:n

temp4 = temp2data(b,:);

temp5 = sum((temp3-temp4)^2,2);

dist_temp2(b,a) = sum(temp5,1);

end

end

[~,centry_indx] = min(dist_temp2,[],1);

last = label;

centroid = data(centry_indx,:);

for a = 1:k

temp1 = ones(n,1)centroid(a,:);

dist_temp1(:,a) = sum((data-temp1)^2,2);

end

[~,label] = min(dist_temp1,[],2);

end

end

难得被人求助一次, 这个必须回答一下 不过你的需求确实没有写得太清楚 根据k值算法出来的是主要颜色有三个, 所以我把三个颜色都打在记事本里了 如果和你的需求有误, 请自行解决吧

另外这里需要用到numpy的库, 希望你装了, 如果没装, 这个直接安装也比较麻烦, 可以看一下portablepython的绿色版。

代码如下:

# -- coding: utf-8 --

import Image

import random

import numpy

class Cluster(object):

    def __init__(self):

        selfpixels = []

        selfcentroid = None

    def addPoint(self, pixel):

        selfpixelsappend(pixel)

    def setNewCentroid(self):

        R = [colour[0] for colour in selfpixels]

        G = [colour[1] for colour in selfpixels]

        B = [colour[2] for colour in selfpixels]

        R = sum(R) / len(R)

        G = sum(G) / len(G)

        B = sum(B) / len(B)

        selfcentroid = (R, G, B)

        selfpixels = []

        return selfcentroid

class Kmeans(object):

    def __init__(self, k=3, max_iterations=5, min_distance=50, size=200):

        selfk = k

        selfmax_iterations = max_iterations

        selfmin_distance = min_distance

        selfsize = (size, size)

    def run(self, image):

        selfimage = image

        selfimagethumbnail(selfsize)

        selfpixels = numpyarray(imagegetdata(), dtype=numpyuint8)

        selfclusters = [None for i in range(selfk)]

        selfoldClusters = None

        randomPixels = randomsample(selfpixels, selfk)

        for idx in range(selfk):

            selfclusters[idx] = Cluster()

            selfclusters[idx]centroid = randomPixels[idx]

        iterations = 0

        while selfshouldExit(iterations) is False:

            selfoldClusters = [clustercentroid for cluster in selfclusters]

            print iterations

            for pixel in selfpixels:

                selfassignClusters(pixel)

            for cluster in selfclusters:

                clustersetNewCentroid()

            iterations += 1

        return [clustercentroid for cluster in selfclusters]

    def assignClusters(self, pixel):

        shortest = float('Inf')

        for cluster in selfclusters:

            distance = selfcalcDistance(clustercentroid, pixel)

            if distance < shortest:

                shortest = distance

                nearest = cluster

        nearestaddPoint(pixel)

    def calcDistance(self, a, b):

        result = numpysqrt(sum((a - b)  2))

        return result

    def shouldExit(self, iterations):

        if selfoldClusters is None:

            return False

        for idx in range(selfk):

            dist = selfcalcDistance(

                numpyarray(selfclusters[idx]centroid),

                numpyarray(selfoldClusters[idx])

            )

            if dist < selfmin_distance:

                return True

        if iterations <= selfmax_iterations:

            return False

        return True

    # ############################################

    # The remaining methods are used for debugging

    def showImage(self):

        selfimageshow()

    def showCentroidColours(self):

        for cluster in selfclusters:

            image = Imagenew("RGB", (200, 200), clustercentroid)

            imageshow()

    def showClustering(self):

        localPixels = [None]  len(selfimagegetdata())

        for idx, pixel in enumerate(selfpixels):

                shortest = float('Inf')

                for cluster in selfclusters:

                    distance = selfcalcDistance(

                        clustercentroid,

                        pixel

                    )

                    if distance < shortest:

                        shortest = distance

                        nearest = cluster

                localPixels[idx] = nearestcentroid

        w, h = selfimagesize

        localPixels = numpyasarray(localPixels)\

            astype('uint8')\

            reshape((h, w, 3))

        colourMap = Imagefromarray(localPixels)

        colourMapshow()

    

if __name__=="__main__":

    from PIL import Image

    import os

    

    k_image=Kmeans()

    path = r'\\pics\\'

    fp = open('file_colortxt','w')

    for filename in oslistdir(path):

        print path+filename

        try:

            color = k_imagerun(Imageopen(path+filename))

            fpwrite('The color of '+filename+' is '+str(color)+'\n')

        except:

            print "This file format is not support"

    fpclose()

以上就是关于急求:谁懂Kmeans聚类算法,求一完整的Kmeans聚类的matlab源程序,一定要多维的,最好带图像,不胜感激全部的内容,包括:急求:谁懂Kmeans聚类算法,求一完整的Kmeans聚类的matlab源程序,一定要多维的,最好带图像,不胜感激、MATLAB 有序聚类突变检验核心程序、怎么用Matlab计算聚类算法的正确率问题等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zz/9271902.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-26
下一篇 2023-04-26

发表评论

登录后才能评论

评论列表(0条)

保存