Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/Coursera-Machine-Learning
Path: blob/master/Week 8/Programming Assignment - 7/ex7/runkMeans.m
863 views
1
function [centroids, idx] = runkMeans(X, initial_centroids, ...
2
max_iters, plot_progress)
3
%RUNKMEANS runs the K-Means algorithm on data matrix X, where each row of X
4
%is a single example
5
% [centroids, idx] = RUNKMEANS(X, initial_centroids, max_iters, ...
6
% plot_progress) runs the K-Means algorithm on data matrix X, where each
7
% row of X is a single example. It uses initial_centroids used as the
8
% initial centroids. max_iters specifies the total number of interactions
9
% of K-Means to execute. plot_progress is a true/false flag that
10
% indicates if the function should also plot its progress as the
11
% learning happens. This is set to false by default. runkMeans returns
12
% centroids, a Kxn matrix of the computed centroids and idx, a m x 1
13
% vector of centroid assignments (i.e. each entry in range [1..K])
14
%
15
16
% Set default value for plot progress
17
if ~exist('plot_progress', 'var') || isempty(plot_progress)
18
plot_progress = false;
19
end
20
21
% Plot the data if we are plotting progress
22
if plot_progress
23
figure;
24
hold on;
25
end
26
27
% Initialize values
28
[m n] = size(X);
29
K = size(initial_centroids, 1);
30
centroids = initial_centroids;
31
previous_centroids = centroids;
32
idx = zeros(m, 1);
33
34
% Run K-Means
35
for i=1:max_iters
36
37
% Output progress
38
fprintf('K-Means iteration %d/%d...\n', i, max_iters);
39
if exist('OCTAVE_VERSION')
40
fflush(stdout);
41
end
42
43
% For each example in X, assign it to the closest centroid
44
idx = findClosestCentroids(X, centroids);
45
46
% Optionally, plot progress here
47
if plot_progress
48
plotProgresskMeans(X, centroids, previous_centroids, idx, K, i);
49
previous_centroids = centroids;
50
fprintf('Press enter to continue.\n');
51
pause;
52
end
53
54
% Given the memberships, compute new centroids
55
centroids = computeCentroids(X, idx, K);
56
end
57
58
% Hold off if we are plotting progress
59
if plot_progress
60
hold off;
61
end
62
63
end
64
65
66