-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathexample_nmf_2.m
49 lines (44 loc) · 1.52 KB
/
example_nmf_2.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
% -------------------------------------------------------------------------
% Usage examples for nonnegative matrix factorization:
% Latent factors reconstruction test
% -------------------------------------------------------------------------
m = 300;
n = 200;
k = 10;
W_org = rand(m,k);, W_org(rand(m,k)>0.5)=0;
H_org = rand(k,n);, H_org(rand(k,n)>0.5)=0;
% normalize W, since 'nmf' normalizes W before return
norm2=sqrt(sum(W_org.^2,1));
toNormalize = norm2>0;
W_org(:,toNormalize) = W_org(:,toNormalize)./repmat(norm2(toNormalize),m,1);
A = W_org * H_org;
% This example is using anls_bpp method, but try with other methods too
[W,H,iter,HIS]=nmf(A,k,'method','anls_bpp','min_iter',100,'tol',1e-5);
% -------------- column reordering before computing difference --------------
% This reording code is only for test purpose.
% Look for Hungarian method (also known as Kuhn–Munkres algorithm)
% for optimal assignments.
reorder = zeros(k,1);
selected = zeros(k,1);
for i=1:k
for j=1:k
if ~selected(j), break, end
end
minIx = j;
for j=minIx+1:k
if ~selected(j)
d1 = norm(W(:,i)-W_org(:,minIx));
d2 = norm(W(:,i)-W_org(:,j));
if (d2<d1)
minIx = j;
end
end
end
reorder(i) = minIx;
selected(minIx) = 1;
end
W_org = W_org(:,reorder);
H_org = H_org(reorder,:);
% ---------------------------------------------------------------------------
recovery_error_W = norm(W_org-W)/norm(W_org)
recovery_error_H = norm(H_org-H)/norm(H_org)