k-means 算法octave实现

转载:https://www.cnblogs.com/pascal1000/articles/12470630.html

 

一、机器学习 k-means octave实现

 

1 看效果:

 

2 octave代码:

function idx = findClosestCentroids(X, centroids)
    % Set K
    K = size(centroids, 1);
    
    % You need to return the following variables correctly.
    idx = zeros(size(X,1), 1);
    
    m = size(X,1);
    %temp_idx = zeros(size(K,1),1);
    
    for i = 1:m
        point =  X(i,:);
        temp_idx = zeros(size(K,1),1);
        poision = 0;
        t = 0;
        
        for j = 1:K
            temp = point - centroids(j,:);
            temp_idx(j) = sum(temp.^2);
        end
        t = min(temp_idx); 
         for j = 1:K
             if(temp_idx(j) == t)
                 poision = j;
             end
         end
         
         idx(i) = poision;
    end
end



function centroids = computeCentroids(X, idx, K)
    % Useful variables
    [m n] = size(X);
    
    % You need to return the following variables correctly.
    centroids = zeros(K, n);
    
    for i = 1:K
        iter = 0;
        temp = zeros(1,n);
        for j = 1:m
            if(idx(j) == i)
                iter = iter + 1;     
                temp = temp + X(j,:);
            end
        end
        centroids(i,:) = 1/iter * temp;
    end
end


function plotDataPoints(X, idx, K)
    % Create palette
    palette = hsv(K + 1);
    colors = palette(idx, :);
    
    % Plot the data
    scatter(X(:,1), X(:,2), 15, colors);
end


clear ; close all; clc

load('ex7data2.mat');

K = 3; % 3 Centroids
centroids = [3 3; 6 2; 8 5];

for i = 1: 50
    idx = findClosestCentroids(X, centroids);
    
    centroids = computeCentroids(X, idx, K);
end

plotDataPoints(X, idx, K);



3 测试数据
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值