转载: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 测试数据