机器学习 k-means octave实现

一、机器学习 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 测试数据

可以向群主索取。qq群号是: 538032618

 

posted @ 2020-03-12 17:30  pascal1000  阅读(268)  评论(0)    收藏  举报