代码:https://github.com/LiuZhe6/AndrewNGMachineLearning
文章目录
测试:Principal Component Analysis
第一题
答案
AB
分析:
若按照C和D方向进行投射,则投射误差会非常大。
第二题
答案
C
第三题
答案
D
第四题
答案
CD
第五题
答案
AB
编程练习:K-Means Clustering and PCA
作业一:Find Closest Centroids (k-Means)
findClosestCentroids.m
for i = 1 : size(X,1)
minError = sum((X(i,:) - centroids(1,:)).^2);
minIdx = 1;
for c = 2 : K
error = sum((X(i,:) - centroids(c,:)).^2) ;
if error < minError
minError = error;
minIdx = c;
end
idx(i) = minIdx;
end
end
作业二:Compute Centroid Means (k-Means)
computeCentroids.m
% 向量化代码
for i = 1 : K
% 找到第i个中心所包含的点的个数
s = sum(idx == i);
if (s ~= 0)
centroids(i,:) = mean( X(find(idx == i),:) );
else
centroids(i,:) = zeros(1,n);
end
end
作业三:PCA
pca.m
% 协方差矩阵
Sigma = 1 / m * X' * X;
% svd
[U,S,V] = svd(Sigma);
作业四:Project Data (PCA)
projectData.m
U_reduce = U(:, 1:K);
Z = X * U_reduce;
作业五:Recover Data (PCA)
recoverData.m
U_reduce = U(:, 1:K);
X_rec = Z * U_reduce';