Path: blob/master/Week 8/Programming Assignment - 7/ex7/runkMeans.m
863 views
function [centroids, idx] = runkMeans(X, initial_centroids, ...1max_iters, plot_progress)2%RUNKMEANS runs the K-Means algorithm on data matrix X, where each row of X3%is a single example4% [centroids, idx] = RUNKMEANS(X, initial_centroids, max_iters, ...5% plot_progress) runs the K-Means algorithm on data matrix X, where each6% row of X is a single example. It uses initial_centroids used as the7% initial centroids. max_iters specifies the total number of interactions8% of K-Means to execute. plot_progress is a true/false flag that9% indicates if the function should also plot its progress as the10% learning happens. This is set to false by default. runkMeans returns11% centroids, a Kxn matrix of the computed centroids and idx, a m x 112% vector of centroid assignments (i.e. each entry in range [1..K])13%1415% Set default value for plot progress16if ~exist('plot_progress', 'var') || isempty(plot_progress)17plot_progress = false;18end1920% Plot the data if we are plotting progress21if plot_progress22figure;23hold on;24end2526% Initialize values27[m n] = size(X);28K = size(initial_centroids, 1);29centroids = initial_centroids;30previous_centroids = centroids;31idx = zeros(m, 1);3233% Run K-Means34for i=1:max_iters3536% Output progress37fprintf('K-Means iteration %d/%d...\n', i, max_iters);38if exist('OCTAVE_VERSION')39fflush(stdout);40end4142% For each example in X, assign it to the closest centroid43idx = findClosestCentroids(X, centroids);4445% Optionally, plot progress here46if plot_progress47plotProgresskMeans(X, centroids, previous_centroids, idx, K, i);48previous_centroids = centroids;49fprintf('Press enter to continue.\n');50pause;51end5253% Given the memberships, compute new centroids54centroids = computeCentroids(X, idx, K);55end5657% Hold off if we are plotting progress58if plot_progress59hold off;60end6162end63646566