Machine Learning 第七波编程作业——K-means Clustering and Principal Component Analysis
仅列出核心代码:
1.findClosestCentroids.m
m = size(X, 1);
len = zeros(K, 1);
for i = 1:m
for j = 1:K
len(j) = norm(X(i, :) - centroids(j, :))^2;
end
[~, idx(i)] = min(len);
end
2.computeCentroids.m
for k = 1:K
ind = find(idx == k);
centroids(k, :) = mean(X(ind, :));
end
3.pca.m
Sigma = X'*X/m;
[U,S,~] = svd(Sigma);
4.projectData.m
Z = X * U(:, 1:K);
5.recoverData.m
X_rec = Z * U(:, 1:K)';