Path: blob/master/Week 8/Programming Assignment - 7/ex7/ex7.m
863 views
%% Machine Learning Online Class1% Exercise 7 | Principle Component Analysis and K-Means Clustering2%3% Instructions4% ------------5%6% This file contains code that helps you get started on the7% exercise. You will need to complete the following functions:8%9% pca.m10% projectData.m11% recoverData.m12% computeCentroids.m13% findClosestCentroids.m14% kMeansInitCentroids.m15%16% For this exercise, you will not need to change any code in this file,17% or any other files other than those mentioned above.18%1920%% Initialization21clear ; close all; clc2223%% ================= Part 1: Find Closest Centroids ====================24% To help you implement K-Means, we have divided the learning algorithm25% into two functions -- findClosestCentroids and computeCentroids. In this26% part, you should complete the code in the findClosestCentroids function.27%28fprintf('Finding closest centroids.\n\n');2930% Load an example dataset that we will be using31load('ex7data2.mat');3233% Select an initial set of centroids34K = 3; % 3 Centroids35initial_centroids = [3 3; 6 2; 8 5];3637% Find the closest centroids for the examples using the38% initial_centroids39idx = findClosestCentroids(X, initial_centroids);4041fprintf('Closest centroids for the first 3 examples: \n')42fprintf(' %d', idx(1:3));43fprintf('\n(the closest centroids should be 1, 3, 2 respectively)\n');4445fprintf('Program paused. Press enter to continue.\n');46pause;4748%% ===================== Part 2: Compute Means =========================49% After implementing the closest centroids function, you should now50% complete the computeCentroids function.51%52fprintf('\nComputing centroids means.\n\n');5354% Compute means based on the closest centroids found in the previous part.55centroids = computeCentroids(X, idx, K);5657fprintf('Centroids computed after initial finding of closest centroids: \n')58fprintf(' %f %f \n' , centroids');59fprintf('\n(the centroids should be\n');60fprintf(' [ 2.428301 3.157924 ]\n');61fprintf(' [ 5.813503 2.633656 ]\n');62fprintf(' [ 7.119387 3.616684 ]\n\n');6364fprintf('Program paused. Press enter to continue.\n');65pause;666768%% =================== Part 3: K-Means Clustering ======================69% After you have completed the two functions computeCentroids and70% findClosestCentroids, you have all the necessary pieces to run the71% kMeans algorithm. In this part, you will run the K-Means algorithm on72% the example dataset we have provided.73%74fprintf('\nRunning K-Means clustering on example dataset.\n\n');7576% Load an example dataset77load('ex7data2.mat');7879% Settings for running K-Means80K = 3;81max_iters = 10;8283% For consistency, here we set centroids to specific values84% but in practice you want to generate them automatically, such as by85% settings them to be random examples (as can be seen in86% kMeansInitCentroids).87initial_centroids = [3 3; 6 2; 8 5];8889% Run K-Means algorithm. The 'true' at the end tells our function to plot90% the progress of K-Means91[centroids, idx] = runkMeans(X, initial_centroids, max_iters, true);92fprintf('\nK-Means Done.\n\n');9394fprintf('Program paused. Press enter to continue.\n');95pause;9697%% ============= Part 4: K-Means Clustering on Pixels ===============98% In this exercise, you will use K-Means to compress an image. To do this,99% you will first run K-Means on the colors of the pixels in the image and100% then you will map each pixel onto its closest centroid.101%102% You should now complete the code in kMeansInitCentroids.m103%104105fprintf('\nRunning K-Means clustering on pixels from an image.\n\n');106107% Load an image of a bird108%A = double(imread('bird_small.png'));109A = double(imread('spidey.png'));110% If imread does not work for you, you can try instead111% load ('bird_small.mat');112113A = A / 255; % Divide by 255 so that all values are in the range 0 - 1114115% Size of the image116img_size = size(A);117118% Reshape the image into an Nx3 matrix where N = number of pixels.119% Each row will contain the Red, Green and Blue pixel values120% This gives us our dataset matrix X that we will use K-Means on.121X = reshape(A, img_size(1) * img_size(2), 3);122123% Run your K-Means algorithm on this data124% You should try different values of K and max_iters here125K = 16;126max_iters = 10;127128% When using K-Means, it is important the initialize the centroids129% randomly.130% You should complete the code in kMeansInitCentroids.m before proceeding131initial_centroids = kMeansInitCentroids(X, K);132133% Run K-Means134[centroids, idx] = runkMeans(X, initial_centroids, max_iters);135136fprintf('Program paused. Press enter to continue.\n');137pause;138139140%% ================= Part 5: Image Compression ======================141% In this part of the exercise, you will use the clusters of K-Means to142% compress an image. To do this, we first find the closest clusters for143% each example. After that, we144145fprintf('\nApplying K-Means to compress an image.\n\n');146147% Find closest cluster members148idx = findClosestCentroids(X, centroids);149150% Essentially, now we have represented the image X as in terms of the151% indices in idx.152153% We can now recover the image from the indices (idx) by mapping each pixel154% (specified by its index in idx) to the centroid value155X_recovered = centroids(idx,:);156157% Reshape the recovered image into proper dimensions158X_recovered = reshape(X_recovered, img_size(1), img_size(2), 3);159160% Display the original image161subplot(1, 2, 1);162imagesc(A);163title('Original');164165% Display compressed image side by side166subplot(1, 2, 2);167imagesc(X_recovered)168title(sprintf('Compressed, with %d colors.', K));169170171fprintf('Program paused. Press enter to continue.\n');172pause;173174175176