Contents

% An example of nonnegative matrix factorization

Generate problem data

rand('seed', 0); randn('seed', 0);

m = 500; n = 500; % matrix dimension
r = 30; % matrix rank
L = max(0,randn(m,r)); U = max(0,randn(r,n)); % nonnegative factors
Mtrue = L*U; % true matrix
sn = 60; % signal to noise ratio
% -- add noise --
N = max(0,randn(m,n));
M = Mtrue + 10^(-sn/20) * norm(Mtrue,'fro') * N/norm(N,'fro');

Solve problem

opts.maxit = 1000; % max # of iterations
opts.tol = 1e-4;   % stopping tolerance

t0 = tic;
[X Y out] = nmf(M,r,opts);
time = toc(t0);
Iteration:  298

Reporting

fprintf('time = %4.2e, ', time);
fprintf('solution relative error = %4.2e\n\n', norm(X*Y - Mtrue,'fro')/norm(Mtrue,'fro'));

figure;
semilogy(1:out.iter, out.hist_obj, 'k-', 'LineWidth', 2);
title('Objective')
xlabel('iteration'); ylabel('0.5 ||XY - M||_F^2');

figure;
semilogy(1:out.iter, out.relerr2, 'k-', 'LineWidth', 2);
title('Relative residual')
xlabel('iteration'); ylabel('||XY - M||_F/||M||_F');
time = 6.20e-001, solution relative error = 6.23e-004

Download this m-file