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/ex7_pca.m
863 views
1
%% Machine Learning Online Class
2
% Exercise 7 | Principle Component Analysis and K-Means Clustering
3
%
4
% Instructions
5
% ------------
6
%
7
% This file contains code that helps you get started on the
8
% exercise. You will need to complete the following functions:
9
%
10
% pca.m
11
% projectData.m
12
% recoverData.m
13
% computeCentroids.m
14
% findClosestCentroids.m
15
% kMeansInitCentroids.m
16
%
17
% For this exercise, you will not need to change any code in this file,
18
% or any other files other than those mentioned above.
19
%
20
21
%% Initialization
22
clear ; close all; clc
23
24
%% ================== Part 1: Load Example Dataset ===================
25
% We start this exercise by using a small dataset that is easily to
26
% visualize
27
%
28
fprintf('Visualizing example dataset for PCA.\n\n');
29
30
% The following command loads the dataset. You should now have the
31
% variable X in your environment
32
load ('ex7data1.mat');
33
34
% Visualize the example dataset
35
plot(X(:, 1), X(:, 2), 'bo');
36
axis([0.5 6.5 2 8]); axis square;
37
38
fprintf('Program paused. Press enter to continue.\n');
39
pause;
40
41
42
%% =============== Part 2: Principal Component Analysis ===============
43
% You should now implement PCA, a dimension reduction technique. You
44
% should complete the code in pca.m
45
%
46
fprintf('\nRunning PCA on example dataset.\n\n');
47
48
% Before running PCA, it is important to first normalize X
49
[X_norm, mu, sigma] = featureNormalize(X);
50
51
% Run PCA
52
[U, S] = pca(X_norm);
53
54
% Compute mu, the mean of the each feature
55
56
% Draw the eigenvectors centered at mean of data. These lines show the
57
% directions of maximum variations in the dataset.
58
hold on;
59
drawLine(mu, mu + 1.5 * S(1,1) * U(:,1)', '-k', 'LineWidth', 2);
60
drawLine(mu, mu + 1.5 * S(2,2) * U(:,2)', '-k', 'LineWidth', 2);
61
hold off;
62
63
fprintf('Top eigenvector: \n');
64
fprintf(' U(:,1) = %f %f \n', U(1,1), U(2,1));
65
fprintf('\n(you should expect to see -0.707107 -0.707107)\n');
66
67
fprintf('Program paused. Press enter to continue.\n');
68
pause;
69
70
71
%% =================== Part 3: Dimension Reduction ===================
72
% You should now implement the projection step to map the data onto the
73
% first k eigenvectors. The code will then plot the data in this reduced
74
% dimensional space. This will show you what the data looks like when
75
% using only the corresponding eigenvectors to reconstruct it.
76
%
77
% You should complete the code in projectData.m
78
%
79
fprintf('\nDimension reduction on example dataset.\n\n');
80
81
% Plot the normalized dataset (returned from pca)
82
plot(X_norm(:, 1), X_norm(:, 2), 'bo');
83
axis([-4 3 -4 3]); axis square
84
85
% Project the data onto K = 1 dimension
86
K = 1;
87
Z = projectData(X_norm, U, K);
88
fprintf('Projection of the first example: %f\n', Z(1));
89
fprintf('\n(this value should be about 1.481274)\n\n');
90
91
X_rec = recoverData(Z, U, K);
92
fprintf('Approximation of the first example: %f %f\n', X_rec(1, 1), X_rec(1, 2));
93
fprintf('\n(this value should be about -1.047419 -1.047419)\n\n');
94
95
% Draw lines connecting the projected points to the original points
96
hold on;
97
plot(X_rec(:, 1), X_rec(:, 2), 'ro');
98
for i = 1:size(X_norm, 1)
99
drawLine(X_norm(i,:), X_rec(i,:), '--k', 'LineWidth', 1);
100
end
101
hold off
102
103
fprintf('Program paused. Press enter to continue.\n');
104
pause;
105
106
%% =============== Part 4: Loading and Visualizing Face Data =============
107
% We start the exercise by first loading and visualizing the dataset.
108
% The following code will load the dataset into your environment
109
%
110
fprintf('\nLoading face dataset.\n\n');
111
112
% Load Face dataset
113
load ('ex7faces.mat')
114
115
% Display the first 100 faces in the dataset
116
displayData(X(1:100, :));
117
118
fprintf('Program paused. Press enter to continue.\n');
119
pause;
120
121
%% =========== Part 5: PCA on Face Data: Eigenfaces ===================
122
% Run PCA and visualize the eigenvectors which are in this case eigenfaces
123
% We display the first 36 eigenfaces.
124
%
125
fprintf(['\nRunning PCA on face dataset.\n' ...
126
'(this might take a minute or two ...)\n\n']);
127
128
% Before running PCA, it is important to first normalize X by subtracting
129
% the mean value from each feature
130
[X_norm, mu, sigma] = featureNormalize(X);
131
132
% Run PCA
133
[U, S] = pca(X_norm);
134
135
% Visualize the top 36 eigenvectors found
136
displayData(U(:, 1:36)');
137
138
fprintf('Program paused. Press enter to continue.\n');
139
pause;
140
141
142
%% ============= Part 6: Dimension Reduction for Faces =================
143
% Project images to the eigen space using the top k eigenvectors
144
% If you are applying a machine learning algorithm
145
fprintf('\nDimension reduction for face dataset.\n\n');
146
147
K = 100;
148
Z = projectData(X_norm, U, K);
149
150
fprintf('The projected data Z has a size of: ')
151
fprintf('%d ', size(Z));
152
153
fprintf('\n\nProgram paused. Press enter to continue.\n');
154
pause;
155
156
%% ==== Part 7: Visualization of Faces after PCA Dimension Reduction ====
157
% Project images to the eigen space using the top K eigen vectors and
158
% visualize only using those K dimensions
159
% Compare to the original input, which is also displayed
160
161
fprintf('\nVisualizing the projected (reduced dimension) faces.\n\n');
162
163
K = 100;
164
X_rec = recoverData(Z, U, K);
165
166
% Display normalized data
167
subplot(1, 2, 1);
168
displayData(X_norm(1:100,:));
169
title('Original faces');
170
axis square;
171
172
% Display reconstructed data from only k eigenfaces
173
subplot(1, 2, 2);
174
displayData(X_rec(1:100,:));
175
title('Recovered faces');
176
axis square;
177
178
fprintf('Program paused. Press enter to continue.\n');
179
pause;
180
181
182
%% === Part 8(a): Optional (ungraded) Exercise: PCA for Visualization ===
183
% One useful application of PCA is to use it to visualize high-dimensional
184
% data. In the last K-Means exercise you ran K-Means on 3-dimensional
185
% pixel colors of an image. We first visualize this output in 3D, and then
186
% apply PCA to obtain a visualization in 2D.
187
188
close all; close all; clc
189
190
% Reload the image from the previous exercise and run K-Means on it
191
% For this to work, you need to complete the K-Means assignment first
192
A = double(imread('bird_small.png'));
193
194
% If imread does not work for you, you can try instead
195
% load ('bird_small.mat');
196
197
A = A / 255;
198
img_size = size(A);
199
X = reshape(A, img_size(1) * img_size(2), 3);
200
K = 16;
201
max_iters = 10;
202
initial_centroids = kMeansInitCentroids(X, K);
203
[centroids, idx] = runkMeans(X, initial_centroids, max_iters);
204
205
% Sample 1000 random indexes (since working with all the data is
206
% too expensive. If you have a fast computer, you may increase this.
207
sel = floor(rand(1000, 1) * size(X, 1)) + 1;
208
209
% Setup Color Palette
210
palette = hsv(K);
211
colors = palette(idx(sel), :);
212
213
% Visualize the data and centroid memberships in 3D
214
figure;
215
scatter3(X(sel, 1), X(sel, 2), X(sel, 3), 10, colors);
216
title('Pixel dataset plotted in 3D. Color shows centroid memberships');
217
fprintf('Program paused. Press enter to continue.\n');
218
pause;
219
220
%% === Part 8(b): Optional (ungraded) Exercise: PCA for Visualization ===
221
% Use PCA to project this cloud to 2D for visualization
222
223
% Subtract the mean to use PCA
224
[X_norm, mu, sigma] = featureNormalize(X);
225
226
% PCA and project the data to 2D
227
[U, S] = pca(X_norm);
228
Z = projectData(X_norm, U, 2);
229
230
% Plot in 2D
231
figure;
232
plotDataPoints(Z(sel, :), idx(sel), K);
233
title('Pixel dataset plotted in 2D, using PCA for dimensionality reduction');
234
fprintf('Program paused. Press enter to continue.\n');
235
pause;
236
237