code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
function r = calc_sumprod(dim, n, a, b) % sum the corresponding products along the direction dim % % expand a or b to n rows/columns along the specified dimension % na = size(a, dim); nb = size(b, dim); if na == 1 if nb == 1 r = a .* b; if n > 1 r = r * n; end else r = a .* sum(b, dim); end else if nb == 1 r = sum(a, dim) .* b; else if dim == 1 if size(a, 2) == 1 r = a' * b; elseif size(b, 2) == 1 r = b' * a; else r = sum(a .* b, 1); end else if size(a, 1) == 1 r = b * a'; elseif size(b, 1) == 1 r = a * b'; else r = sum(a .* b, 2); end end end end
zzhangumd-smitoolbox
pmodels/gamma/private/calc_sumprod.m
MATLAB
mit
875
function X = invgammad_sample(alpha, beta, n) %invgammad_sample Samples from an inverse Gamma distribution % % X = invgammad_sample(alpha, beta); % X = invgammad_sample(alpha, beta, n); % % draws n samples from an inverse gamma distribution with shape % parameter alpha and scale parameter beta. % % Input arguments: % - alpha: can be a scalar or a d x 1 column vector. % - beta: can be a scalar or a d x 1 column vector. % - n: the number of samples to draw % % If n is omitted, it is assumed to be 1, and is d is omitted, % it is set to size(alpha, 1). % % X = invgammad_sample(alpha, beta, [d, n]); % % Additionally, specifies the dimension of the samples as d. % This syntax is particularly useful when you need to sample % from multi-dimensional gamma distributions of which both alpha % and beta parameters are scalars. % % Created by Dahua Lin, on Sep 1, 2011 % Modified by Dahua Lin, on Dec 26, 2011 %% main if nargin < 3 n = 1; end X = 1 ./ gammad_sample(alpha, 1 ./ beta, n);
zzhangumd-smitoolbox
pmodels/gamma/invgammad_sample.m
MATLAB
mit
1,095
function C = dird_cov(alpha, d) %DIRD_COV the covariance matrix of a Dirichlet distribution % % C = DIRD_COV(alpha); % C = DIRD_COV(alpha, d); % % Computes the covariance matrix of a dirichlet distribution. % Here, alpha is either a scalar, or a vector of size d x 1. % % Created by Dahua Lin, on Dec 26, 2011 % %% verify input arguments if ~( isfloat(alpha) && isreal(alpha) && ... (isscalar(alpha) || (ndims(alpha) == 2 && size(alpha, 2) == 1)) ) error('dird_cov:invalidarg', 'alpha should be a scalar or a column vector.'); end da = size(alpha, 1); if nargin < 2 d = da; else if ~(isscalar(d) && isnumeric(d)) error('dird_cov:invalidarg', 'd should be a numeric scalar.'); end if ~(da == 1 || da == d) error('dird_cov:invalidarg', 'd is inconsistent with alpha.'); end end %% main if d == 1 C = 0; return; end if da == 1 a0 = alpha * d; s = 1 ./ (a0^2 * (a0 + 1)); c1 = alpha .* (a0 - alpha) * s; c2 = - alpha^2 * s; C = constmat(d, d, c2); C(1:(d+1):d^2) = c1; else a0 = sum(alpha, 1); s = 1 ./ (a0^2 * (a0 + 1)); C = (alpha * alpha') * (-s); c1 = alpha .* (a0 - alpha) * s; C(1:(d+1):d^2) = c1; end
zzhangumd-smitoolbox
pmodels/gamma/dird_cov.m
MATLAB
mit
1,262
function W = wishartd_sample(S, df, n) % Samples from a Wishart distribution % % W = wishartd_sample(d, df); % draws a sample from a d-dimensional df-degree standard Wishart % distribution (whose scale matrix is an identity matrix). % % The result is returned in form of a d x d matrix. % % W = wishartd_sample(d, df, n); % draws n samples from a d-dimensional df-degree standard Wishart % distribution. % % The results are returned as an d x d x n array, with each page % being a sample. % % W = wishartd_sample(S, df); % W = wishartd_sample(S, df, n); % draws n samples from an df-degree Wishart distribution with % scale matrix S, which should be a pdmat struct (S.n == 1). % If n is omitted, it draws one sample % % History % ------- % - Created by Dahua Lin, on Spe 2, 2011 % %% verify input arguments if isnumeric(S) && isscalar(S) d = S; if ~(d == fix(d) && d >= 1) error('wishartd_sample:invalidarg', ... 'd should be a positive integer scalar.'); end use_S = 0; elseif is_pdmat(S) if S.n ~= 1 error('wishartd_sample:invalidarg', ... 'S should contain only one matrix.'); end d = S.d; use_S = 1; else error('wishartd_sample:invalidarg', ... 'The first argument to wishartd_sample is invalid.'); end if ~(isfloat(df) && isreal(df) && isscalar(df) && df >= d - 1) error('wishartd_sample:invalidarg', ... 'df should be a real scalar with m >= d - 1.'); end if nargin < 3 n = 1; else if ~(isnumeric(n) && isscalar(n) && n == fix(n) && n >= 0) error('wishartd_sample:invalidarg', ... 'n should be a non-negative integer scalar.'); end end %% main if d == 1 W = randg(df / 2, 1, n) * 2; if use_S W = W * S.v; end if n > 1 W = reshape(W, 1, 1, n); end else gv = 0.5 * (df - (0:d-1).'); css = randg(gv(:, ones(1,n))) * 2; if d == 2 nrms = randn(1, n); else nrms = randn(d*(d-1)/2, n); end B = wishartd_sample_cimp(css, nrms); if (~use_S) || (S.ty == 's' || S.ty == 'd') if n == 1 W = B * B'; else W = zeros(d, d, n); for i = 1 : n cB = B(:,:,i); W(:,:,i) = cB * cB'; end end if use_S if S.ty == 's' W = W * S.v; else sqv = sqrt(S.v); W = W .* (sqv * sqv'); end end else if d == 2 L = chol2x2(S.v); else L = chol(S.v, 'lower'); end if n == 1 LB = L * B; W = LB * LB'; else W = zeros(d, d, n); for i = 1 : n cLB = L * B(:,:,i); W(:,:,i) = cLB * cLB'; end end end end
zzhangumd-smitoolbox
pmodels/gamma/wishartd_sample.m
MATLAB
mit
3,032
function L = dird_logpdf(alpha, X, c) %DIRD_LOGPDF Evaluates log-pdf of Dirichlet distribution % % L = dird_logpdf(alpha, X) % L = dird_logpdf(alpha, X, 0); % L = dird_logpdf(alpha, X, c); % % Evaluates the log probability density values at given samples % with respect to given Dirichlet distribution(s). % % Input arguments: % - alpha: the parameter(s) of the Dirichlet distribution % The size of alpha can be either 1 x 1, d x 1, % 1 x m, or d x m. % % Here, d is the space dimension, and m is the % number of distributions. If m > 1, then the log % pdf values w.r.t. all distributions will be % evaluated. % % - X: the sample matrix, of size d x n. Each column of % X is a sample, which sums to 1. % % - c: The constant given by multivariate beta function, % which can be pre-computed as mvbetaln(alpha, d). % % If c is not supplied, the function invokes % mvbetaln to evaluate it. % % If c is set to zero, then only the linear terms % are computed, without adding the constant. % % Output arguments: % - L: the log pdf values. The size of L is m x n, where % L(k, i) is the log-pdf at X(:,i) with respect to % the k-th parameter in alpha. % % Created by Dahua Lin, on Dec 26, 2011 % %% verify input arguments if ~(isfloat(alpha) && isreal(alpha) && ndims(alpha) == 2) error('dird_logpdf:invalidarg', 'alpha should be a real matrix.'); end [da, m] = size(alpha); if ~(isfloat(X) && isreal(X) && ndims(X) == 2) error('dird_logpdf:invalidarg', 'X should be a real matrix.'); end d = size(X, 1); if ~(da == 1 || da == d) error('dird_logpdf:invalidarg', 'alpha and X have inconsistent dimensions.'); end if nargin >= 3 if ~( isequal(c, 0) || ... (isfloat(c) && isreal(c) && isequal(size(c), [1 m])) ) error('gammad_logpdf:invalidarg', ... 'c should be either zero or a 1 x m real vector.'); end calc_c = 0; else calc_c = 1; end %% main if da == d L = (alpha - 1)' * log(X); else L = (alpha - 1)' * sum(log(X), 1); end if calc_c c = mvbetaln(alpha, d); end if ~isequal(c, 0) if isscalar(c) L = L - c; else L = bsxfun(@minus, L, c.'); end end
zzhangumd-smitoolbox
pmodels/gamma/dird_logpdf.m
MATLAB
mit
2,567
function L = invgammad_logpdf(alpha, beta, X, c) %invgammad_logpdf Evaluate log probability density of inverse gamma distribution % % log f(x; alpha, beta) = % - (alpha + 1) * log(x) - beta / x + const % % with const = alpha * log(beta) - gammaln(alpha) % % L = invgammad_logpdf(alpha, beta, X); % L = invgammad_logpdf(alpha, beta, X, 0); % L = invgammad_logpdf(alpha, beta, X, c); % % evaluates the log probability density function of inverse gamma % distribution(s) at given samples. % % Inputs: % - alpha: the shape parameter(s) % - beta: the scale parameter(s) % - X: the sample matrix [d x n] % % - c: the constant term in the log-pdf. % % If c is not provided if will be evaluated in the % function. When this function is invoked multiple times % with the same set of distributions, it is advisable % to pre-compute it using gammad_const. % % One can also set c to 0, which means only computing % the linear part without adding the constant. % % When d > 1, this indicates a multi-dimensional inverse gamma % distribution with independent components. % % alpha and beta can respectively be either of the following: % a scalar, d x 1 vector, 1 x m vector, or d x m matrix. % When m > 1, it indicates there are multiple distributions, % the log-pdf values with respect to all distributions are evaluated % for each sample. % % The sizes of alpha and beta need not be the same, but they have % to be compatible with each other in bsxfun sense. % % Outputs: % - L: the log-pdf value matrix, of size m x n. % Particularly, L(k, i) is the log-pdf at the i-th sample % with respect to the k-th distribution. % % % % Created by Dahua Lin, on Dec 26, 2011 % %% verify input arguments if ~(isfloat(X) && isreal(X) && ndims(X) == 2) error('invgammad_logpdf:invalidarg', 'X should be a real matrix.'); end if ~(isfloat(alpha) && isreal(alpha) && ndims(alpha) == 2) error('invgammad_logpdf:invalidarg', 'alpha should be a real matrix.'); end if ~(isfloat(beta) && isreal(beta) && ndims(beta) == 2) error('invgammad_logpdf:invalidarg', 'beta should be a real matrix.'); end dx = size(X, 1); [da, ma] = size(alpha); [db, mb] = size(beta); if ~( (da == 1 || da == dx) && (db == 1 || db == dx) && ... (ma == 1 || mb == 1 || ma == mb)) error('invgammad_logpdf:invalidarg', 'The size of alpha or beta is invalid.'); end m = max(ma, mb); if nargin >= 4 if ~( isequal(c, 0) || ... (isfloat(c) && isreal(c) && isequal(size(c), [1 m])) ) error('invgammad_logpdf:invalidarg', ... 'c should be either zero or a 1 x m real vector.'); end calc_c = 0; else calc_c = 1; end %% Evaluate % first term: (alpha - 1) log(x) if da == dx T1 = (alpha + 1)' * log(X); else T1 = (alpha + 1)' * sum(log(X), 1); end % second term: x / beta if db == dx T2 = beta' * (1 ./ X); else T2 = beta' * sum(1 ./ X, 1); end % combine terms if size(T1, 1) == size(T2, 1) L = - (T1 + T2); else L = - bsxfun(@plus, T1, T2); end % add constants if calc_c c = invgammad_const(alpha, beta); if da < dx && db < dx c = c * dx; end end if ~isequal(c, 0) if m == 1 L = L + c; else L = bsxfun(@plus, L, c.'); end end
zzhangumd-smitoolbox
pmodels/gamma/invgammad_logpdf.m
MATLAB
mit
3,537
function opt = mcmc_options(opt, varargin) % Verify or set MCMC sampling options for smi_mcmc % % opt = mcmc_options(); % opt = mcmc_options([]); % returns the default MCMC sampling option struct. % % opt = mcmc_options(opt); % verify the validity of an MCMC sampling option % % opt = mcmc_options([], 'name1', val1, 'name2', val2, ...); % constructs an option struct with a series of name/value pairs. % % opt = mcmc_options(opt, 'name1', val1, 'name2', val2, ...); % updates an option struct with a series of name/value pairs % % Available options % - 'burnin': the number of iterations for burn-in % % - 'nsamples': the number of samples to acquire % % - 'ips': the number of iterations per sample % % - 'display: the level of information displaying % (can be either a string or a level number) % 0 | 'off': no display % 1 | 'final': display at the end % 2 | 'stage': display per stage % 3 | 'sample': display per sample collection % 4 | 'iter': display per iteration % % Created by Dahua Lin, on Sep 4, 2011 % %% main if nargin < 1 || isempty(opt) opt = make_default_opt(); else if ~(isstruct(opt) && isscalar(opt) && ... isfield(opt, 'tag') && isequal(opt.tag, 'mcmc_options')) error('mcmc_options:invalidarg', ... 'The input option struct is invalid.'); end end if isempty(varargin) return; end names = varargin(1:2:end); vals = varargin(2:2:end); if ~(numel(names) == numel(vals) && iscellstr(names)) error('mcmc_options:invalidarg', ... 'The name value list is invalid.'); end is_int = @(x) ... isscalar(x) && isnumeric(x) && isreal(x) && x == fix(x); for i = 1 : numel(names) cn = names{i}; lcn = lower(cn); cv = vals{i}; switch lcn case {'burnin', 'nsamples', 'ips'} if ~(is_int(cv) && cv >= 1) error('mcmc_options:invalidarg', ... 'The value of option %s must be a positive integer scalar.', lcn); end opt.(lcn) = cv; case 'display' if isnumeric(cv) if ~(is_int(cv) && cv >= 0 && cv <= 4) error('mcmc_options:invalidarg', ... 'The value of cps must be an integer in [0, 4].'); end opt.display = cv; elseif ischar(cv) switch lower(cv) case 'off' dv = 0; case 'final' dv = 1; case 'stage' dv = 2; case 'sample' dv = 3; case 'iter' dv = 4; otherwise error('mcmc_options:invalidarg', ... 'Invalid display level name ''%s''.', cv); end opt.display = dv; else error('mcmc_options:invalidarg', ... 'The value for display option is invalid.'); end otherwise error('mcmc_options:invalidarg', ... 'Unknown option name %s', cn); end end function opt = make_default_opt() opt.tag = 'mcmc_options'; opt.burnin = 500; opt.nsamples = 100; opt.ips = 50; opt.nrepeats = 1; opt.display = 0;
zzhangumd-smitoolbox
pmodels/common/mcmc_options.m
MATLAB
mit
3,713
function r = randpick(n, k) %RANDPICK Random sample without replacement % % r = RANDPICK(n, k); % % randomly pick k distinct numbers from 1:n. In the output, r is % a vector of size 1 x k. (Note that it should have k <= n). % Note that r is sorted. % % History % ------- % - Created by Dahua Lin, on Sep 27, 2010 % - Modified by Dahua Lin, on Aug 10, 2011 % - using an more efficient suffling algorithm % - Modified by Dahua Lin, on Jan 30, 2012 % %% verify input if ~(isscalar(n) && n == fix(n) && n > 0) error('randpick:invalidarg', 'n should be a positive scalar integer.'); end if ~(isscalar(k) && k == fix(k) && k > 0 && k <= n) error('randpick:invalidarg', ... 'k should be a positive scalar integer in [1, n].'); end %% main if k == 1 r = randi(n); else n = int32(n); k = int32(k); use_shuffle = (n < k*200); r = randpick_cimp(n, k, use_shuffle); end
zzhangumd-smitoolbox
pmodels/common/randpick.m
MATLAB
mit
996
function R = mcmc_drive(S, opts) %MCMC_DRIVE Drive the running of an MCMC procedure. % % R = MCMC_DRIVE(S, opts); % % Drives a MCMC sampling procedure and collects samples. % % Input arguments: % - S0: The SMI state (an instance of class smi_state) that % has been initialized. % % - opts: The MCMC control options, which can be obtained by % calling mcmc_options. % (See the help of mcmc_options for details). % % Output arguments: % - R: A cell array of samples (each sample % results from calling the output method of the state). % % Remarks % ------- % - If opts.nrepeats > 0, multiple independent Markov chains % will be spawned, running in an parallel way (using parfor). % A proper setting of matlabpool would help to enhance the % parallel efficiency. % % History % ------- % - Created by Dahua Lin, on Sep 4, 2011 % %% verify input arguments if ~isa(S, 'smi_state') error('mcmc_drive:invalidarg', 'S should be an smi_state object.'); end if ~S.is_ready() error('varinfer_drive:invalidarg', 'S has not been ready.'); end opts = mcmc_options(opts); %% main displevel = opts.display; % burn in if displevel >= 2 fprintf('Burning in ...\n'); end for t = 1 : opts.burnin if displevel >= 4 fprintf(' burn-in iter %d/%d\n', t, opts.burnin); end S = update(S); end % main iterations if displevel >= 2 fprintf('Collecting samples ...\n'); end nsamples = opts.nsamples; R = cell(1, nsamples); ips = opts.ips; for i = 1 : nsamples if ips == 1 S = update(S); else for t = 1 : ips if displevel >= 4 fprintf(' sample[%d] iter %d/%d\n', i, t, ips); end S = update(S); end end R{i} = output(S); if displevel >= 3 fprintf(' %d/%d samples collected.\n', i, nsamples); end end
zzhangumd-smitoolbox
pmodels/common/mcmc_drive.m
MATLAB
mit
2,037
function mv = vecmean(X, w) %VECMEAN Mean(s) of vectors % % mv = VECMEAN(X); % Computes the mean vector of the column vectors in X. % % The mean vector of vectors v1, v2, ..., vn is defined as % % mv = (v1 + v2 + ... + vn) / n; % % Let X be a d x n matrix, with each column representing a % d-dimensional sample. Then mv is a d x 1 column vector, % which is their mean vector. % % mv = VECMEAN(X, w); % Computes the weighted mean vector of the columns in X. % % The weighted mean vector is defined as % % mv = sum_i w(i) * vi / (sum_i w(i)) % % Let X be a d x n matrix, then w can be a n x 1 column vector, % in which, w(i) is the weight of the i-th sample in X. % % w can also be a n x k matrix, with each column giving a set % of weights. In this case, the output mv will be a d x k % matrix, with mv(:, i) being the weighted mean vector % computed based on the weights in w(i, :). % % History % - Created by Dahua Lin, on Jun 4, 2008 % - Modified by Dahua Lin, on April 13, 2010 % %% parse and verify input arguments if ~(isfloat(X) && ndims(X) == 2) error('vecmean:invalidarg', ... 'X should be a numeric matrix with floating point value type.'); end n = size(X, 2); if nargin < 2 || isempty(w) weighted = false; else if ~(isnumeric(w) && ndims(w) == 2 && size(w,1) == n) error('vecmean:invalidarg', ... 'w should be a matrix with n rows.'); end weighted = true; end %% main if ~weighted mv = sum(X, 2) * (1/n); else if size(w, 1) == 1 mv = X * (w / sum(w)); else mv = X * bsxfun(@times, w, 1 ./ sum(w, 1)); end end
zzhangumd-smitoolbox
pmodels/common/vecmean.m
MATLAB
mit
1,810
function opt = varinfer_options(opt, varargin) % Verify or set variational inference control options for smi_varinfer % % opt = varinfer_options(); % opt = varinfer_options([]); % returns the default variational inference option struct. % % opt = varinfer_options(opt); % verify the validity of an variational inference option % % opt = varinfer_options([], 'name1', val1, 'name2', val2, ...); % constructs an option struct with a series of name/value pairs. % % opt = varinfer_options(opt, 'name1', val1, 'name2', val2, ...); % updates an option struct with a series of name/value pairs % % Available options % - 'maxiters': the maximum number of iterations % % - 'ipe': the number of iterations between two % evaluations of the objective value. % % - 'tol': the tolerance of objective change between % current and last objective values on % convergence. % % - 'display: the level of information displaying % (can be either a string or a level number) % 0 | 'off': no display % 1 | 'final': display at the end % 2 | 'stage': display per stage % 3 | 'eval': display per objective evaluation % 4 | 'iter': display per iteration % % Created by Dahua Lin, on Sep 4, 2011 % %% main if nargin < 1 || isempty(opt) opt = make_default_opt(); else if ~(isstruct(opt) && isscalar(opt) && ... isfield(opt, 'tag') && isequal(opt.tag, 'varinfer_options')) error('varinfer_options:invalidarg', ... 'The input option struct is invalid.'); end end if isempty(varargin) return; end names = varargin(1:2:end); vals = varargin(2:2:end); if ~(numel(names) == numel(vals) && iscellstr(names)) error('varinfer_options:invalidarg', ... 'The name value list is invalid.'); end is_int = @(x) ... isscalar(x) && isnumeric(x) && isreal(x) && x == fix(x); for i = 1 : numel(names) cn = names{i}; lcn = lower(cn); cv = vals{i}; switch lcn case {'maxiters', 'ipe'} if ~(is_int(cv) && cv >= 1) error('varinfer_options:invalidarg', ... 'The value of option %s must be a positive integer scalar.', lcn); end opt.(lcn) = cv; case 'tol' if ~(isfloat(cv) && isscalar(cv) && cv >= 0) error('varinfer_options:invalidarg', ... 'The value of option tol must be a non-negative real number.'); end opt.tol = cv; case 'display' if isnumeric(cv) if ~(is_int(cv) && cv >= 0 && cv <= 4) error('varinfer_options:invalidarg', ... 'The value of cps must be an integer in [0, 4].'); end opt.display = cv; elseif ischar(cv) switch lower(cv) case 'off' dv = 0; case 'final' dv = 1; case 'stage' dv = 2; case 'eval' dv = 3; case 'iter' dv = 4; otherwise error('varinfer_options:invalidarg', ... 'Invalid display level name ''%s''.', cv); end opt.display = dv; else error('varinfer_options:invalidarg', ... 'The value for display option is invalid.'); end otherwise error('varinfer_options:invalidarg', ... 'Unknown option name %s', cn); end end function opt = make_default_opt() opt.tag = 'varinfer_options'; opt.maxiters = 200; opt.ipe = 1; opt.tol = 1e-6; opt.display = 0;
zzhangumd-smitoolbox
pmodels/common/varinfer_options.m
MATLAB
mit
4,197
function [V, mv] = vecvar(X, w, mv) %VECVAR Variances of vector components % % V = VECVAR(X); % computes the variances of the components of vectors in X. % % The variance of values v1, v2, ..., vn is defined as % % (sum_i (v_i - mv)^2) / n % % here, mv is the mean value. % % Given a matrix X of size d x n, with each column representing a % d-dimensional vector, then V will be a d x 1 vector, in which % V(i) is the variance of the values in the i-th row of X. % % V = VECVAR(X, w); % computes the weighted variances of the components of vectors in X. % % The weighted variance is computed as follows % % (sum_i w(i) * (vi - mv)^2) / (sum_i w(i)) % % here w(i) is the weight for the i-th value. % % Given a matrix X of size d x n, the weights can be input by a % vector w of size n x 1, with w(i) being the weight for the i-th % sample. % % w can also be an n x k matrix, offering multiple sets of different % weights. Then, in the output, V will be a d x k matrix, with V(:,i) % giving the variances based on the weights in w(i, :). % % V = VECVAR(X, [], mv); % computes the weighted variance with pre-computed mean vector. % % The pre-computed mean vector is given by mv, which should be a % d x 1 column vector. % % V = VECVAR(X, w, mv); % computes the weighted variances with pre-computed mean vector. % % Then w is a n x 1 column vector, mv should be a d x 1 column vector % giving the weighted mean vector based on that weights. % % If w is an n x k matrix offering multiple sets of weights, then % mv should be a d x k column vector, with mv(:, i) being the % mean vector based on the weights given in w(:, i). % % [V, mv] = VECVAR( ... ); % additionally returns the mean vector as the 2nd output argument. % % Remarks % - The implementation is based on the following identity rather than % the original definition: % % Var(x) = E(x^2) - (E x)^2 % % This implementation is typically more efficient, especially when % d < n, which is often the case in the context of statistics. % % History % - Created by Dahua Lin, on Jun 5, 2008 % - Modified by Dahua Lin, on Mar 20, 2010 % - returns mean vector as the second output argument % - Modified by Dahua Lin, on April 13, 2010 % %% parse and verify input arguments if ~(isfloat(X) && ndims(X) == 2) error('vecvar:invalidarg', ... 'X should be a numeric matrix with floating-point value type.'); end [d, n] = size(X); if nargin < 2 || isempty(w) weighted = false; k = 1; else if ~(isnumeric(w) && ndims(w) == 2 && size(w,1) == n) error('vecvar:invalidarg', ... 'w should be a matrix with n columns.'); end k = size(w, 2); weighted = true; end if nargin < 3 mv = []; else if k == 1 if ~(isnumeric(mv) && ndims(mv) == 2 && ... size(mv,1) == d && size(mv,2) == 1) error('vecvar:invalidarg', ... 'mv should be a d x 1 vector.'); end else if ~(isnumeric(mv) && ndims(mv) == 2 && ... size(mv,1) == d && size(mv,2) == k) error('vecvar:invalidarg', ... 'mv should be a d x k matrix.'); end end end %% main % normalize the weights if weighted if k == 1 w = w / sum(w); else w = bsxfun(@times, w, 1 ./ sum(w, 1)); end end % compute E(x) if isempty(mv) if ~weighted mv = sum(X, 2) / n; else mv = X * w; end end % compute E(x^2) if ~weighted Ex2 = sum(X .* X, 2) / n; else Ex2 = (X .* X) * w; end % result V = Ex2 - mv .* mv;
zzhangumd-smitoolbox
pmodels/common/vecvar.m
MATLAB
mit
3,811
classdef genmodel_base % The base of the classes that implement simple generative model % % This is an abstract class that defines the functions to be % implemented by derived classes. % methods(Abstract) n = query_obs(obj, X); % Verify the observations and return the number of observations n = query_params(obj, A); % Verify the parameters and return the number of parameters L = loglik(obj, A, X); % Evaluate the log-likelihood of all samples w.r.t all params A = mle(obj, X, W, I); % Performs maximum likelihood estimation of parameters % % W: empty or a matrix of size n x K % S = capture(obj, X, W, I); % Captures the sufficient stats of observations as updates to prior end end
zzhangumd-smitoolbox
pmodels/common/genmodel_base.m
MATLAB
mit
910
function [C, mv] = veccov(X, w, mv) %VECCOV Computes the covariance matrix of vectors % % C = veccov(X); % computes the covariance matrix of column vectors in X. % % The function computes the sample covariance matrix for sample % vectors v1, v2, ..., vn, as % % C = sum_i (vi - mv) * (vi - mv)' / n % % where, mv is the mean vector. % % Let X be a d x n matrix with each column representing a sample. % Then C will the covariance matrix, whose size is d x d. % % C = veccov(X, w); % compute the covariance matrix based on weighted samples. % % The weighted covariance matrix is computed as % % C = sum_i w(i) * (vi - mv) * (vi - mv)' / (sum_i w(i)) % % where, mv is the weighted mean vector. % % Let X be a d x n matrix, then w can be an n x 1 col-vector, with % w(i) gives the weight of the sample X(:, i). % % w can also be a n x k matrix, with each col in w giving a set of % weights. Then k covariance matrices will be computed, ans thus % in the output, C is a d x d x k array, with C(:,:,i) being the % covariance matrix computed based on the weights in w(i, :). % % C = veccov(X, [], mv); % compute the covariance matrix, with a pre-computed mean vector % given by mv. Typically, mv should be a d x 1 vector in a % d-dimensional space. % % C = veccov(X, w, mv); % compute the covariance matrix(matrices) using pre-computed % mean vector(s). % % When w is an n x k matrix, mv should be given as a d x k matrix, % with mv(:, i) corresponding to the weighted mean vector based on % the weights in w(:, i). % % [C, mv] = veccov( ... ); % additionally returns the mean vector as the 2nd ouptut argument. % % Remarks % - Rather than using the original definition given above, the % function implements the computation based on the following % identity: % Cov(X) = E(X * X') - E(X) * E(X)'; % % This implementation is more efficient, especially when d < n. % % History % - Created by Dahua Lin, on Jun 4, 2008 % - Modified by Dahua Lin, on Mar 20, 2010 % - returns mean vector as the second output argument % - Modified by Dahua Lin, on April 13, 2010 % %% parse and verify input arguments if ~(isfloat(X) && ndims(X) == 2) error('veccov:invalidarg', ... 'X should be a numeric matrix with floating-point value type.'); end [d, n] = size(X); if nargin < 2 || isempty(w) weighted = false; k = 1; else if ~(isnumeric(w) && ndims(w) == 2 && size(w,1) == n) error('veccov:invalidarg', ... 'w should be a matrix with n columns.'); end k = size(w, 2); weighted = true; end if nargin < 3 mv = []; else if k == 1 if ~(isnumeric(mv) && ndims(mv) == 2 && ... size(mv,1) == d && size(mv,2) == 1) error('veccov:invalidarg', ... 'mv should be a d x 1 vector.'); end else if ~(isnumeric(mv) && ndims(mv) == 2 && ... size(mv,1) == d && size(mv,2) == k) error('veccov:invalidarg', ... 'mv should be a d x k matrix.'); end end end %% main % normalize the weights if weighted if k == 1 w = w / sum(w); else w = bsxfun(@times, w, 1 ./ sum(w, 1)); end end % compute mean vector(s) if isempty(mv) if ~weighted mv = sum(X, 2) / n; else mv = X * w; end end % compute covariance if ~weighted C = X * X' * (1/n); if ~all(mv == 0) C = C - mv * mv'; end C = 0.5 * (C + C'); else if k == 1 C = X * bsxfun(@times, X', w); if ~all(mv == 0) C = C - mv * mv'; end C = 0.5 * (C + C'); else C = zeros(d, d, k, class(X)); for i = 1 : k cw = w(:, i); cmv = mv(:, i); cc = X * bsxfun(@times, X', cw) - cmv * cmv'; C(:,:,i) = 0.5 * (cc + cc'); end end end
zzhangumd-smitoolbox
pmodels/common/veccov.m
MATLAB
mit
4,372
function R = varinfer_drive(S, opts) % Drive a MCMC sampling procedure based on an SMI program % % R = varinfer_drive(S, opts); % % Drives a variational inference procedure and collects samples. % % Input arguments: % - S: the SMI state that has been properly initialized. % % - opts: the inference control options, which can be obtained % by calling varinfer_options. % (See the help of varinfer_options for details). % % Output arguments: % - R: a struct with following fields: % - 'sol': the obtained solution (this is the % result returned by invoking make_output % method on the states of final iteration) % % - 'state': the updated state object % % - 'niters': the number of elapsed iterations % % - 'converged': whether the procedure converges % % - 'objv': the vector of recorded objective values. % objv(end) is the final objective. % % - 'eiters': the indices of iterations at which the % objectives are evaluated. Specifically, % objv(i) is evaluated at iteration eiters(i). % % History % ------- % - Created by Dahua Lin, on Sep 4, 2011 % - Modified by Dahua Lin, on Dec 27, 2011 % %% verify input arguments if ~isa(S, 'smi_state') error('varinfer_drive:invalidarg', 'S should be an smi_state object.'); end if ~S.is_ready() error('varinfer_drive:invalidarg', 'S has not been ready.'); end opts = varinfer_options(opts); %% main displevel = opts.display; % main iterations if displevel >= 2 fprintf('Variational inference updating ...\n'); end converged = false; it = 0; maxiters = opts.maxiters; ipe = opts.ipe; ne = 0; max_ne = ceil(maxiters / ipe); objv = zeros(1, max_ne); eiters = zeros(1, max_ne); while ~converged && it < maxiters % do update if ipe == 1 it = it + 1; if displevel >= 4 fprintf(' iter %d\n', it); end S = update(S); else it_first = it + 1; it_last = min(it + ipe, maxiters); for it = it_first : it_last if displevel >= 4 fprintf(' iter %d\n', it); end S = update(S); end end % evaluate objective & determine convergence cobjv = S.evaluate_objv(); ne = ne + 1; eiters(ne) = it; objv(ne) = cobjv; if ne == 1 ch = nan; else ch = objv(ne) - objv(ne-1); converged = (abs(ch) <= opts.tol); end if displevel >= 3 fprintf(' eval (@ iter %d): objv = %.4g (ch = %g)\n', ... it, cobjv, ch); end end if displevel >= 1 if converged fprintf('Variational inference converged (#iters = %d)\n', it); else fprintf('Variational inference did NOT converge (#iters = %d)\n', it); end end % make output struct R.sol = S.output(); R.state = S; R.niters = it; R.converged = converged; R.objv = objv(1:ne); R.eiters = eiters(1:ne);
zzhangumd-smitoolbox
pmodels/common/varinfer_drive.m
MATLAB
mit
3,297
classdef prior_base % The base class of prior distributions % % Created by Dahua Lin, on Dec 27, 2011 % methods(Abstract) n = query_samples(obj, X); % Verify the validity of input samples and return the number L = logpdf(obj, X); % Evaluate the log pdf at given samples X = sample(obj, n); % Samples from the prior distribution X = pos_sample(obj, S, n); % Draw from posterior distribution with the stats of observations X = mapest(obj, S); % Performs MAP estimation with the stats of observations end end
zzhangumd-smitoolbox
pmodels/common/prior_base.m
MATLAB
mit
683
/******************************************************************** * * C++ mex implementation of core algorithm of randpick * * Created by Dahua Lin, on Aug 10, 2011 * *******************************************************************/ #include <bcslib/matlab/bcs_mex.h> #include <set> #include <cmath> using namespace bcs; using namespace bcs::matlab; mxArray *call_rand(int n, int len) { mxArray *x = 0; mxArray *prhs[2]; prhs[0] = mxCreateDoubleScalar(1); prhs[1] = mxCreateDoubleScalar(len); mexCallMATLAB(1, &x, 2, prhs, "rand"); mxDestroyArray(prhs[0]); mxDestroyArray(prhs[1]); return x; } mxArray *call_randi(int n, int len) { mxArray *x = 0; mxArray *prhs[3]; prhs[0] = mxCreateDoubleScalar(n); prhs[1] = mxCreateDoubleScalar(1); prhs[2] = mxCreateDoubleScalar(len); mexCallMATLAB(1, &x, 3, prhs, "randi"); mxDestroyArray(prhs[0]); mxDestroyArray(prhs[1]); mxDestroyArray(prhs[2]); return x; } void randpick_by_rejection_sampling(int n, int k, double *r) { std::set<int> s; int len = k + (k / 2); int remain = k; int it = k; while(remain > 0 && it > 0) { mxArray *mxX = call_randi(n, len); const double *x = mxGetPr(mxX); for(int i = 0; i < len; ++i) { int v = (int)x[i]; if (s.find(v) == s.end()) // not in set { s.insert(v); *(r++) = v; if (--remain == 0) break; } } -- it; mxDestroyArray(mxX); } } void randpick_by_random_suffling(int n, int k, double *r) { // initialize mxArray *mxX = call_rand(n, k); const double *x = mxGetPr(mxX); int *s = new int[n]; for (int i = 0; i < n; ++i) s[i] = i; for (int i = 0; i < k; ++i) { // pick int j = i + std::floor(x[i] * (n - i)); // swap if (i != j) { int t = s[i]; s[i] = s[j]; s[j] = t; } } // copy for (int i = 0; i < k; ++i) { r[i] = (double)(s[i] + 1); } delete[] s; mxDestroyArray(mxX); } /** * main entry: * * Input * [0]: n: the total number of population (double) * [1]: k: the number of samples to pick (double) * [2]: b: whether to use shuffle * * Ouput * [0]: r: the resultant sample vector (k x 1) */ void bcsmex_main(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { const_marray mN(prhs[0]); const_marray mK(prhs[1]); const_marray mB(prhs[2]); int n = mN.get_scalar<int32_t>(); int k = mK.get_scalar<int32_t>(); bool b = mB.get_scalar<bool>(); marray mR = create_marray<double>(1, (size_t)k); double *r = mR.data<double>(); if (b) { randpick_by_random_suffling(n, k, r); } else { randpick_by_rejection_sampling(n, k, r); } plhs[0] = mR.mx_ptr(); } BCSMEX_MAINDEF
zzhangumd-smitoolbox
pmodels/common/private/randpick_cimp.cpp
C++
mit
3,201
function P = binoprobs(n, p) % Compute probability of binomial distribution % % P = binoprobs(n, p); % Compute the probability mass function of binomial distribution. % In the input, n is a positive integer representing the total % number of trials, p is the probability of success of each trial. % % Then in the output, P is a row vector of size 1 x (n+1), where % P(i) is the probability of having i - 1 successes in n trials. % % p can also be a vector with m elements that give different % probabilities of success. In this case, P is a matrix of size % m x (n+1), where P(k, :) corresponds to the probabilities derived % with success rate p(k). % % Created by Dahua Lin, on Apr 16, 2010 % %% verify input arguments if ~(isfloat(n) && isscalar(n) && n == fix(n) && n >= 1) error('binoprobs:invalidarg', ... 'n should be a positive integer scalar.'); end if ~(isfloat(p) && isreal(p) && isvector(p)) error('binoprobs:invalidarg', ... 'p should be a real vector.'); end if size(p, 2) > 1 p = p.'; end m = numel(p); %% main fv = [1 cumprod(1:n)]; % the list of values of factorials k = 0 : n; fn = fv(n+1); if m == 1 a = (p .^ k) ./ fv; b = ((1 - p) .^ (n - k)) ./ fv(end:-1:1); P = fn * (a .* b); else A = bsxfun(@times, bsxfun(@power, p, k), 1 ./ fv); B = bsxfun(@times, bsxfun(@power, 1-p, n-k), 1 ./ fv(end:-1:1)); P = fn * (A .* B); end
zzhangumd-smitoolbox
pmodels/common/binoprobs.m
MATLAB
mit
1,468
function R = rand_label(K, n, op) % Generates random labeling % % R = rand_label(K, n); % R = rand_label(K, n, 'v'); % % Generates a 1 x n row vector, with each element being a % random integer in [1, K]. % % R = rand_label(K, n, 'b'); % % Generates a K x n matrix, with each column being a random % indicator vector (a vector with a random entry set to one, % and others set to zeros). % % R = rand_label(K, n, 'p'); % % Generates a K x n random matrix, such that each column has % a unit sum. % % Created by Dahua Lin, on Sep 4, 2011 % %% verify input if ~(isnumeric(K) && isscalar(K) && K == fix(K) && K >= 1) error('rand_label:invalidarg', ... 'K should be a positive integer scalar.'); end if ~(isnumeric(n) && isscalar(n) && n == fix(n) && n >= 0) error('rand_label:invalidarg', ... 'n should be a non-negative integer scalar.'); end if nargin < 3 op = 'v'; else if ~(ischar(op) && isscalar(op)) error('rand_label:invalidarg', ... 'The 3rd argument should be a char.'); end op = lower(op); end %% main if op == 'v' R = randi(K, 1, n); elseif op == 'b' L = randi(K, 1, n); R = l2mat(K, L); elseif op == 'p' R = rand(K, n); R = bsxfun(@times, R, 1 ./ sum(R, 1)); else error('rand_label:invalidarg', 'The 3rd argument is invalid.'); end
zzhangumd-smitoolbox
pmodels/common/rand_label.m
MATLAB
mit
1,409
function R = vscatter(X, U, W, op) % Compute the scatter vector/matrix % % R = vscatter(X, U, W, 'v'); % computes the scatter vector defined as follows. % % Suppose X is a d x n matrix, U is a d x K matrix, then % R is a d x K matrix defined by % % R(i, k) = sum_j W(k, j) * (X(i, j) - U(i, k))^2. % % Here, W is a K x n matrix. If all weights are equal, the input % W can be a scalar. % % R = vscatter(X, U, W, 'c'); % computes the scatter matrix defined as follows. % % Suppose X is a d x n matrix, U is a d x K matrix, then % R is a d x d x K array, defined by % % R(i,i',k) = sum_j W(k,j) * (X(i,j) - U(i,k)) * (X(i',j) - U(i',k)) % % Here, W is a K x n matrix. If all weights are equal, the input % W can be a scalar. % % Note, U can be input as simply a zero (0), when all its entries are 0. % % Created by Dahua Lin, on Sep 28, 2011 % %% verify inputs if ~(isfloat(X) && isreal(X) && ndims(X) == 2) error('vscatter:invalidarg', 'X should be a real matrix.'); end if ~(isfloat(U) && isreal(U) && ndims(U) == 2) error('vscatter:invalidarg', 'U should be a real matrix.'); end [d, n] = size(X); if isequal(U, 0) z_u = true; K = 1; else z_u = false; [d2, K] = size(U); if d ~= d2 error('vscatter:invalidarg', 'The dimensions of X and U are inconsistent.'); end end if ~(isfloat(W) && isreal(W) && (isscalar(W) || isequal(size(W), [K n]))) error('vscatter:invalidarg', ... 'W should be either a scalar or a matrix of size K x n.'); end if ~(ischar(op) && isscalar(op) && (op == 'v' || op == 'c')) error('vscatter:invalidarg', ... 'The 4th argument should be either ''v'' or ''c''.'); end %% main if K == 1 if z_u Y = X; else Y = bsxfun(@minus, X, U); end if op == 'v' if isscalar(W) R = sum(Y .^ 2, 2); if W ~= 1 R = R * W; end else R = (Y .^ 2) * W'; end else % op == 'c' if isscalar(W) R = Y * Y'; if W ~= 1 R = R * W; end else R = Y * bsxfun(@times, Y, W)'; R = 0.5 * (R + R'); end end else % K > 1 if op == 'v' if isscalar(W) T1 = sum(X.^2, 2); T2 = bsxfun(@times, sum(X,2), U); T3 = n * (U.^2); R = bsxfun(@plus, T1, T3 - 2 * T2); if W ~= 1 R = R * W; end else T1 = (X.^2) * W'; T2 = (X * W') .* U; T3 = bsxfun(@times, sum(W, 2)', U.^2); R = T1 - 2 * T2 + T3; end else % op == 'c' R = zeros(d, d, K); if isscalar(W) for k = 1 : K Y = bsxfun(@minus, X, U(:,k)); C = (Y * Y') * W; R(:,:,k) = C; end else for k = 1 : K Y = bsxfun(@minus, X, U(:,k)); C = Y * bsxfun(@times, Y, W(k,:))'; R(:,:,k) = 0.5 * (C + C'); end end end end
zzhangumd-smitoolbox
pmodels/common/vscatter.m
MATLAB
mit
3,310
classdef smi_state %SMI_STATE the base class of the run-time state of an iterative program % % Created by Dahua Lin, on Dec 26, 2011 % methods(Abstract) obj = initialize(obj, varargin); % Initialize the state obj = update(obj); % Update current state R = output(obj); % Make the output from the current state b = is_ready(obj); % Whether the object is properly initialized end end
zzhangumd-smitoolbox
pmodels/common/smi_state.m
MATLAB
mit
525
function s = dpmm_merge_samples(M, obs, H, ss, varargin) %DPMM_MERGE_SAMPLES Merges multiple samples from the same chain into one % % s = dpmm_merge_samples(M, obs, H, ss, ...); % % merges multiple DPMM samples drawn from a MCMC chain (those % produced by the method make_output of dpmm class) into a single % sample by voting. % % Input arguments: % - M: the DPMM model % % - H: the struct of inheritance (empty if no inheritance) % % - ss: the sequence of samples % % One can customize the following options via name/value pairs. % % - rthres: the threshold of ratio. If the count of an % atom takes a ratio less than rthres, the atom % will be discarded, and the corresponding % observations will be assigned the labels of % the most fitted atom in the remaining set. % (default = 0); % % - redraw_iters: the number of iterations to redraw an atom. % (default = 1). % % % Created by Dahua Lin, on Sep 26, 2011. % %% verify input arguments if ~isa(M, 'dpmm') error('dpmm_merge_samples:invalidarg', ... 'M should be an instance of the class dpmm.'); end amdl = M.amodel; basedist = M.basedist; n = amdl.get_num_observations(obs); if ~isstruct(ss) && isvector(ss) error('dpmm_merge_samples:invalidarg', 'ss should be a struct vector.'); end if ~isempty(H) if ~(isstruct(H) && isfield(H, 'tag') && strcmp(H.tag, 'dpmm_inherits')) error('dpmm_merge_samples:invalidarg', ... 'H should be either empty or a dpmm_inherits struct.'); end Kp = H.num; else Kp = 0; end rthres = 0; redraw_iters = 1; if ~isempty(varargin) onames = varargin(1:2:end); ovals = varargin(2:2:end); if ~(numel(onames) == numel(ovals) && iscellstr(onames)) error('dpmm_merge_samples:invalidarg', 'Invalid option list.'); end for i = 1 : numel(onames) cn = onames{i}; cv = ovals{i}; switch cn case 'rthres' if ~(isfloat(cv) && isreal(cv) && isscalar(cv) && cv >= 0 && cv < 1) error('dpmm_merge_samples:invalidarg', ... 'rthres should be a real value in [0, 1).'); end rthres = cv; case 'redraw_iters' if ~(isnumeric(cv) && isscalar(cv) && cv == fix(cv) && cv >= 1) error('dpmm_merge_samples:invalidarg', ... 'redraw_iters should be a positive integer scalar.'); end redraw_iters = cv; end end end %% main % get maximum atom id max_aid = max([ss.max_atom_id]); % voting all_labels = vertcat(ss.labels); labels = mode(all_labels, 1); [atom_ids, counts, grps, z] = uniqvalues(labels, 'CGI'); K = numel(atom_ids); % discard unlabeled = []; if rthres > 0 cthres = rthres * n; if any(counts < cthres) di = find(counts < cthres); if numel(di) == K error('dpmm_merge_samples:rterror', ... 'No atom can be retained after thresholding.'); end unlabeled = [grps{di}]; atom_ids(di) = []; counts(di) = []; %#ok<NASGU> grps(di) = []; zmap = zeros(1, K); ri = setdiff(1:K, di); zmap(ri) = 1 : numel(ri); K = numel(ri); z = zmap(z); end end % re-draw atoms atoms = cell(1, K); auxes = cell(1, K); if Kp == 0 for k = 1 : K [atoms{k}, auxes{k}] = redraw_atom(amdl, basedist, obs, grps{k}, redraw_iters); end else [is_inherit, pids] = ismember(atom_ids, H.atom_ids); for k = 1 : K if is_inherit(k) pri_k = H.atoms{pids(k)}; else pri_k = basedist; end [atoms{k}, auxes{k}] = redraw_atom(amdl, pri_k, obs, grps{k}, redraw_iters); end end % relabel observations whose atoms were discarded if ~isempty(unlabeled) assert(all(z(unlabeled) == 0)); L = zeros(K, numel(unlabeled)); for k = 1 : K llik = amdl.evaluate_logliks(atoms{k}, obs, auxes{k}, unlabeled); L(k, :) = llik; end [~, zu] = max(L, [], 1); z(unlabeled) = zu; end % make output s.natoms = K; s.max_atom_id = max_aid; s.atom_ids = atom_ids; s.atoms = atoms; s.atom_counts = intcount(K, z); s.iatoms = z; s.labels = s.atom_ids(z); %% Subfunctions function [a,aux] = redraw_atom(amdl, pridist, obs, g, niters) aux = []; for t = 1 : niters [a, aux] = amdl.posterior_params(pridist, obs, aux, g, 'atom'); end
zzhangumd-smitoolbox
pmodels/dp/dpmm_merge_samples.m
MATLAB
mit
4,819
classdef dpmm_sol % The class that captures a DPMM solution % % Created by Dahua Lin, on Sep 26, 2011 % %% properties properties(GetAccess='public', SetAccess='private') nobs; % the number of observations iatoms; % the vector of the atom-indices associated with the observations groups; % the cell array of grouped obs indices based on labels end properties(GetAccess='private', SetAccess='private') asys; % an internal struct maintaining a set of atoms end properties(Dependent) natoms; % the number of atoms (K) max_atom_id; % the maximum identifier of the atoms capacity; % the maximum #atoms that can be accomodated without growing atom_ids; % the vector of atom identifiers (1 x K) atoms; % the cell array of atoms (1 x K) auxes; % the cell array of auxiliary structs (1 x K) priweights; % the vector of prior weights (1 x K) atom_counts; % the current counts of atoms (1 x K) logliks; % the matrix of log-likelihood values (K x n) base_logliks; % the vector of log-lik values w.r.t. the base labels; % the vector of labels (ids of atoms associated with obs) end methods function v = get.natoms(sol) v = sol.asys.natoms; end function v = get.max_atom_id(sol) v = sol.asys.max_aid; end function v = get.capacity(sol) v = sol.asys.capacity; end function v = get.atom_ids(sol) v = sol.asys.atom_ids(1:sol.natoms); end function v = get.atoms(sol) v = sol.asys.atoms(1:sol.natoms); end function v = get.priweights(sol) v = sol.asys.priweights(1:sol.natoms); end function v = get.atom_counts(sol) v = sol.asys.counts(1:sol.natoms); end function v = get.logliks(sol) v = sol.asys.logliks(1:sol.natoms, :); end function v = get.base_logliks(sol) v = sol.asys.logliks0; end function v = get.labels(sol) I = sol.iatoms; n = sol.nobs; v = zeros(1, n); v(I > 0) = sol.atom_ids(I(I > 0)); end end %% Construction methods function sol = dpmm_sol(amdl, basedist, obs, base_id, r0) % Constructs an empty DPMM solution % % sol = dpmm_sol(amdl, basedist, obs); % sol = dpmm_sol(amdl, basedist, obs, base_id); % sol = dpmm_sol(amdl, basedist, obs, base_id, r0); % % Constructs an empty DPMM solution. % % amdl is the underlying atom model % % basedist is the base distribution % % obs is the observation set % % base_id is the base from which the atom id is % incremented. default = 0. % % If r0 is specified, the solution has an initial % capacity that is enough to host at least r0 atoms. % if ~isa(amdl, 'genmodel_base') error('dpmm_sol:invalidarg', ... 'amdl should be an instance of a class derived from genmodel_base.'); end n = amdl.get_num_observations(obs); if nargin >= 4 if ~(isnumeric(base_id) && isscalar(base_id) && ... base_id >= 0 && base_id == fix(base_id)) error('dpmm_sol:invalidarg', ... 'max_id should be a non-negative integer scalar.'); end else base_id = 0; end if nargin >= 5 if ~(isnumeric(r0) && isscalar(r0) && r0 >= 0 && r0 == fix(r0)) error('dpmm_sol:invalidarg', ... 'r0 should be a non-negative integer scalar.'); end c0 = 2^(ceil(log2(r0))); else c0 = 8; end sol.nobs = n; sol.iatoms = zeros(1, n); sol.groups = []; llik0 = amdl.evaluate_logliks(basedist, obs); sol.asys = dpmm_sol.init_atomsys(c0, n, base_id, llik0); end end %% Methods for updating methods function sol = update_atoms(sol, amdl, basedist, obs, H, ainds) % Updating atoms based on grouped observations % % sol = sol.update_atoms(amdl, basedist, obs); % sol = sol.update_atoms(amdl, basedist, obs, H); % sol = sol.update_atoms(amdl, basedist, obs, H, ainds); % % updates all (or selected) atoms based on the current % labeling. % % Input arguments: % - amdl: the underlying atom model % - basedist: the base distribution % - obs: the observation array % - H: the struct capturing the inherited atoms % (it can be omitted when there is no % inheritance) % - ainds: the selected indices to atoms to be % updated. (update all atoms if omitted). % % parse input arguments if nargin < 5 H = []; Kp = 0; else if isempty(H) Kp = 0; else Kp = H.num; end end AS = sol.asys; if nargin < 6 ainds = 1 : AS.natoms; end na = numel(ainds); if na == 0 return; end % do updates grps = sol.groups; if isempty(grps) error('dpmm_sol:rterror', ... 'The observations have to been grouped before doing atom updates.'); end for j = 1 : na k = ainds(j); gk = grps{k}; aux = AS.auxes{k}; if k > Kp [a, aux] = amdl.posterior_params(basedist, obs, aux, gk, 'atom'); else if ~isempty(gk) [a, aux] = amdl.posterior_params(H.atoms{k}, obs, aux, gk, 'atom'); AS.priweights(k) = H.pricounts(k); else a = H.atoms{k}; aux = []; AS.priweights(k) = H.pricounts(k) * H.q(k); end end AS.atoms{k} = a; AS.auxes{k} = aux; AS.logliks(k, :) = amdl.evaluate_logliks(a, obs, aux); end sol.asys = AS; end function sol = update_labels(sol, amdl, basedist, obs, alpha, inds) % Update the labels associated with the observations % % sol = sol.update_labels(amdl, basedist, obs, alpha); % sol = sol.update_labels(amdl, basedist, obs, alpha, inds); % % Updates the labels of all or selected observations. % % Input arguments: % - amdl: the underlying atom model % - basedist: the base distribution % - obs: the observation array % - alpha: the concentration parameter % - inds: the indices of the observations selected % to be updated (if omitted, all labels % are to be updated) % % Note: % - inds should not contain repeated indices. % - the method will create new atoms when necessary. % if nargin < 6 ni = sol.nobs; s = 1:ni; else s = inds; end AS = sol.asys; if sol.natoms == 0 [a, aux] = amdl.posterior_params(basedist, obs, [], s(1), 'atom'); llik = amdl.evaluate_logliks(a, obs, aux); AS = dpmm_sol.add_atom(AS, a, aux, llik); sol.iatoms(s(1)) = 1; AS.counts(1) = 1; s(1) = []; end niters = 0; lalpha = log(double(alpha)); while ~isempty(s) niters = niters + 1; % re-draw labels K = AS.natoms; lpri = log(AS.priweights(1:K) + AS.counts(1:K)).'; E = bsxfun(@plus, lpri, AS.logliks(1:K, s)); ev0 = lalpha + AS.logliks0(1, s); z = dpmm_redraw_labels(E, ev0, rand(1, numel(s))); % update labels to the solution sol.iatoms(s) = z; if niters == 1 AS.counts(1:K) = intcount(K, sol.iatoms); else AS.counts(1:K) = AS.counts(1:K) + intcount(K, z); end % create new atom if necessary s = s(z == 0); if ~isempty(s) [a, aux] = amdl.posterior_params(basedist, obs, [], s(1), 'atom'); llik = amdl.evaluate_logliks(a, obs, aux); AS = dpmm_sol.add_atom(AS, a, aux, llik); K = AS.natoms; sol.iatoms(s(1)) = K; AS.counts(K) = 1; s(1) = []; end end sol.asys = AS; sol.groups = intgroup(K, sol.iatoms); % assert(dpmm_sol.verify_sol(sol.asys, sol.iatoms)); end function sol = prune(sol, Kp, tolratio) % Prune the solution by removing dead atoms % % sol = prune(sol, Kp, tolratio); % % Prunes the solution by removing dead atoms from % the solution, when the ratio of dead atoms is % above the tolratio. % % Kp is the number of atoms inherited from the prior, % which should not be removed, even if they are not % seen in the current samples. % K = sol.natoms; is_dead = sol.atom_counts == 0; if Kp > 0 is_dead(1:Kp) = false; end if nnz(is_dead) > K * tolratio deads = find(is_dead); [sol.asys, rlmap] = dpmm_sol.prune_atoms(sol.asys, deads); if ~isempty(sol.groups) sol.groups(deads) = []; end sol.iatoms = rlmap(sol.iatoms); % assert(dpmm_sol.verify_sol(sol.asys, sol.iatoms)); end end end %% private implementation methods(Static, Access='private') function S = init_atomsys(K0, n, max_id, logliks0) % Initialize an internal atom system S.natoms = 0; S.max_aid = max_id; S.capacity = K0; S.atom_ids = zeros(1, K0); S.atoms = cell(1, K0); S.auxes = cell(1, K0); S.priweights = zeros(1, K0); S.counts = zeros(1, K0); S.logliks = zeros(K0, n); S.logliks0 = logliks0; end function S = add_atom(S, a, aux, llik) % Adds a new atom % K = S.natoms; if K == S.capacity % grow the capacity new_capa = 2^(ceil(log2(K * 2))); S.capacity = new_capa; S.atom_ids(1, new_capa) = 0; S.atoms{1, new_capa} = []; S.auxes{1, new_capa} = []; S.priweights(1, new_capa) = 0; S.counts(1, new_capa) = 0; S.logliks(new_capa, end) = 0; end K = K + 1; S.natoms = K; S.max_aid = S.max_aid + 1; S.atom_ids(K) = S.max_aid; S.atoms{K} = a; S.auxes{K} = aux; S.logliks(K, :) = llik; end function [S, rlmap] = prune_atoms(S, ainds) % Prune the atom system by removing specified atoms % nd = numel(ainds); % the number of atoms to be deleted K = S.natoms; S.natoms = K - nd; S.atom_ids(ainds) = []; S.atoms(ainds) = []; S.auxes(ainds) = []; S.priweights(ainds) = []; S.counts(ainds) = []; S.logliks(ainds, :) = []; S.capacity = numel(S.atoms); % relabeling map is_retained = true(1, K); is_retained(ainds) = false; rlmap = zeros(1, K); rlmap(is_retained) = 1 : (K - nd); end function tf = verify_sol(AS, z) % A function for verifying the validity of the solution (for DEBUG) % K = AS.natoms; c = AS.counts(1:K); cr = intcount(K, z); tf = isequal(c, cr); end end end
zzhangumd-smitoolbox
pmodels/dp/dpmm_sol.m
MATLAB
mit
14,667
function v = logcrp(alpha, M) % LOGCRP evaluates log-probability of a partition under Chinese Restaurant Process % % Given a partition with K clusters, in which the k-th cluster has % m(k) elements, the log-probability of m is % % p(m) = alpha^K * prod_{k=1}^K (m(k) - 1)! * % Gamma(alpha) / Gamma(alpha + N). % % In particular, we call the part of the formula in the first line % to be the "upper part", and the remaining part is called "lower part". % Note that the "lower part" is fixed when the total number of elements % is fixed, and thus sometimes we are only interested in the upper part. % % v = LOGCRP(alpha, m); % evaluates the log-probability of a partition given by m under % a Chinese restaurant process of concentration parameter alpha. % % m represents a partition as follows: there are numel(m) clusters, % the k-th cluster has m(k) elements. % % V = LOGCRP(alpha, M); % % evaluates the log-probabilities of a collection of partitions % in M. Here M is a cell array, and each cell contains a partition. % % The size of V is the same as the size of M. % % Created by Dahua Lin, on Sep 17, 2011 % %% Verify input arguments if ~(isfloat(alpha) && isscalar(alpha) && isreal(alpha) && alpha > 0) error('logcrp:invalidarg', 'alpha should be a positive real number.'); end if isnumeric(M) if ~(isfloat(M) && isvector(M) && isreal(M)) error('logcrp:invalidarg', 'Each m should be a real vector.'); end n = 1; elseif iscell(M) n = numel(M); for i = 1 : n m = M{i}; if ~(isfloat(m) && isvector(m) && isreal(m)) error('logcrp:invalidarg', 'Each m should be a real vector.'); end end else error('logcrp:invalidarg', ... 'The 2nd argument should be either a real vector or a cell array.'); end %% Main if n == 1 v = eval_v(alpha, M); else v = zeros(size(M)); for i = 1 : n v(i) = eval_v(alpha, M{i}); end end %% Evaluation function v = eval_v(alpha, m) N = sum(m); c = gammaln(alpha) - gammaln(alpha + N); m = m(m > 0); v = numel(m) * log(alpha) + sum(gammaln(m)) + c;
zzhangumd-smitoolbox
pmodels/dp/logcrp.m
MATLAB
mit
2,180
function S = dpmm_inherits(atom_ids, max_id, atoms, pricounts, q, T) %DPMM_INHERITS Creates a struct that captures the inherited atoms for DPMM % % S = DPMM_INHERITS(atom_ids, max_id, atoms, pricounts); % S = DPMM_INHERITS(atom_ids, max_id, atoms, pricounts, q); % S = DPMM_INHERITS(atom_ids, max_id, atoms, pricounts, q, T); % % Creates a struct of priors based on inherited atoms for DPMM. % % Input arguments: % - atom_ids: the identifiers of inherited atoms % - atoms: the cell array of inherited atoms % - pricounts: the prior counts of the inherited atoms % - q: the acceptance probabilities % - T: the a function handle to transform atoms into % either an atom or a distribution of atoms % % If q is omitted, we set it to 1 by default. % If T is omitted, we set it to identity transform by default. % % The output S is a struct with the following fields: % - tag: a string: 'dpmm_inherits' % - num: the number of atoms that can be inherited % - atom_ids: the vector of inherited atom identifiers % - max_id: the maximum value of previous id % - atoms: the cell array of inherited (and transformed) atoms % - pricounts: the vector of prior counts of the inherited atoms % - q: the acceptance probability % % Created by Dahua Lin, on Sep 25, 2011 % %% verify input arguments if ~(isnumeric(atom_ids) && isvector(atom_ids)) error('dpmm_inherits:invalidarg', 'atom_ids should be a numeric vector.'); end if ~(isnumeric(max_id) && isscalar(max_id) && max_id >= max(atom_ids)) error('dpmm_inherits:invalidarg', 'max_id is invalid.'); end if ~iscell(atoms) error('dpmm_inherits:invalidarg', 'atoms should be a cell array.'); end if ~(isfloat(pricounts) && isvector(pricounts)) error('dpmm_inherits:invalidarg', ... 'pricounts should be a numeric vector.'); end if ~isequal(size(atom_ids), size(atoms), size(pricounts)) error('dpmm_inherits:invalidarg', ... 'The sizes of atom_ids, atoms, and pricounts are inconsistent.'); end na = numel(atoms); if nargin >= 3 if ~(isfloat(q) && isreal(q) && (isscalar(q) || numel(q) == na)) error('dpmm_inherits:invalidarg', ... 'q should be a real scalar or a vector of length == #atoms'); end if isscalar(q) q = q * ones(1, na); else q = reshape(q, [1, na]); end else q = zeros(1, na); end if nargin >= 4 if ~isa(T, 'function_handle') error('dpmm_inherits:invalidarg', ... 'T should be a function handle.'); end else T = []; end %% main na = numel(atoms); A = cell(1, na); if isempty(T) for i = 1 : na A{i} = atoms{i}; end else for i = 1 : na A{i} = T(atoms{i}); end end S.tag = 'dpmm_inherits'; S.num = na; S.atom_ids = reshape(atom_ids, 1, na); S.max_id = max_id; S.atoms = A; S.pricounts = pricounts; S.q = q;
zzhangumd-smitoolbox
pmodels/dp/dpmm_inherits.m
MATLAB
mit
3,046
function [x, acc] = crpsim(alpha, n, pricount) %CRPSIM Simulate a Chinese Restaurant Process (CRP) % % x = CRPSIM(alpha, n); % % simulates a Chinese Restaurant process to generate a sequence % of length n. % % x = CRPSIM(alpha, n, pricount); % % performs the simulation with prior count on the first K values. % K is numel(pricount). % % [x, acc] = CRPSIM(alpha, n); % [x, acc] = CRPSIM(alpha, n, pricount); % % Additionally returns the accumulated counts of each atom. % If pricount is given, acc includes the prior counts. % % Created by Dahua Lin, on Sep 17, 2011 % %% verify input arguments if ~(isfloat(alpha) && isscalar(alpha) && isreal(alpha) && alpha > 0) error('crpsim:invalidarg', 'alpha should be a positive real number.'); end if ~(isnumeric(n) && isscalar(n) && n == fix(n) && n >= 0) error('crpsim:invalidarg', 'n should be a non-negative integer.'); end if nargin < 3 pricount = []; else if ~(isnumeric(pricount) && isvector(pricount) && isreal(pricount)) error('crpsim:invalidarg', 'pricount should be a real vector.'); end end %% main alpha = double(alpha); if ~isempty(pricount) && ~isa(pricount, 'double') pricount = double(pricount); end r = rand(1, n); if nargout < 2 x = crpsim_cimp(alpha, r, pricount); else [x, acc] = crpsim_cimp(alpha, r, pricount); end
zzhangumd-smitoolbox
pmodels/dp/crpsim.m
MATLAB
mit
1,375
function s = dpmm_demo(op) % A program to demonstrate the use of DPMM % % s = dpmm_demo; with visualization % s = dpmm_demo('novis'); no visualization % % The function returns the merged sample. % % Created by Dahua Lin, on Sep 21, 2011 % %% parse input novis = nargin == 1 && strcmpi(op, 'novis'); %% Prepare data d = 2; Cx = pdmat('s', d, 1); Cu = pdmat('s', d, 5^2); centers = [-1 0; 1 0; 0 1]' * 5; K0 = size(centers, 2); n = 1000; Xs = cell(1, K0); for k = 1 : K0 Xs{k} = gsample(centers(:,k), Cx, n); end X = [Xs{:}]; %% Construct underlying model gbase = gaussd.from_mp(0, Cu, 'ip'); amodel = gaussgm(d, Cx); %% Construct DPMM Kp = 2; assert(Kp <= K0); pri_atoms = cell(1, Kp); for i = 1 : Kp pri_atoms{i} = centers(:,i); end pri_counts = 1000 * ones(1, Kp); inherits = dpmm_inherits(1:Kp, Kp, pri_atoms, pri_counts, 0.5, @gtransit); alpha = 1; prg = dpmm(amodel, gbase, alpha); %% Run DPMM S0.inherits = inherits; opts = mcmc_options([], ... 'burnin', 100, ... 'nsamples', 20, ... 'ips', 20, ... 'display', 'sample'); R = smi_mcmc(prg, X, S0, opts); ss = R{1}; s = dpmm_merge_samples(prg, X, inherits, ss, 'rthres', 0.05); %% Visualize if novis; return; end figure; title('DPMM (Gauss) Demo'); plot(X(1,:), X(2,:), '.'); axis equal; A = s.atoms; A = [A{:}]; cnts = s.atom_counts; A = A(:, cnts > n / 2); hold on; plot(A(1,:), A(2,:), 'r+', 'MarkerSize', 20, 'LineWidth', 2); hold off; %% Probabilistic transition function g = gtransit(a) g = gaussd.from_mp(a, pdmat('s', 2, 1e-8), 'ip');
zzhangumd-smitoolbox
pmodels/dp/dpmm_demo.m
MATLAB
mit
1,578
/******************************************************************** * * crpsim_cimp.cpp * * The C++ mex implementation of crpsim (CRP simulation) * * Created by Dahua Lin, on Sep 17, 2011 * ********************************************************************/ #include <bcslib/matlab/bcs_mex.h> #include <vector> #include "dp_base.h" using namespace bcs; using namespace bcs::matlab; inline double calc_sum(int n, const double *a) { double s(0); for (int i = 0; i < n; ++i) s += a[i]; return s; } void do_sim(double alpha, int n, double *x, std::vector<double>& acc, const double *randnums) { int K = (int)acc.size(); double tw = calc_sum(K, &(acc[0])) + alpha; for (int i = 0; i < n; ++i) { int k = dd_draw(K, &(acc[0]), tw, randnums[i]); if (k < K) { acc[k] += 1.0; } else { acc.push_back(1.0); ++ K; } tw += 1.0; x[i] = double(k + 1); } } /*********** * * Main entry * * Input: * [0] alpha: the concentration parameter [double scalar] * [1] randnums: the sequence of uniform random numbers [1 x n] * [2] pricount: the prior count [double array] * * Output: * [0] x: the generated sequence * [1] acc: the accumulated count of atoms * */ void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // take input const_marray mAlpha(prhs[0]); const_marray mRandNums(prhs[1]); const_marray mPriCount(prhs[2]); double alpha = mAlpha.get_scalar<double>(); int n = (int)mRandNums.nelems(); const double *randnums = mRandNums.data<double>(); int K = (int)mPriCount.nelems(); const double *pric = 0; if (K > 0) { pric = mPriCount.data<double>(); } // prepare output marray mX = create_marray<double>(1, (size_t)n); double *x = mX.data<double>(); // do simulation std::vector<double> acc; acc.reserve((size_t)(K + 16)); if (K > 0) { for (int k = 0; k < K; ++k) { acc.push_back(pric[k]); } } do_sim(alpha, n, x, acc, randnums); // make output plhs[0] = mX.mx_ptr(); if (nlhs >= 2) { plhs[1] = to_matlab_row(acc).mx_ptr(); } } BCSMEX_MAINDEF
zzhangumd-smitoolbox
pmodels/dp/private/crpsim_cimp.cpp
C++
mit
2,468
/******************************************************************** * * dp_base.h * * Basic facilities for DP-based implementation * * Created by Dahua Lin, on Sep 17, 2011 * ********************************************************************/ #ifndef DP_BASE_H_ #define DP_BASE_H_ /** * Draw from a discrete distribution */ inline int dd_draw(int K, const double *w, double tw, double u) { double v = u * tw; int k = -1; double cs = 0.0; int Km1 = K - 1; while (cs < v && k < Km1) { cs += w[++k]; } if (cs < v) ++ k; // indicates the draw falls outside range return k; } #endif
zzhangumd-smitoolbox
pmodels/dp/private/dp_base.h
C
mit
668
/********************************************************** * * dpmm_redraw_labels.cpp * * C++ mex implementation of label re-drawing * * Created by Dahua Lin, on Sep 24, 2011 * **********************************************************/ #include <bcslib/matlab/bcs_mex.h> #include "dp_base.h" #include <cmath> using namespace bcs; using namespace bcs::matlab; inline double draw_label(int K, const double *e, double e0, double u, double *w) { double mv = e0; for (int k = 0; k < K; ++k) { if (e[k] > mv) mv = e[k]; } double w0 = std::exp(e0 - mv); double sw = w0; for (int k = 0; k < K; ++k) { sw += (w[k] = std::exp(e[k] - mv)); } int z = dd_draw(K, w, sw, u); return z < K ? double(z + 1) : 0.0; } /** * Input * [0] E: the main log-evidence matrix [K x n] * [1] ev0: the base log-evidence vector [1 x n] * [2] rnums: the random numbers [1 x n] * * Output * [0] z: the obtained labels [1 x n] */ void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // take input const_marray mE(prhs[0]); const_marray mEv0(prhs[1]); const_marray mRnums(prhs[2]); int K = (int)mE.nrows(); int n = (int)mE.ncolumns(); const double *E = mE.data<double>(); const double *ev0 = mEv0.data<double>(); const double *rnums = mRnums.data<double>(); marray mZ = create_marray<double>(1, n); double *z = mZ.data<double>(); // main double *w = new double[K]; for (int i = 0; i < n; ++i) { z[i] = draw_label(K, E + K * i, ev0[i], rnums[i], w); } delete[] w; // output plhs[0] = mZ.mx_ptr(); } BCSMEX_MAINDEF
zzhangumd-smitoolbox
pmodels/dp/private/dpmm_redraw_labels.cpp
C++
mit
1,765
classdef dpmm < smi_prg % The class to implement a DP mixture model (DPMM) program % % Created by Dahua Lin, on Sep 17, 2011 % %% Properties properties(GetAccess='public', SetAccess='private') amodel; % the underlying atom model (of class genmodel_base) basedist; % the base distribution alpha; % the concentration parameter end % configuration properties dead_tolratio = 0.3; % the tolerable ratio of dead atoms end %% Constructor methods function prg = dpmm(model, basedist, alpha) % Creates an DPMM program % % sol = dpmm(model, basedist, alpha, ...); % % Creates a DPMM program, given the underlying % atom model (model), the base distribution, and % the concentration parameter (alpha). % % verify inputs if ~isa(model, 'genmodel_base') error('dpmm:invalidarg', ... 'The input model should be of a class derived from genmodel_base.'); end if ~model.is_supported_optype('atom') error('dpmm:invalidarg', ... 'The input model does not support the optype ''atom''.'); end if ~model.is_valid_prior(basedist) error('dpmm:invalidarg', ... 'basedist is not a valid prior w.r.t to the atom model.'); end if ~(isfloat(alpha) && isscalar(alpha) && isreal(alpha) && alpha > 0) error('dpmm:invalidarg', ... 'alpha should be a positive real number.'); end % set fields prg.amodel = model; prg.basedist = basedist; prg.alpha = alpha; end end %% Interface methods methods function [sol, Sc] = initialize(prg, obs, S0, optype) % Initialize the states given observations and relevant info % % [sol, Sc] = prg.initialize(obs, S0, 'sample'); % % The method initialize the solution and a struct that % captures relevant information about the observation % and inherited atoms. % % S0 is either empty (use default settings), or % a struct with all or part of the following fields % that customize the settings. % % - inherits: an inherit struct that captures the % atoms inherited from prior source. % (can be made by dpmm_inherits) % If omitted, there is no inheritance. % % - initcap: the initial capacity of the solution. % % - sol: the initial solution (of class dpmm_sol). % % In the output, % - sol: the initial solutio (of class dpmm_sol) % - Sc: a struct of static information: % - obs: the observation array % - inherits: the inheritance struct % - nh; the number of inherits % % basics amdl = prg.amodel; n = amdl.get_num_observations(obs); H = []; c0 = []; sol = []; % check init fields if ~isempty(S0) if ~(isstruct(S0) && isscalar(S0)) error('dpmm:invalidarg', ... 'S0 should be either empty or a struct scalar.'); end if isfield(S0, 'inherits') && ~isempty(S0.inherits) H = S0.inherits; if ~(isstruct(H) && isfield(H, 'tag') && ... strcmp(H.tag, 'dpmm_inherits')) error('dpmm:invalidarg', ... 'The inherits field is not valid.'); end end if isfield(S0, 'initcap') && ~isempty(S0.initcap) c0 = S0.initcap; if ~(isnumeric(c0) && isscalar(c0) && c0 >= 0) error('dpmm:invalidarg', ... 'initcap should be a non-negative scalar.'); end end if isfield(S0, 'sol') && ~isempty(S0.sol) sol = S0.sol; if ~isa(sol, 'dpmm_sol') error('dpmm:invalidarg', ... 'sol should be an instance of class dpmm_sol.'); end if sol.nobs ~= n error('dpmm:invalidarg', ... '#obs is inconsistent with sol.nobs.'); end end end if ~(ischar(optype) && strcmpi(optype, 'sample')) error('dpmm:invalidarg', ... 'The only supported operation type is ''sample''.'); end % construct solution if isempty(sol) if isempty(c0) sol = dpmm_sol(amdl, prg.basedist, obs); else sol = dpmm_sol(amdl, prg.basedist, obs, c0); end end % construct Sc Sc.inherits = H; Sc.obs = obs; if isempty(H) Sc.nh = 0; else Sc.nh = H.num; end end function [sol, Sc] = update(prg, sol, Sc) % Updates the solution % % [sol, Sc] = prg.update(sol, Sc); % % Updates the solution by running re-sampling steps. % amdl = prg.amodel; dist0 = prg.basedist; obs = Sc.obs; sol = sol.update_labels(amdl, dist0, obs, prg.alpha); sol = sol.update_atoms(amdl, dist0, obs, Sc.inherits); sol = sol.prune(Sc.nh, prg.dead_tolratio); end function S = make_output(prg, sol, ~) %#ok<MANU> % Makes the output sample from states % % S = make_output(prg, sol, Sc); % % This returns a struct that representa s sample, % which contains the following fields: % % - natoms; % - max_atom_id; % - atom_ids; % - atoms; % - atom_counts; % - iatoms; % - labels := atom_ids(iatoms) % S.natoms = sol.natoms; S.max_atom_id = sol.max_atom_id; S.atom_ids = sol.atom_ids; S.atoms = sol.atoms; S.atom_counts = sol.atom_counts; S.iatoms = sol.iatoms; S.labels = sol.labels; end function objv = evaluate_objective(prg, sol, Sc) %#ok<STOUT,MANU,INUSD> % Evaluate objective of a solution (not implemented) % error('dpmm:notimplemented', ... 'Evaluation of objective is not implemented for DPMM.'); end end end
zzhangumd-smitoolbox
pmodels/dp/dpmm.m
MATLAB
mit
8,128
function write_mps(P, filename, fmt) % Write an LP or QP optimization problem to MPS file % % write_mps(P, filename); % writes an LP problem to the specified MPS file. % % write_mps(P, filename, fmt); % writes an QP problem to the specified MPS file using specified % extension. % % Note that the standard MPS format does not support QP in itself. % Different vendors have their respective extention to MPS format % to support QP and other problems. % % The argument fmt here specifies which extension to use, whose % value can be % - 'cplex': the ILOG CPLEX extensions. % - 'gurobi': the GUROBI extensions. % - 'mosek': the MOSEK extensions. % % Created by Dahua Lin, on April 16, 2011 % %% verify input arguments if ~(isstruct(P) && isfield(P, 'type') && ... (strcmp(P.type, 'lp') || strcmp(P.type, 'qp')) ) error('write_mps:invalidarg', ... 'P should be a lp_problem or qp_problem struct.'); end is_qp = strcmp(P.type, 'qp'); if is_qp if nargin < 3 error('write_mps:invalidarg', ... 'The 3rd argument (fmt) should be specified for QP problem.'); end if ~ischar(fmt) error('write_mps:invalidarg', 'fmt should be a char string.'); end FMT_CPLEX = 1; FMT_GUROBI = 2; FMT_MOSEK = 3; switch lower(fmt) case 'cplex' fmt_id = FMT_CPLEX; case 'gurobi' fmt_id = FMT_GUROBI; case 'mosek' fmt_id = FMT_MOSEK; otherwise error('write_mps:invalidarg', 'Unknown fmt name %s', fmt); end end %% main % open file fid = fopen(filename, 'w'); if fid <= 0 error('write_mps:ioerror', 'Failed to open file %s to write', filename); end % NAME section [pastr, name] = fileparts(filename); %#ok<ASGLU> fprintf(fid, '%-14s%s\n', 'NAME', upper(name)); % ROWS section cons_names = write_rows_section(fid, P); % COLUMNS section var_names = write_columns_section(fid, P, cons_names); fprintf(fid, '\n'); % RHS section write_rhs_section(fid, P, cons_names); % BOUNDS section write_bounds_section(fid, P, var_names); % Quadraic section (for QP) if is_qp switch fmt_id case FMT_CPLEX write_quad_obj_cplex(fid, P.H, var_names); case FMT_GUROBI write_quad_obj_gurobi(fid, P.H, var_names); case FMT_MOSEK write_quad_obj_mosek(fid, P.H, var_names); end end % ENDATA fprintf(fid, 'ENDATA\n\n'); % close file fclose(fid); %% standard sections function cons_names = write_rows_section(fid, P) fprintf(fid, 'ROWS\n'); fprintf(fid, ' N COST\n'); ge_names = []; le_names = []; eq_names = []; if ~isempty(P.A) m1 = size(P.A, 1); ge_name_pat = sprintf('G%%0%dd', length(int2str(m1))); le_name_pat = sprintf('L%%0%dd', length(int2str(m1))); ge_names = arrayfun(@(x) sprintf(ge_name_pat, x), (1:m1)', 'UniformOutput', false); le_names = arrayfun(@(x) sprintf(le_name_pat, x), (1:m1)', 'UniformOutput', false); for i = 1 : m1 if is_val(P.bl, i) fprintf(fid, make_row('G', ge_names{i})); end if is_val(P.bu, i) fprintf(fid, make_row('L', le_names{i})); end end end if ~isempty(P.Aeq) m0 = size(P.Aeq, 1); eq_name_pat = sprintf('E%%%dd', length(int2str(m0))); eq_names = arrayfun(@(x) sprintf(eq_name_pat, x), (1:m0)', 'UniformOutput', false); for i = 1 : m0 fprintf(fid, make_row('E', eq_names{i})); end end cons_names.ge = ge_names; cons_names.le = le_names; cons_names.eq = eq_names; function var_names = write_columns_section(fid, P, cons_names) fprintf(fid, 'COLUMNS\n'); n = P.d; cname_pat = sprintf('X%%0%dd', length(int2str(n))); cnames = arrayfun(@(x) sprintf(cname_pat, x), (1:n).', 'UniformOutput', false); ge_names = cons_names.ge; le_names = cons_names.le; eq_names = cons_names.eq; for j = 1 : n cname = cnames{j}; fv = 0; if ~isempty(P.f) fv = P.f(j); end if fv == 0 fprintf(fid, make_entry(cname)); else fprintf(fid, make_entry(cname, 'COST', fv)); end if ~isempty(P.A) [i, v] = find(P.A(:,j)); if ~isempty(i) for k = 1 : numel(i) bl = is_val(P.bl, i(k)); bu = is_val(P.bu, i(k)); if bl && bu fprintf(fid, make_entry(cname, ge_names{i(k)}, v(k), le_names{i(k)}, v(k))); elseif bl fprintf(fid, make_entry(cname, ge_names{i(k)}, v(k))); elseif bu fprintf(fid, make_entry(cname, le_names{i(k)}, v(k))); end end end end if ~isempty(P.Aeq) [i, v] = find(P.Aeq(:,j)); if ~isempty(i) for k = 1 : numel(i) fprintf(fid, make_entry(cname, eq_names{i(k)}, v(k))); end end end end var_names = cnames; function write_rhs_section(fid, P, cons_names) fprintf(fid, 'RHS\n'); ge_names = cons_names.ge; le_names = cons_names.le; eq_names = cons_names.eq; if ~isempty(P.A) m1 = size(P.A, 1); for i = 1 : m1; bl = is_val(P.bl, i); bu = is_val(P.bu, i); if bl && bu fprintf(fid, make_entry('RH', ge_names{i}, P.bl(i), le_names{i}, P.bu(i))); elseif bl fprintf(fid, make_entry('RH', ge_names{i}, P.bl(i))); elseif bu fprintf(fid, make_entry('RH', le_names{i}, P.bu(i))); end end end if ~isempty(P.Aeq) m0 = size(P.Aeq, 1); for i = 1 : m0 fprintf(fid, make_entry('RH', eq_names{i}, P.beq(i))); end end function write_bounds_section(fid, P, var_names) fprintf(fid, 'BOUNDS\n'); n = P.d; if isempty(P.l) if isempty(P.u) for j = 1 : n fprintf(fid, make_bnd('FR', var_names{j})); end else for j = 1 : n if is_val(P.u, j) fprintf(fid, make_bnd('UP', var_names{j}, P.u(j))); end end end else if isempty(P.u) for j = 1 : n if is_val(P.l, j) fprintf(fid, make_bnd('LO', var_names{j}, P.l(j))); end end else for j = 1 : n if is_val(P.l, j) fprintf(fid, make_bnd('LO', var_names{j}, P.l(j))); end if is_val(P.u, j) fprintf(fid, make_bnd('UP', var_names{j}, P.u(j))); end end end end %% vendor-specific extended sections function write_quad_obj_cplex(fid, H, var_names) fprintf(fid, 'QMATRIX\n'); [I, J, V] = find(H); si = find(I <= J); I = I(si); J = J(si); V = V(si); for k = 1 : numel(I) i = I(k); j = J(k); v = V(k); if i == j fprintf(fid, make_entry(var_names{i}, var_names{j}, v)); else fprintf(fid, make_entry(var_names{i}, var_names{j}, v)); fprintf(fid, make_entry(var_names{j}, var_names{i}, v)); end end function write_quad_obj_gurobi(fid, H, var_names) fprintf(fid, 'QUADOBJ\n'); [I, J, V] = find(H); si = find(I <= J); I = I(si); J = J(si); V = V(si); for k = 1 : numel(I) i = I(k); j = J(k); v = V(k); fprintf(fid, make_entry(var_names{i}, var_names{j}, v)); end function write_quad_obj_mosek(fid, H, var_names) fprintf(fid, '%15s%s\n', 'QSECTION', 'COST'); [I, J, V] = find(H); si = find(I <= J); I = I(si); J = J(si); V = V(si); for k = 1 : numel(I) i = I(k); j = J(k); v = V(k); if i == j fprintf(fid, make_entry(var_names{i}, var_names{j}, v)); else fprintf(fid, make_entry(var_names{i}, var_names{j}, 2 * v)); end end %% auxiliary formatting functions function line = make_row(type, name) line = sprintf(' %c %s\n', type(1), name); function line = make_entry(n0, n1, v1, n2, v2) pb = ' '; switch nargin case 1 line = [pb, n0, '\n']; case 2 line = [pb, sprintf('%-10s%s\n', n0, n1)]; case 3 line = [pb, sprintf('%-10s%-10s%g\n', n0, n1, v1)]; case 5 line = [pb, sprintf('%-10s%-10s%-15g%-10s%g\n', n0, n1, v1, n2, v2)]; end function line = make_bnd(type, cname, v) if nargin == 2 line = sprintf(' %-2s %-10s%s\n', type, 'BND', cname); else line = sprintf(' %-2s %-10s%-10s%g\n', type, 'BND', cname, v); end %% Other auxiliary function function tf = is_val(a, i) tf = ~isempty(a) && ~isinf(a(i)) && ~isnan(a(i));
zzhangumd-smitoolbox
optim/adaptor/write_mps.m
MATLAB
mit
8,634
function [x, fval, flag, info] = mstd_solve(P, options) % Adaptor of MATLAB optimization toolbox to solve the LP/QP problem % % x = mstd_solve(P); % x = mstd_solve(P, options); % % Uses linprog/quadprog (in optimization toolbox) to solve the % LP/QP problem given by the struct P (as constructed in lp_problem % or qp_problem). % % [x, fval] = mstd_solve( ... ); % [x, fval, flag] = mstd_solve( ... ); % [x, fval, flag, info] = mstd_solve( ... ); % % Returns additional outputs. % % - fval: the value of objective function at x % - flag: the exit flag that describes the exit condition. % - info: the struct that contains information of the optimization % procedure. % % Please refer to the document of linprog for more details about % the options and outputs. % % Created by Dahua Lin, on Apr 7, 2011 % %% verify input arguments if ~(isstruct(P) && isfield(P, 'type') && (strcmp(P.type, 'lp') || strcmp(P.type, 'qp'))) error('mstd_solve:invalidarg', 'P should be a lp_problem/qp_problem struct.'); end is_qp = strcmp(P.type, 'qp'); if nargin < 2 if ~is_qp options = optimset('linprog'); else options = optimset('quadprog'); end options = optimset(options, 'Display', 'off'); else if ~isstruct(options) error('mstd_solve:invalidarg', 'options should be a struct.'); end end %% main % convert problem f = P.f; if is_qp H = P.H; end if isempty(P.A) A = []; b = []; else if isempty(P.bl) A = P.A; b = P.bu; elseif isempty(P.bu) A = -P.A; b = -P.bl; else A = [P.A; -P.A]; b = [P.bu; -P.bl]; end end Aeq = P.Aeq; beq = P.beq; lb = P.l; ub = P.u; % solve nout = nargout; if ~is_qp if nout <= 1 x = linprog(f, A, b, Aeq, beq, lb, ub, [], options); elseif nout == 2 [x, fval] = linprog(f, A, b, Aeq, beq, lb, ub, [], options); elseif nout == 3 [x, fval, flag] = linprog(f, A, b, Aeq, beq, lb, ub, [], options); else [x, fval, flag, info] = linprog(f, A, b, Aeq, beq, lb, ub, [], options); end else if nout <= 1 x = quadprog(H, f, A, b, Aeq, beq, lb, ub, [], options); elseif nout == 2 [x, fval] = quadprog(H, f, A, b, Aeq, beq, lb, ub, [], options); elseif nout == 3 [x, fval, flag] = quadprog(H, f, A, b, Aeq, beq, lb, ub, [], options); else [x, fval, flag, info] = quadprog(H, f, A, b, Aeq, beq, lb, ub, [], options); end end
zzhangumd-smitoolbox
optim/adaptor/mstd_solve.m
MATLAB
mit
2,562
function [x, fval, flag, info] = cplex_solve(P, options) % Adaptor of CPLEX optimizer to solve the LP/QP problem % % x = cplex_solve(P); % x = cplex_solve(P, options); % % Uses quadprog (in optimization toolbox) to solve the LP or QP % problem given by the struct P (as constructed in lp_problem or % qp_problem). % % [x, fval] = cplex_solve( ... ); % [x, fval, flag] = cplex_solve( ... ); % [x, fval, flag, info] = cplex_solve( ... ); % % Returns additional outputs. % % - fval: the value of objective function at x % - flag: the exit flag that describes the exit condition. % - info: the struct that contains information of the optimization % procedure. % % Created by Dahua Lin, on Apr 15, 2011 % %% verify input arguments if ~(isstruct(P) && isfield(P, 'type') && (strcmp(P.type, 'lp') || strcmp(P.type, 'qp'))) error('cplex_solve:invalidarg', 'P should be a qp_problem struct.'); end is_qp = strcmp(P.type, 'qp'); if nargin < 2 options = []; else if ~isstruct(options) error('cplex_solve:invalidarg', 'options should be a CPLEX option struct.'); end end %% main % convert problem H = P.H; f = P.f; if isempty(P.A) A = []; b = []; else if isempty(P.bl) A = P.A; b = P.bu; elseif isempty(P.bu) A = -P.A; b = -P.bl; else A = [P.A; -P.A]; b = [P.bu; -P.bl]; end end Aeq = P.Aeq; beq = P.beq; lb = P.l; ub = P.u; % solve if isempty(options); options = cplexoptimset('Display', 'off'); end nout = nargout; if ~is_qp if nout <= 1 x = cplexlp(f, A, b, Aeq, beq, lb, ub, [], options); elseif nout == 2 [x, fval] = cplexlp(f, A, b, Aeq, beq, lb, ub, [], options); elseif nout == 3 [x, fval, flag] = cplexlp(f, A, b, Aeq, beq, lb, ub, [], options); else [x, fval, flag, info] = cplexlp(f, A, b, Aeq, beq, lb, ub, [], options); end else if nout <= 1 x = cplexqp(H, f, A, b, Aeq, beq, lb, ub, [], options); elseif nout == 2 [x, fval] = cplexqp(H, f, A, b, Aeq, beq, lb, ub, [], options); elseif nout == 3 [x, fval, flag] = cplexqp(H, f, A, b, Aeq, beq, lb, ub, [], options); else [x, fval, flag, info] = cplexqp(H, f, A, b, Aeq, beq, lb, ub, [], options); end end
zzhangumd-smitoolbox
optim/adaptor/cplex_solve.m
MATLAB
mit
2,366
function [x, fval, flag, info] = mosek_solve(P, options) % The wrapper of MOSEK optimizer for solving LP or QP problem. % % x = mosek_solve(P); % x = mosek_solve(P, options); % % [x, fval] = mosek_solve( ... ); % [x, fval, flag] = mosek_solve( ... ); % [x, fval, flag, info] = mosek_solve( ... ); % % Use MOSEK LP/QP optimizer to solve the LP problem specified by the % lp_problem struct P. % % options is a struct with MOSEK parameter fields. In addition, one % can specify the following option: % - 'Display': whose values can be 'off', 'final', or 'iter'. % % Output arguments: % % - x: the solution % - fval: the value of objective function at x % - flag: the return code that describes the exit condition. % - info: the struct that contains information of the optimization % procedure and result. % % Created by Dahua Lin, on April 14, 2011 % %% verify input arguments if ~(isstruct(P) && isfield(P, 'type') && (strcmp(P.type, 'lp') || strcmp(P.type, 'qp'))) error('mosek_solve:invalidarg', 'P should be a lp_problem or qp_problem struct.'); end is_qp = strcmp(P.type, 'qp'); if nargin < 2 || isempty(options) options = []; options.Display = 'off'; else if ~isstruct(options) error('mosek_solve:invalidarg', 'options should be a MOSEK parameter struct.'); end end [cmd, verbosity, param] = msksetup(true, options); %% main % prepare A = P.A; bl = P.bl; bu = P.bu; Ae = P.Aeq; be = P.beq; a = []; blc = []; buc = []; if ~isempty(A) if ~isempty(Ae) % A & Ae a = [A; Ae]; if isempty(bl) blc = [-inf(size(A,1), 1); be]; else blc = [bl; be]; end if isempty(bu) buc = [inf(size(A,1), 1); be]; else buc = [bu; be]; end else % only A a = A; blc = bl; buc = bu; end elseif ~isempty(Ae) % only Ae a = Ae; blc = be; buc = be; end if ~issparse(a) a = sparse(a); end % setup problem prob = []; if is_qp [prob.qosubi,prob.qosubj,prob.qoval] = find(tril(sparse(P.H))); end prob.c = P.f; prob.a = a; prob.blc = blc; prob.buc = buc; prob.blx = P.l; prob.bux = P.u; % solve [rcode, res] = mosekopt(cmd, prob, param); mskstatus('mosek_solve', verbosity, 0, rcode, res); % extract output if isfield(res, 'sol') x = res.sol.itr.xx; else x = []; end if nargout >= 2 if ~isempty(x) if ~is_qp fval = P.f' * x; else fval = (x' * P.H * x) / 2 + P.f' * x; end else fval = nan; end end if nargout >= 3 flag = rcode; end if nargout >= 4 info = res; end
zzhangumd-smitoolbox
optim/adaptor/mosek_solve.m
MATLAB
mit
2,760
function [x, fval, flag, info] = gurobi_solve(P, options) % Adaptor of GUROBI optimizer to solve the LP/QP problem % % x = gurobi_solve(P); % x = gurobi_solve(P, options); % % Uses GUROBI optimizer to solve the LP or QP problem given by the % struct P (as constructed in lp_problem or qp_problem). % % [x, fval] = gurobi_solve( ... ); % [x, fval, flag] = gurobi_solve( ... ); % [x, fval, flag, info] = gurobi_solve( ... ); % % Returns additional outputs. % % - fval: the value of objective function at x % - flag: the exit flag that describes the exit condition. % - info: the struct that contains information of the optimization % procedure. % % Created by Dahua Lin, on Apr 15, 2011 % %% verify input arguments if ~(isstruct(P) && isfield(P, 'type') && (strcmp(P.type, 'lp') || strcmp(P.type, 'qp'))) error('gurobi_solve:invalidarg', 'P should be a qp_problem struct.'); end is_qp = strcmp(P.type, 'qp'); if nargin < 2 options = []; else if ~isstruct(options) error('gurobi_solve:invalidarg', 'options should be a GUROBI params struct.'); end end if exist('gurobi_lpqp', 'file') ~= 2 error('gurobi_solve:invalidarg', ... 'This function relies on gurobi_lpqp (a gurobi matlab wrapper), which is not found.'); end %% main % convert problem if is_qp GP.H = P.H; end GP.f = P.f; GP.A = P.A; GP.bl = P.bl; GP.bu = P.bu; GP.Ae = P.Aeq; GP.be = P.beq; GP.lb = P.l; GP.ub = P.u; % solve nout = nargout; if nout <= 1 x = gurobi_lpqp(GP, options); elseif nout == 2 [x, fval] = gurobi_lpqp(GP, options); elseif nout == 3 [x, fval, flag] = gurobi_lpqp(GP, options); else [x, fval, flag, info] = gurobi_lpqp(GP, options); end
zzhangumd-smitoolbox
optim/adaptor/gurobi_solve.m
MATLAB
mit
1,757
/******************************************************************** * * qpps.cpp * * The C++ mex implementation of qpps.m * * Created by Dahua Lin, on Jul 21, 2010 * ********************************************************************/ #include <bcslib/matlab/bcs_mex.h> #include <algorithm> using namespace bcs; using namespace bcs::matlab; template <typename T> struct entry { int i; T v; bool operator < (const entry& rhs) const { return v > rhs.v; // just want to sort it in descending order } void set(int _i, T _v) { i = _i; v = _v; } }; template<typename T> void qpps(caview1d<T> f, aview1d<T> x, entry<T> *es) { int d = (int)f.nelems(); // pre-condition: x has all zeros // make and sort entries for (int i = 0; i < d; ++i) { es[i].set(i, f[i]); } std::sort(es, es + d); // main int k = 0; T s = T(0); T cumsum = T(0); while (k < d) { cumsum += es[k].v; T new_s = cumsum - (k+1) * es[k].v; if (new_s < 1) { s = new_s; ++k; } else break; } T a = (1 - s) / k - es[k - 1].v; // calculate output (x) for (int i = 0; i < k; ++i) { x[es[i].i] = es[i].v + a; } } template<typename T> inline marray do_qpps(const_marray mF) { index_t m = mF.nrows(); index_t n = mF.ncolumns(); marray mX; entry<T> *es = 0; if (m == 1 || n == 1) { if (m == 1) { mX = create_marray<T>(1, (size_t)n); es = new entry<T>[n]; } else { mX = create_marray<T>((size_t)m, 1); es = new entry<T>[m]; } caview1d<T> f = view1d<T>(mF); aview1d<T> x = view1d<T>(mX); qpps(f, x, es); } else { mX = create_marray<T>((size_t)m, (size_t)n); caview2d<T> F = view2d<T>(mF); aview2d<T> X = view2d<T>(mX); es = new entry<T>[m]; for (index_t i = 0; i < n; ++i) { qpps(F.column(i), X.column(i), es); } } delete[] es; return mX; } /********** * * main entry: * * input: * [0]: f [d x n] * * output: * [0]: x [d x n] * */ void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // take input if (nrhs != 1) { throw mexception("qpps:invalidarg", "The number of input arguments should be 1 for qpps"); } const_marray mF(prhs[0]); if (!( mF.is_matrix() && mF.is_float() && !mF.is_sparse() && !mF.is_complex() )) { throw mexception("qpps:invalidarg", "F should be a non-sparse real matrix."); } // main marray mX; if (mF.is_double()) { mX = do_qpps<double>(mF); } else { mX = do_qpps<float>(mF); } // output plhs[0] = mX.mx_ptr(); } BCSMEX_MAINDEF
zzhangumd-smitoolbox
optim/lpqp/qpps.cpp
C++
mit
3,226
function [x, lambda] = qplec(H, f, A, b) % Solves quadratic programming problems with linear equation constraints % % x = qplec(H, f, A, b); % solves the following constrained quadratic programming problem: % % minimize (1/2) * x' * H * x + f' * x % s.t. A * x = b % % Suppose there are m constraints, then size of H should be n x n, % and the size of A should be m x n. % The size of f and b can be configured in either of the following % ways: % % (1) f is an n x 1 vector, and b is an m x 1 vector, specifying % a qp problem. In the output, the size of x is n x 1. % % (2) f is an n x k matrix, and b is an m x 1 vector, specifying % k different qp problems, corresponding to different f. % In the output, the size of x is n x k, where x(:,i) % corresponds to f(:, i). % % (3) f is an n x 1 vector, and b is an m x k matrix, specifying % k different qp problems, corresponding to different b. % In the output, the size of x is n x k, where x(:,i) % corresponds to b(:, i). % % (4) f is an n x k matrix, and b is an m x k matrix, specifying % k different qp problems, with different f and b. % In the output, the size of x is n x k, where x(:,i) % corresponds to f(:,i) and b(:,i). % % [x, lambda] = qplec(H, f, A, b); % also returns the dual solution (lambda). % % Remarks: % - The function directly computes the solution using closed form % solution. % % History % ------- % - Created by Dahua Lin, on Nov 26, 2009 % - Modified by Dahua Lin, on Jul 21, 2010 % - change the error handling to light weighting % - Modified by Dahua Lin, on April 16, 2011 % %% parse and verify input arguments if ~(isfloat(H) && isreal(H) && ndims(H) == 2 && size(H,1) == size(H,2)) error('qplec:invalidarg', 'H should be a real valued square matrix.'); end if ~(isfloat(f) && isreal(f) && ndims(f) == 2) error('qplec:invalidarg', 'f should be a real valued matrix.'); end n = size(H, 1); if size(f, 1) ~= n error('qplec:invalidarg', 'The sizes of H and f are inconsistent.'); end kf = size(f, 2); if ~(isfloat(A) && isreal(A) && ndims(A) == 2) error('qplec:invalidarg', 'A should be a real valued matrix.'); end if ~(isfloat(b) && isreal(b) && ndims(b) == 2) error('qplec:invalidarg', 'b should be a real valued matrix.'); end if size(A, 2) ~= n error('qplec:invalidarg', 'A should have n columns.'); end m = size(A, 1); if size(b, 1) ~= m error('qplec:invalidarg', 'b should have m columns.'); end kb = size(b, 2); if kf > 1 && kb > 1 if kf ~= kb error('qplec:invalidarg', ... 'when both f and b have multiple columns, the number of columns should be the same.'); end end %% main % solve the unconstraint solution x0 = - (H \ f); % solve the dual problem if kf == kb dif = A * x0 - b; else dif = bsxfun(@minus, A * x0, b); end G = H \ A'; Q = A * G; Q = (Q + Q') / 2; lambda = Q \ dif; % derive the primal solution if size(x0, 2) == size(lambda, 2) x = x0 - G * lambda; else x = bsxfun(@minus, x0, G * lambda); end
zzhangumd-smitoolbox
optim/lpqp/qplec.m
MATLAB
mit
3,228
function S = lp_problem(f, A, b, Aeq, beq, l, u) %LP_PROBLEM Linear programming problem % % A Linear programming problem is formulated as: % % minimize f(x) = f' * x; % % s.t. bl <= A * x <= bu % Aeq * x = beq % l <= x <= u % % S = LP_PROBLEM(f, A, b); % S = LP_PROBLEM(f, A, b, Aeq, beq); % S = LP_PROBLEM(f, A, b, Aeq, beq, l, u); % constructs the problem. % % Input arguments: % - f: the objective coefficients % - A: the coefficient matrix of the inequalities % - b: the bounds of the inequalities, which can be in form of % bu or {bl, bu}. % - Aeq: the coefficient matrix of the equalities % - beq: the right hand side values of the equalities % - l: the lower bound of the solution entries % - u: the upper bound of the solution entries % % Note that when some contraints are not used, the corresponding % inputs can be omitted or set to empty. % % The output is a struct, which has a field type = 'lp', and the % following fields: d, c, A, bl, bu, Aeq, beq, l, u. % % Remarks % ------- % - x0 is the initial guess of the solution. If can be empty or % omitted, when it is available. Note that x0 serves just a hint, % whether it is used depends on particular solver chosen to solve % the problem. % % History % ------- % - Created by Dahua Lin, on Sep 25, 2010 % %% main error(nargchk(3, 7, nargin)); % f if ~(isnumeric(f) && isvector(f) && isreal(f) && ~isempty(f)) error('lp_problem:invalidarg', 'f should be a non-empty real vector.'); end if ~isa(f, 'double'); f = double(f); end if size(f, 2) > 2; f = f.'; end % turn f to a column vector d = length(f); % constraints if nargin >= 3 && ~isempty(A) [A, bl, bu] = check_lin_iec(d, A, b, 'lp_problem'); else A = []; bl = []; bu = []; end if nargin >= 5 && ~isempty(Aeq) [Aeq, beq] = check_lin_eqc(d, Aeq, beq, 'lp_problem'); else Aeq = []; beq = []; end % bounds if nargin >= 6 if nargin < 7 u = []; end [l, u] = check_bnds(d, l, u, 'lp_problem'); else l = []; u = []; end % output S = struct( ... 'type', 'lp', ... 'd', d, ... 'f', f, ... 'A', A, 'bl', bl, 'bu', bu, ... 'Aeq', Aeq, 'beq', beq, ... 'l', l, 'u', u);
zzhangumd-smitoolbox
optim/lpqp/lp_problem.m
MATLAB
mit
2,392
% The function to solve a simple QP on probability simplex % % The problem is formulated as follows: % % min (1/2) ||x||^2 - f' * x; % % s.t. x >= 0 (element wise), and sum(x) == 1. % % % X = qpps(F); % % When F is a vector, it returns the solution vector. % % When F is an m x n matrix (m > 1 and n > 1), X will be a matrix % of the same size. In particular, X(:,i) is the solution % corresponding to F(:,i). % % History % ------- % - Created by Dahua Lin, on Mar 28, 2011 %
zzhangumd-smitoolbox
optim/lpqp/qpps.m
MATLAB
mit
528
function [Aeq, beq] = check_lin_eqc(d, Aeq, beq, funname) % Check the validity of linear equality constraints % % [Aeq, beq] = check_lin_eqc(d, Aeq, beq, funname); % if ~(isfloat(Aeq) && ndims(Aeq) == 2) error([funname ':invalidconstr'], ... 'The equality coefficient matrix Aeq should be a numeric matrix.'); end [m, n] = size(Aeq); if n ~= d error([funname ':invalidconstr'], ... 'The requirement size(Aeq, 2) == d is not satisfied.'); end if ~(isfloat(beq) && ndims(beq) == 2 && size(beq, 2) == 1) error([funname ':invalidconstr'], ... 'The right-hand-side of equality beq should be a numeric column vector.'); end if size(beq,1) ~= m error([funname ':invalidconstr'], ... 'The right-hand-side of equality is inconsistent with Aeq.'); end
zzhangumd-smitoolbox
optim/lpqp/private/check_lin_eqc.m
MATLAB
mit
795
function [l, u] = check_bnds(d, l, u, funname) % Check the validity of range bounds % % [l, u] = check_bnds(d, l, u, funcname); % if ~isempty(l) if ~(isfloat(l) && (isscalar(l) || isequal(size(l), [d 1]))) error([funname ':invalidconstr'], ... 'The lower bound should be either a scalar of a d x 1 column.'); end if isscalar(l) l = constmat(d, 1, l); end else l = []; end if ~isempty(u) if ~(isfloat(u) && (isscalar(u) || isequal(size(u), [d 1]))) error([funname ':invalidconstr'], ... 'The upper bound should be either a scalar of a d x 1 column.'); end if isscalar(u) u = constmat(d, 1, u); end else u = []; end
zzhangumd-smitoolbox
optim/lpqp/private/check_bnds.m
MATLAB
mit
729
function [A, bl, bu] = check_lin_iec(d, A, b, funname) % Check the validity of linear inequality constraints % % [A, bl, bu] = check_lin_iec(d, A, b, funname); % if ~(isfloat(A) && ndims(A) == 2) error([funname ':invalidconstr'], ... 'The inequality coefficient matrix A should be a numeric matrix.'); end [m, n] = size(A); if n ~= d error([funname ':invalidconstr'], ... 'The requirement size(A, 2) == d is not satisfied.'); end if iscell(b) && numel(b) == 2 bl = b{1}; bu = b{2}; if ~(isempty(bl) || (isfloat(bl) && ndims(bl) == 2 && size(bl, 2) == 1)) error([funname ':invalidconstr'], ... 'The left-bound of inequality bl should be a numeric column vector.'); end if ~(isempty(bu) || (isfloat(bu) && ndims(bu) == 2 && size(bu, 2) == 1)) error([funname ':invalidconstr'], ... 'The right-bound of inequality bu should be a numeric column vector.'); end if ~((isempty(bl) || size(bl,1) == m) && (isempty(bu) || size(bu,1) == m)) error([funname ':invalidconstr'], ... 'The size of the bounds of inequality is inconsistent with A.'); end elseif isnumeric(b) if ~(isfloat(b) && ndims(b) == 2 && size(b, 2) == 1) error([funname ':invalidconstr'], ... 'The right-bound of inequality b should be a numeric column vector.'); end if size(b,1) ~= m error([funname ':invalidconstr'], ... 'The size of the bounds of inequality is inconsistent with A.'); end bl = []; bu = b; end
zzhangumd-smitoolbox
optim/lpqp/private/check_lin_iec.m
MATLAB
mit
1,588
function S = qp_problem(H, f, A, b, Aeq, beq, l, u) %QP_PROBLEM Quadratic programming problem % % A Linear programming problem is formulated as: % % minimize f(x) = (1/2) * x' * H * x + f' * x; % % s.t. bl <= A * x <= bu % Aeq * x = beq % l <= x <= u % % S = QP_PROBLEM(H, f, A, b); % S = QP_PROBLEM(H, f, A, b, Aeq, beq); % S = QP_PROBLEM(H, f, A, b, Aeq, beq, l, u); % constructs the problem. % % Input arguments: % - H: the quadratic coefficient matrix % - f: the linear coefficient vector % - A: the coefficient matrix of the inequalities % - b: the bounds of the inequalities, which can be in form of % bu or {bl, bu}. % - Aeq: the coefficient matrix of the equalities % - beq: the right hand side values of the equalities % - l: the lower bound of the solution entries % - u: the upper bound of the solution entries % % Note that when some contraints are not used, the corresponding % inputs can be omitted or set to empty. % % The output is a struct, which has a field type = 'lp', and the % following fields: d, c, A, bl, bu, Aeq, beq, l, u. % % Remarks % ------- % - x0 is the initial guess of the solution. If can be empty or % omitted, when it is available. Note that x0 serves just a hint, % whether it is used depends on particular solver chosen to solve % the problem. % % History % ------- % - Created by Dahua Lin, on Jan 2, 2010 % %% main error(nargchk(4, 8, nargin)); % H d = size(H,1); if ~(isfloat(H) && isreal(H) && ndims(H) == 2 && ~isempty(H) && d==size(H,2)) error('qp_problem:invalidarg', 'H should be a non-empty square matrix.'); end % f if ~(isnumeric(f) && isvector(f) && isreal(f) && ~isempty(f) && d==numel(f)) error('qp_problem:invalidarg', 'f should be a non-empty real vector.'); end if ~isa(f, 'double'); f = double(f); end if size(f, 2) > 2; f = f.'; end % constraints if nargin >= 4 && ~isempty(A) [A, bl, bu] = check_lin_iec(d, A, b, 'qp_problem'); else A = []; bl = []; bu = []; end if nargin >= 6 && ~isempty(Aeq) [Aeq, beq] = check_lin_eqc(d, Aeq, beq, 'qp_problem'); else Aeq = []; beq = []; end % bounds if nargin >= 7 if nargin < 8 u = []; end [l, u] = check_bnds(d, l, u, 'qp_problem'); else l = []; u = []; end % output S = struct( ... 'type', 'qp', ... 'd', d, ... 'H', H, ... 'f', f, ... 'A', A, 'bl', bl, 'bu', bu, ... 'Aeq', Aeq, 'beq', beq, ... 'l', l, 'u', u);
zzhangumd-smitoolbox
optim/lpqp/qp_problem.m
MATLAB
mit
2,648
function [x, v, dx, fcnt] = linesearch(f, x0, v0, step, beta, minstep) % Performs line search as a step in numerical optimization % % [x, v, dx, fcnt] = linesearch(f, x, step, beta, minstep); % performs line search along the direction of step to locate the % minima. % % Inputs: % - f: the objective function to be minimized % - x0: the location from which the search starts % - v0: the objective value at x0: f(x0) % - step: the initial moving step % - beta: the exponential decay coefficient % - minstep: the minimum allowable L2-norm of a step % % Outputs: % - x: the located point (x0 + dx) % - v: the objective value at located point (x) % - dx: the actual step % - fcnt: the number of times that f is invoked % % The search procedure runs as follows. It first take dx = step, % if f(x + dx) < f(x) then it is done, otherwise, it decreases dx % as dx = dx * beta. This process continues until the condition % f(x + dx) < f(x) is met, or ||dx|| < minstep. In latter case, % we simply return with dx set to a zero vector. % % Remarks % -------- % - This function is designed to be used by an optimization % algorithm. % - As this function is on a critical path of a typical optimization % method, no argument checking is performed for the sake of % efficiency. % % % Created by Dahua Lin, on Aug 2, 2010 % %% main dx = step; x = x0 + dx; v = f(x); fcnt = 1; while v >= v0 && norm(dx) > minstep dx = dx * beta; x = x0 + dx; v = f(x); fcnt = fcnt + 1; end if v >= v0 dx = 0; x = x0; v = v0; end
zzhangumd-smitoolbox
optim/nonlin/linesearch.m
MATLAB
mit
1,767
function options = smi_optimset(op0, varargin) % Set optimization options (for SMI optimization functions) % % options = smi_optimset(funcname); % % Gets the default optimization setting for a smi optimization % function (such as 'gdfmin', 'bfgsfmin', and 'newtonfmin'). % % options = smi_optimset(funcname, 'name1', value1, 'name2', value2, ...); % options = smi_optimset(options0, 'name1', value1, 'name2', value2, ...); % % Sets the optimization setting. It starts with the default setting % of a particular function or the supplied initial setting, and % updates it using the values in the ensuing name/value pairs. % % Created by Dahua Lin, on Jan 5, 2011 % %% Initialize options if ischar(op0) || isa(op0, 'function_handle') options = feval(op0, 'options'); else if ~(isstruct(op0) && numel(op0) == 1) error('smi_optimset:invalidarg', ... 'The first argument to smi_optimset is invalid.'); end options = op0; end %% Update if ~isempty(varargin) ns = varargin(1:2:end); vs = varargin(2:2:end); if numel(ns) ~= numel(vs) || ~iscellstr(ns) error('smi_optimset:invalidarg', ... 'The input option list is invalid.'); end for i = 1 : numel(ns) nam = ns{i}; v = vs{i}; switch lower(nam) case 'maxiter' if ~(isnumeric(v) && isscalar(v) && v >= 1) error('smi_optimset:invalidarg', ... 'MaxIter should be a positive integer scalar.'); end options.MaxIter = v; case 'tolfun' if ~(isfloat(v) && isscalar(v) && v > 0) error('smi_optimset:invalidarg', ... 'TolFun should be a positive scalar.'); end options.TolFun = v; case 'tolx' if ~(isfloat(v) && isscalar(v) && v > 0) error('smi_optimset:invalidarg', ... 'TolX should be a positive scalar.'); end options.TolX = v; case 'display' mon = optim_mon(v); options.Monitor = mon; case 'monitor' if ~isobject(v) error('smi_optimset:invalidarg', ... 'Monitor should be an object.'); end options.Monitor = v; case 'initinvhess' if ~(isfloat(v) && ndims(v) == 2 && size(v,1) == size(v,2)) error('smi_optimset:invalidarg', ... 'InitInvHess should be a numeric square matrix.'); end options.InitInvHess = v; case 'directnewton' if ~((isnumeric(v) || islogical(v)) && isscalar(v)) error('smi_optimset:invalidarg', ... 'DirectNewton should be a numeric/logical scalar.'); end options.DirectNewton = logical(v); otherwise error('smi_optimset:invalidarg', ... 'Unsupported optimization option %s', nam); end end end
zzhangumd-smitoolbox
optim/nonlin/smi_optimset.m
MATLAB
mit
3,401
classdef optim_mon % The class to represent a optimization monitor % % Created by Dahua Lin, on Aug 7, 2010 % properties(Constant) NoneLevel = 0; ProcLevel = 1; IterLevel = 2; end properties(GetAccess='public', SetAccess='private') level; fid = 1; end methods function mon = optim_mon(level) % Constructs an optimization monitor % % mon = optim_mon(level); % constructs an optimization monitor at specified level. % Here, level can be either a number of a string name: % 'none', 'proc', 'iter', 'step', or 'term'. % if isnumeric(level) && isscalar(level) v = level; elseif ischar(level) switch lower(level) case 'none' v = 0; case 'proc' v = 1; case 'iter' v = 2; case 'step' v = 3; otherwise error('optim_mon:invalidarg', ... 'Unknown monitor level %s', level); end else error('optim_mon:invalidarg', ... 'The input monitor level is invalid.'); end mon.level = v; end function on_proc_start(mon) if mon.level >= optim_mon.ProcLevel if mon.level >= optim_mon.IterLevel print_log(mon, '%10s%12s%15s%17s%15s\n', ... 'Iters', 'Fun.Evals', 'Move', 'Obj-value', 'Obj-change'); end end end function on_proc_end(mon, info) if mon.level >= optim_mon.ProcLevel if info.IsConverged print_log(mon, 'Optimization converges with %d iterations.\n', ... info.NumIters); else print_log(mon, ... 'Optimization did NOT converge after %d iterations.\n', ... info.NumIters); end end end function on_iter_start(mon, it) %#ok<MANU,INUSD> end function on_iter_end(mon, it, itstat) if mon.level >= optim_mon.IterLevel print_log(mon, '%10d %10d %13.4g %15.6g %13.4g\n', ... it, itstat.FunEvals, ... itstat.MoveNorm, itstat.FunValue, itstat.FunChange); end end end methods(Access='private') function print_log(mon, varargin) fprintf(mon.fid, varargin{:}); end end end
zzhangumd-smitoolbox
optim/nonlin/optim_mon.m
MATLAB
mit
3,109
function [x, info] = bfgsfmin(f, x0, varargin) % Perform unconstrained minimization using (BFGS) quasi-Newton method % % x = bfgsfmin(f, x0, ...); % solves a (local) minima of f using quasi-Newton method, with % Broyden-Fletcher-Goldfarb-Shanno (BFGS) updates. % Here, f is the objective function that supports the following % usage: % % [v, g] = f(x); % % In the output, v is the function value evaluated at x, g is the % gradient of f at x. % % x0 is the initial guess of the solution. % % One can also specify following options through name/value pairs. % % - MaxIter: the maximum number of iterations {100} % - TolFun: the termination tolerance of objective value change {1e-8} % - TolX: the termination tolerance of solution change {1e-7} % - Display: the level of display {'none'}|'proc'|'iter' % - InitInvHess: the initial inversed Hessian matrix % (if omitted, the default is the identity matrix) % % The function returns the optimized solution. % % [x, info] = bfgsfmin(f, x0, ...); % additionally returns the information of the solution. Here, info % is a struct with the following fields: % % - FunValue: the objective function value % - LastChange: the objective value change at last step % - LastMove: the solution change at last step % - IsConverged: whether the procedure converges % - NumIters: the number of elapsed iterations % % History % ------- % - Created by Dahua Lin, on Aug 7, 2010 % - Modified by Dahua Lin, on Jan 5, 2010 % - change the way of option setting % %% verify input if nargin == 3 && isstruct(varargin{1}) options = varargin{1}; else options = struct('MaxIter', 100, 'TolFun', 1e-8, 'TolX', 1e-7); if nargin == 1 && strcmpi(f, 'options') x = options; return; end options = smi_optimset(options, varargin{:}); end omon_level = 0; if isfield(options, 'Monitor') omon = options.Monitor; omon_level = omon.level; end d = length(x0); if isfield(options, 'InitInvHess') && ~isempty(options.InitInvHess) B = options.InitInvHess; if ~(size(B,1) == d && size(B,2) == d) error('bfgsfmin:invalidopt', ... 'InitInvHess should be a d x d real matrix.'); end else B = eye(d, d); end %% main x = x0; converged = false; it = 0; beta = 0.8; minstep = 0.5 * options.TolFun; if omon_level >= optim_mon.ProcLevel omon.on_proc_start(); end while ~converged && it < options.MaxIter it = it + 1; if omon_level >= optim_mon.IterLevel omon.on_iter_start(it); end if it == 1 [v, g] = f(x); total_fcnt = 1; end v0 = v; g0 = g; step = - (B * g); [x, v, dx, fcnt] = linesearch(f, x, v0, step, beta, minstep); ch = v - v0; nrm_dx = norm(dx); converged = abs(ch) < options.TolFun && nrm_dx < options.TolX; if ~converged % update B (inverse Hessian) [v, g] = f(x); fcnt = fcnt + 1; y = g - g0; sv = y' * dx; By = B * y; B = B + ((sv + y' * By) / (sv^2)) * (dx * dx') - (1/sv) * (By * dx' + dx * By'); B = (B + B') / 2; end total_fcnt = total_fcnt + fcnt; if omon_level >= optim_mon.IterLevel itstat = struct( ... 'FunValue', v, ... 'FunChange', ch, ... 'FunEvals', total_fcnt, ... 'Move', dx, ... 'MoveNorm', nrm_dx, ... 'IsConverged', converged); omon.on_iter_end(it, itstat); end end if nargout >= 2 || omon_level >= optim_mon.ProcLevel info = struct( ... 'FunValue', v, ... 'LastChange', ch, ... 'LastMove', dx, ... 'IsConverged', converged, ... 'NumIters', it); end if omon_level >= optim_mon.ProcLevel omon.on_proc_end(info); end
zzhangumd-smitoolbox
optim/nonlin/bfgsfmin.m
MATLAB
mit
4,174
function [x, info] = gdfmin(f, x0, varargin) % Perform unconstrained minimization using simple gradient descent % % x = gdfmin(f, x0, ...); % solves a (local) minima of f using standard gradient descent. % Here, f is the objective function that supports the following % usage: % % [v, g] = f(x); % % In the output, v is the function value evaluated at x, g and H % are respectively the gradient and Hessian. % % x0 is the initial guess of the solution. % % One can also specify following options through name/value pairs. % % - MaxIter: the maximum number of iterations {200} % - TolFun: the termination tolerance of objective value change {1e-6} % - TolX: the termination tolerance of solution change {1e-6} % - Display: the level of display {'none'}|'proc'|'iter' % % The function returns the optimized solution. % % [x, info] = gdfmin(f, x0, ...); % additionally returns the information of the solution. Here, info % is a struct with the following fields: % % - FunValue: the objective function value % - LastChange: the objective value change at last step % - LastMove: the solution change at last step % - IsConverged: whether the procedure converges % - NumIters: the number of elapsed iterations % % History % ------- % - Created by Dahua Lin, on Aug 7, 2010 % - Modified by Dahua Lin, on Jan 5, 2010 % - change the way of option setting % %% verify input if nargin == 3 && isstruct(varargin{1}) options = varargin{1}; else options = struct('MaxIter', 200, 'TolFun', 1e-6, 'TolX', 1e-6); if nargin == 1 && strcmpi(f, 'options') x = options; return; end options = smi_optimset(options, varargin{:}); end omon_level = 0; if isfield(options, 'Monitor') omon = options.Monitor; omon_level = omon.level; end %% main x = x0; converged = false; it = 0; beta = 0.8; minstep = 0.5 * options.TolFun; if omon_level >= optim_mon.ProcLevel omon.on_proc_start(); end total_fcnt = 0; while ~converged && it < options.MaxIter it = it + 1; if omon_level >= optim_mon.IterLevel omon.on_iter_start(it); end [v0, g] = f(x); step = -g; [x, v, dx, fcnt] = linesearch(f, x, v0, step, beta, minstep); ch = v - v0; nrm_dx = norm(dx); converged = abs(ch) < options.TolFun && nrm_dx < options.TolX; total_fcnt = total_fcnt + (fcnt + 1); if omon_level >= optim_mon.IterLevel itstat = struct( ... 'FunValue', v, ... 'FunChange', ch, ... 'FunEvals', total_fcnt, ... 'Move', dx, ... 'MoveNorm', nrm_dx, ... 'IsConverged', converged); omon.on_iter_end(it, itstat); end end if nargout >= 2 || omon_level >= optim_mon.ProcLevel info = struct( ... 'FunValue', v, ... 'LastChange', ch, ... 'LastMove', dx, ... 'IsConverged', converged, ... 'NumIters', it); end if omon_level >= optim_mon.ProcLevel omon.on_proc_end(info); end
zzhangumd-smitoolbox
optim/nonlin/gdfmin.m
MATLAB
mit
3,319
function [g, H] = approx_deriv(f, x, h) % Compute approximated derivatives by finite difference % % g = approx_deriv(f, x); % g = approx_deriv(f, x, h); % computes the (approximated) gradient of a function f at x. % Here, h is the difference at x-value used in the approximation. % If omitted, it uses 1e-5 for h. % % [g, H] = approx_deriv(f, x); % [g, H] = approx_deriv(f, h); % additionally computes the (approximated) Hessian matrix at x. % % Remarks % ------- % - First order central difference approximation is used. % % - This routine is designed for the purpose of verifying whether % the computation of the derivatives of a particular function % is correctly implemented, but not for actual computation. % % History % ------- % - Created by Dahua Lin, on Jan 24, 2011 % %% verify input arguments if ~isa(f, 'function_handle') error('approx_deriv:invalidarg', 'f should be a function handle.'); end if ~(isfloat(x) && ndims(x) == 2 && size(x, 2) == 1) error('approx_deriv:invalidarg', 'x should be a numeric column vector.'); end d = size(x, 1); if nargin < 3 h = 1e-5; else if ~(isfloat(h) && isscalar(h) && isreal(h) && h > 0) error('approx_deriv:invalidarg', 'h should be a positive real number.'); end end %% main % compute gradient g = zeros(d, 1); for i = 1 : d x_p = av(x, i, h/2); x_n = av(x, i, -h/2); g(i) = (f(x_p) - f(x_n)) / h; end % compute Hessian if nargout < 2 return; end H = zeros(d, d); for i = 1 : d for j = 1 : i x_pp = av(x, i, h/2, j, h/2); x_pn = av(x, i, h/2, j, -h/2); x_np = av(x, i, -h/2, j, h/2); x_nn = av(x, i, -h/2, j, -h/2); H(i, j) = (f(x_pp) + f(x_nn) - f(x_pn) - f(x_np)) / (h^2); if j < i H(j, i) = H(i, j); end end end %% Auxiliary routine function y = av(x, i, ei, j, ej) y = x; y(i) = y(i) + ei; if nargin >= 5 y(j) = y(j) + ej; end
zzhangumd-smitoolbox
optim/nonlin/approx_deriv.m
MATLAB
mit
2,009
function [r1, r2] = check_deriv(f, X, h) % A function for checking whether derivatives are computed correctly % % r1 = check_deriv(f, X); % r1 = check_deriv(f, X, h); % % This statement takes an objective function f and a set of vectors % in X as input. Here, f should be a function handle that supports % the following usage: % % [v, g] = f(x); % % Here, f returns the objective value and the gradient at x. % % Supppose the input dimension for f is d, and there are n check % points. Then X should be a matrix of size d x n, with each column % being a test vector. % % This function will compute the gradient of f at these test vectors % and compare them with those yielded by finite difference % approximation. In addition, one can specify h, which is the % difference value used in approximation. By default, it is 1e-5. % % In the output, r1 is a vector of size 1 x n. In particular, r1(i) % is the norm of the difference between the gradient yielded by f % and that by approximation. % % [r1, r2] = check_deriv(f, X); % [r1, r2] = check_deriv(f, X, h); % % This statement also checks the Hessian matrices. Here, f should % support the following usage: % % [v, g, H] = f(x); % % Here, f returns the objective value, the gradient, as well as the % Hessian matrix at x. % % In the output, r1 gives the norm of difference between gradients, % while r2 gives the norm of difference between Hessian matrices. % % History % ------- % - Created by Dahua Lin, on Jan 24, 2011 % %% verify input arguments if ~isa(f, 'function_handle') error('check_deriv:invalidarg', 'f should be a function handle.'); end if ~(isfloat(X) && ndims(X) == 2) error('check_deriv:invalidarg', 'X should be a numeric matrix.'); end if nargin < 3 h = 1e-5; else if ~(isfloat(h) && isscalar(h) && h > 0) error('check_deriv:invalidarg', 'h should be a positive scalar.'); end end %% main n = size(X, 2); r1 = zeros(1, n); if nargout < 2 for i = 1 : n x = X(:,i); [v, g] = f(x); %#ok<ASGLU> ga = approx_deriv(f, x, h); r1(i) = norm(g - ga); end else r2 = zeros(1, n); for i = 1 : n x = X(:,i); [v, g, H] = f(x); %#ok<ASGLU> [ga, Ha] = approx_deriv(f, x, h); r1(i) = norm(g - ga); r2(i) = norm(H - Ha); end end
zzhangumd-smitoolbox
optim/nonlin/check_deriv.m
MATLAB
mit
2,476
function [x, info] = newtonfmin(f, x0, varargin) % Perform unconstrained minimization using Newton's method % % x = newtonfmin(f, x0, ...); % solves a (local) minima of f using standard Newton's method. % Here, f is the objective function that supports the following % usage: % % [v, g, H] = f(x); % % In the output, v is the function value evaluated at x, g and H % are respectively the gradient and Hessian. % % Note that H need not to be a true Hessian matrix, the function % just uses it as H \ g to derive the updating direction. Therefore, % any object that supports left matrix division is fine. % % If the option 'DirectNewton' is set to true, then f should support % % [v, dx] = f(x); % % Here, dx is the Newton direction (-H\g) evaluated at x. % This is useful when there is some structure of H and g such that % dx can be evaluated more efficiently with special implementation. % % x0 is the initial guess of the solution. % % One can also specify following options through name/value pairs. % % - MaxIter: the maximum number of iterations {30} % - TolFun: the termination tolerance of objective value change {1e-9} % - TolX: the termination tolerance of solution change {1e-7} % - Display: the level of display {'none'}|'proc'|'iter' % - DirectNewton: whether f directly outputs the newton direction % (-H\g) as the second argument. {false} % % The function returns the optimized solution. % % [x, info] = newtonfmin(f, x0, ...); % additionally returns the information of the solution. Here, info % is a struct with the following fields: % % - FunValue: the objective function value % - LastChange: the objective value change at last step % - LastMove: the solution change at last step % - IsConverged: whether the procedure converges % - NumIters: the number of elapsed iterations % % options = newtonfmin('options'); % gets the default options struct. % % History % ------- % - Created by Dahua Lin, on Aug 3, 2010 % - Modified by Dahua Lin, on Aug 7, 2010 % - use monitor to replace display level. % - Modified by Dahua Lin, on Jan 5, 2010 % - change the way of option setting % - Modified by Dahua Lin, on April 23, 2011 % - support DirectNewton. % %% check options if nargin == 3 && isstruct(varargin{1}) options = varargin{1}; else options = struct('MaxIter', 30, 'TolFun', 1e-9, 'TolX', 1e-7); if nargin == 1 && strcmpi(f, 'options') x = options; return; end options = smi_optimset(options, varargin{:}); end omon_level = 0; if isfield(options, 'Monitor') omon = options.Monitor; omon_level = omon.level; end if isfield(options, 'DirectNewton') dnewton = options.DirectNewton; else dnewton = false; end %% main x = x0; converged = false; it = 0; beta = 0.5; minstep = 0.5 * options.TolFun; if omon_level >= optim_mon.ProcLevel omon.on_proc_start(); end total_fcnt = 0; while ~converged && it < options.MaxIter it = it + 1; if omon_level >= optim_mon.IterLevel omon.on_iter_start(it); end if ~dnewton [v0, g, H] = f(x); step = - (H \ g); else [v0, step] = f(x); end [x, v, dx, fcnt] = linesearch(f, x, v0, step, beta, minstep); ch = v - v0; nrm_dx = norm(dx); converged = abs(ch) < options.TolFun && nrm_dx < options.TolX; total_fcnt = total_fcnt + (fcnt + 1); if omon_level >= optim_mon.IterLevel itstat = struct( ... 'FunValue', v, ... 'FunChange', ch, ... 'FunEvals', total_fcnt, ... 'Move', dx, ... 'MoveNorm', nrm_dx, ... 'IsConverged', converged); omon.on_iter_end(it, itstat); end end if nargout >= 2 || omon_level >= optim_mon.ProcLevel info = struct( ... 'FunValue', v, ... 'LastChange', ch, ... 'LastMove', dx, ... 'IsConverged', converged, ... 'NumIters', it); end if omon_level >= optim_mon.ProcLevel omon.on_proc_end(info); end
zzhangumd-smitoolbox
optim/nonlin/newtonfmin.m
MATLAB
mit
4,318
function [x, flag] = lincg(A, b, x0, tol, max_iter) %LINCG Solves a linear equation using conjugate gradient % % x = LINCG(A, b, x0); % x = LINCG(A, b, x0, tol); % x = LINCG(A, b, x0, tol, max_iter); % % solves a linear equation A * x = b using conjugate gradient % method. % % Input arguments: % - A: the linear coefficient matrix, or it can be a % function handle such that A(x) yields A * x. % - b: the vector on the right hand side of the equation % - x0: initial guess of the solution % - tol: the tolerance of residue norm at convergence % (when omitted, tol = 1e-6 by default) % - max_iter: the maximum number of iterations % (when omitted, max_iter = 100 by default) % % Output arguments: % - x: the solution % % [x, flag] = LINCG( ... ); % additionally returns the flag about the result of the solution. % Here is the list of flag meanings: % 0: the algorithm converges to the desired tolerance % 1: the algorithm iterates max_iter times but have not converged. % 2: early termination due to numerical issues % % Created by Dahua Lin, on Oct 31, 2011 % %% verify input arguments if isnumeric(A) if ~(isfloat(A) && ndims(A) == 2 && isreal(A) && size(A,1) == size(A,2)) error('lincg:invalidarg', 'A should be a real matrix.'); end n = size(A, 1); is_fun = 0; elseif isa(A, 'function_handle') n = 0; % indicate it is unknown from A is_fun = 1; end if ~(isfloat(b) && ndims(b) == 2 && size(b,2) == 1 && isreal(b) && ~issparse(b)) error('lincg:invalidarg', 'b should be a non-sparse real vector.'); end if n > 0 if size(b,1) ~= n error('lincg:invalidarg', 'The dimensions of A and b are inconsistent.'); end else n = size(b, 1); end if ~(isfloat(x0) && isequal(size(x0), [n 1]) && isreal(x0) && ~issparse(x0)) error('lincg:invalidarg', 'x0 should be a non-sparse real vector.'); end if nargin < 4 tol = 1e-6; else if ~(isfloat(tol) && isscalar(tol) && isreal(tol) && tol > 0) error('lincg:invalidarg', 'tol should be a positive real value.'); end end if nargin < 5 max_iter = 100; else if ~(isnumeric(max_iter) && isscalar(max_iter) && ... max_iter == fix(max_iter) && max_iter >= 1) error('lincg:invalidarg', 'max_iter should be a positive integer.'); end end %% main x = x0; if is_fun r = b - A(x); else r = b - A * x; end p = r; k = 0; converged = false; s = r' * r; while k < max_iter k = k + 1; if is_fun z = A(p); else z = A * p; end alpha = s / (p' * z); x = x + alpha * p; r = r - alpha * z; s_pre = s; s = r' * r; if sqrt(s) < tol converged = true; break; end beta = s / s_pre; p = r + beta * p; end if converged flag = 0; else flag = 1; end
zzhangumd-smitoolbox
optim/nonlin/lincg.m
MATLAB
mit
3,067
function f = comb_objfun(varargin) %COMB_OBJFUN Linear combination of objective functions % % An objective function f is a function that support the following use: % % (1) v = f(x); % (2) [v, g] = f(x); (optional) % (3) [v, g, H] = f(x); (optional) % % Here, x is a feasible solution, and v, g, H are respective the % function value, gradient, and Hessian matrix evaluated at x. % % % f = comb_objfun(c1, f1); % returns an objective function f, which is equivalent to c1 * f1. % % f = comb_objfun(c1, f1, c2, f2); % returns an objective function f, as c1 * f1 + c2 * f2 % % f = comb_objfun(c1, f1, c2, f2, c3, f3, ...); % returns an objective function f, as a linear combination of % multiple objective functions. % %% verify input arguments if isempty(varargin) error('comb_objfun:invalidarg', 'There is no input to comb_objfun'); end coeffs = varargin(1:2:end); funs = varargin(2:2:end); n = numel(coeffs); if ~(numel(funs) == n && ... all(cellfun(@(x) isfloat(x) && isscalar(x), coeffs)) && ... all(cellfun(@(f) isa(f, 'function_handle'), funs)) ) error('comb_objfun:invalidarg', 'The inputs to comb_objfun are invalid.'); end %% main if n == 1 c1 = coeffs{1}; f1 = funs{1}; f = @(x) comb_objfun1(x, c1, f1); elseif n == 2 c1 = coeffs{1}; c2 = coeffs{2}; f1 = funs{1}; f2 = funs{2}; f = @(x) comb_objfun2(x, c1, f1, c2, f2); else c = vertcat(coeffs{:}); f = @(x) comb_objfun_multi(x, c, funs); end %% objective functions function [v, g, H] = comb_objfun1(x, c1, f1) nout = nargout; if nout <= 1 v = c1 * f1(x); elseif nout == 2 [v1, g1] = f1(x); v = c1 * v1; g = c1 * g1; elseif nout == 3 [v1, g1, H1] = f1(x); v = c1 * v1; g = c1 * g1; H = c1 * H1; end function [v, g, H] = comb_objfun2(x, c1, f1, c2, f2) nout = nargout; if nout <= 1 v = c1 * f1(x) + c2 * f2(x); elseif nout == 2 [v1, g1] = f1(x); [v2, g2] = f2(x); v = c1 * v1 + c2 * v2; g = c1 * g1 + c2 * g2; elseif nout == 3 [v1, g1, H1] = f1(x); [v2, g2, H2] = f2(x); v = c1 * v1 + c2 * v2; g = c1 * g1 + c2 * g2; H = c1 * H1 + c2 * H2; end function [v, g, H] = comb_objfun_multi(x, c, funs) nout = nargout; m = numel(funs); if nout <= 1 f1 = funs{1}; v = c(1) * f1(x); for k = 2 : m fk = funs{k}; v = v + c(k) * fk(x); end elseif nout == 2 f1 = funs{1}; [v1, g1] = f1(x); v = c(1) * v1; g = c(1) * g1; for k = 2 : m fk = funs{k}; [vk, gk] = fk(x); v = v + c(k) * vk; g = g + c(k) * gk; end elseif nout == 3 f1 = funs{1}; [v1, g1, H1] = f1(x); v = c(1) * v1; g = c(1) * g1; H = c(1) * H1; for k = 2 : m fk = funs{k}; [vk, gk, Hk] = fk(x); v = v + c(k) * vk; g = g + c(k) * gk; H = H + c(k) * Hk; end end
zzhangumd-smitoolbox
optim/nonlin/comb_objfun.m
MATLAB
mit
2,953
function modules = smi_modules() % Get modules information of SMI toolbox % % smi_modules(); % prints information about modules of SMI toolbox. % % modules = smi_modules(); % get a list of module information. % % modules is an array of structs, of which each element corresponds % to a particular module. % % The struct has the following fields: % - name: the name of the module. % - summary: a brief description that summarizes the contents % of the module. % - depends: the dependent modules % - subpaths: the path (relative to the root of smitoolbox) % of each directory for this module. % - mex: the list of mex targets % % Remarks % ------- % This function reads all information from the configuration % file: smi_modules.cfg. % % Created by Dahua Lin, on Nov 10, 2010 % %% read file cdir = fileparts(mfilename('fullpath')); cfgfile = fullfile(cdir, 'smi_modules.cfg'); if ~exist(cfgfile, 'file') error('smi_modules:filenotfound', 'smi_modules.cfg is not found'); end fid = fopen(cfgfile, 'r'); lines = textscan(fid, '%s', 'delimiter', '\n'); lines = lines{1}; fclose(fid); %% read configuration nm = 0; cmodule = []; n = length(lines); i = 1; while i <= n; % read current line line = strtrim(lines{i}); if isempty(line) || line(1) == '#' i = i + 1; continue; end % parse the current line if line(1) == '[' && line(end) == ']' % module head % add current module to list if ~isempty(cmodule) nm = nm + 1; modules{nm, 1} = cmodule; %#ok<AGROW> end % start a new module name = strtrim(line(2:end-1)); if isempty(name) parse_error(i, 'Invalid module head'); end cmodule = struct( ... 'name', name, ... 'summary', [], ... 'depends', [], ... 'subpaths', [], ... 'mex', []); i = i + 1; elseif line(1) == ':' % summary [cmodule.summary, i] = read_summary(lines, i); elseif line(1) == '.' % items starts [name, items, i] = read_items(lines, i); switch (name) case {'depends', 'subpaths' } cmodule.(name) = items; case 'mex' nmex = numel(items); cmodule.mex = cell(nmex, 1); for j = 1 : nmex cmodule.mex{j} = process_mex(items{j}); end cmodule.mex = vertcat(cmodule.mex{:}); end end end if ~isempty(cmodule) nm = nm + 1; modules{nm, 1} = cmodule; end modules = vertcat(modules{:}); %% sub functions for parsing function [s, i] = read_summary(lines, i) line = lines{i}; s{1} = strtrim(line(2:end)); n = 1; i = i + 1; while i < numel(lines) line = strtrim(lines{i}); if ~isempty(line) n = n + 1; s{n} = [' ', line]; %#ok<AGROW> i = i + 1; else break; end end s = [s{:}]; function [name, items, i] = read_items(lines, i) [name, remain] = strtok(lines{i}, '='); name = strtrim(name(2:end)); remain = strtrim(remain(2:end)); if isempty(name) || isempty(remain) parse_error(i, 'Invalid line in starting an item.'); end if remain(1) ~= '{' parse_error(i, 'Invalid line in starting an item.'); end remain = remain(2:end); if ~isempty(remain) && remain(end) == '}' remain = strtrim(remain(1:end-1)); is_end = true; else is_end = false; end rs = {remain}; while ~is_end i = i + 1; remain = strtrim(lines{i}); while (isempty(remain) || remain(1) == '#') && i < numel(lines) i = i + 1; remain = strtrim(lines{i}); end if isempty(remain) break; else if remain(end) == '}' remain = strtrim(remain(1:end-1)); is_end = true; else is_end = false; end rs = [rs; {remain}]; %#ok<AGROW> end end i = i + 1; for k = 1 : numel(rs) r = rs{k}; if ~isempty(r) toks = textscan(r, '%s', 'delimiter', ','); toks = toks{1}; else toks = {}; end rs{k} = toks; end items = vertcat(rs{:}); function r = process_mex(line) [tname, remain] = strtok(line, ':'); tname = strtrim(tname); remain = strtrim(remain(2:end)); if isempty(remain) error('smi_module:parseerror', 'Invalid line for mex target %s', tname); end srcs = textscan(remain, '%s').'; r.name = tname; r.sources = srcs{1}; %% Auxiliary functions function parse_error(i, msg) error('smi_module:parseerror', ... 'Parse error at line %d: %s', i, msg);
zzhangumd-smitoolbox
tbman/smi_modules.m
MATLAB
mit
4,910
function smi_build_mex(varargin) % Re-build all mex files in the toolbox % % smi_build_mex; % smi_build_mex name1 name2 ... % %% main mdls = smi_modules; bopts = {'-O'}; % get environment bcslib_home = getenv('BCSLIB_HOME'); if isempty(bcslib_home) error('smi_build_mex:enverror', ... 'Cannot find BCS Lib. Please add environment variable BCSLIB_HOME.'); end bopts = [bopts, {['-I' bcslib_home]}]; % get the list S = vertcat(mdls.mex); % filter the list if ~isempty(varargin) [tf, si] = ismember(varargin, {S.name}); if ~all(tf) error('smi_build_mex:invalidtarget', ... '%s is not a valid mex target.', ... varargin{find(~tf, 1)}); end S = S(si); end n = length(S); % build rootdir = fileparts(fileparts(mfilename('fullpath'))); for i = 1 : n s = S(i); fprintf('Building %s ...\n', s.name); outdir = fullfile(rootdir, fileparts(s.sources{1})); sources = cellfun(@(s) fullfile(rootdir, s), s.sources, 'UniformOutput', false); args = [bopts, {'-outdir', outdir}, sources]; cmd = joinstr('mex', args{:}); fprintf('%s\n', cmd); fprintf('\n'); mex(args{:}); fprintf('\n'); end %% parse function function s = joinstr(varargin) n = length(varargin); terms = cell(1, 2 * n - 1); terms(1:2:end) = varargin; terms(2:2:end) = {' '}; s = [terms{:}];
zzhangumd-smitoolbox
tbman/smi_build_mex.m
MATLAB
mit
1,404
function smi_add_path() % The function to add smitoolbox to MATLAB search paths % % smi_add_path; % % Note that this function does not save path permantly. To do so, % one can call savepath. % %% main mdls = smi_modules; rdir = fileparts(fileparts(mfilename('fullpath'))); subpaths = ['tbman'; vertcat(mdls.subpaths)]; fpaths = cellfun(@(p) fullfile(rdir, p), subpaths, 'UniformOutput', false); addpath(fpaths{:});
zzhangumd-smitoolbox
tbman/smi_add_path.m
MATLAB
mit
427
function info = smi_test(module, suitename) % Performs unit testing for SMI modules % % info = smi_test(module, suitename); % info = smi_test(module, suitenames); % Runs a test suite or a collection of suites under a module. % % Here, module and suitename are both strings, and suitenames % is a cell array of strings. % % In the output, info is a struct (or struct array, if for % a collection of multiple suites), which has the following field: % % - 'module': the module name % - 'name': the suite name % - 'classname': the class name % - 'ntotal': the total number of cases % - 'nfailed': the number of failed cases % - 'failed_cases': the cell array of names of failed cases % % names = smi_test(module, 'get.suitenames'); % Gets all test suite names under a module. % % History % ------- % - Created by Dahua Lin, on Sep 3, 2011 % %% verify input arguments if ~isvarname(module) error('smi_test:invalidarg', 'The module name is not valid.'); end snames_all = get_suitenames(module); if nargin < 2 use_all = 1; snames = snames_all; get_attr = []; else use_all = 0; if ischar(suitename) if strcmpi(suitename, 'get.suitenames'); get_attr = 'suitenames'; snames = []; else snames = {suitename}; get_attr = []; end elseif iscellstr(suitename) snames = suitename; get_attr = []; else error('smi_test:invalidarg', ... 'The suitename should be either a string or a cell array of strings.'); end end nsuites = numel(snames); %% main if ~isempty(get_attr) info = snames_all; return; end if ~use_all for i = 1 : nsuites sname = snames{i}; if ~ismember(sname, snames_all) error('smi_test:invalidarg', ... 'There is no test suite named %s for module %s.', ... sname, module); end end end info.module = module; info.name = []; info.classname = []; info.ntotal = 0; info.nfailed = 0; info.failed_cases = {}; if nsuites > 1 info = repmat(info, [nsuites, 1]); end fid = 1; for i = 1 : nsuites sname = snames{i}; fprintf(fid, 'Test suite [%d / %d]: %s\n', i, nsuites, snames{i}); fprintf(fid, '====================================\n'); clsname = ['tsuite_' sname]; tobj = feval(clsname); Ms = methods(tobj); cases = cell(numel(Ms), 1); nc = 0; for j = 1 : numel(Ms) cmethod = Ms{j}; if length(cmethod) >= 6 && strcmp(cmethod(1:5), 'test_') nc = nc + 1; cases{nc} = cmethod; end end fcases = {}; for j = 1 : nc cmethod = cases{j}; fprintf(fid, ' running %s ...\n', cmethod); try feval(cmethod, tobj); catch err fcases = [fcases; {cmethod}]; print_error(fid, cmethod, err); end end fprintf(' --------------------------------\n'); if isempty(fcases) fprintf(' All %d cases passed\n', nc); else fprintf(' In all %d cases, %d failed\n', nc, numel(fcases)); end fprintf(fid, '\n'); % store information info(i).name = sname; %#ok<*AGROW> info(i).classname = clsname; info(i).ntotal = nc; info(i).nfailed = numel(fcases); info(i).failed_cases = fcases; end %% Auxiliary functions function sall = get_suitenames(module) % retrieve suite names smiroot = fileparts(fileparts(mfilename('fullpath'))); moduleroot = fullfile(smiroot, module); if exist(moduleroot, 'dir') testdir = fullfile(moduleroot, 'tests'); sall = {}; if exist(testdir, 'dir') fns = dir(fullfile(testdir, 'tsuite_*.m')); if ~isempty(fns) ns = numel(fns); sall = cell(ns, 1); for i = 1 : numel(fns) [pstr, cname] = fileparts(fns(i).name); %#ok<ASGLU> if ~exist(cname, 'class') error('smi_test:rterror', ... '%s is not a class or is not in search-path.', cname); end sall{i} = cname(8:end); end end end if isempty(sall) warning('smi_test:notests', ... 'There are no testes for module %s', module); end else error('smi_test:nonexist', ... 'Cannot find the module named %s', module); end function print_error(fid, cmethod, err) % print an error fprintf(fid, ' %s failed: %s\n', cmethod, err.message); fprintf(fid, ' Stack: \n'); m = numel(err.stack) - 1; % ignore the smi_test function for i = 1 : m s = err.stack(i); [pstr, fname, fext] = fileparts(s.file); %#ok<ASGLU> fprintf(fid, ' %s (line %d)\n', [fname fext], s.line); end
zzhangumd-smitoolbox
tbman/smi_test.m
MATLAB
mit
4,978
function S = pca_std(X, pd, varargin) %PCA_STD Standard principal component analysis % % S = PCA_STD(X); % S = PCA_STD(X, pd, ...); % % trains a standard principal component analysis model based on % the data given as columns of X. % % Suppose there are n samples in d-dimensional space, then X should % be a d x n matrix with each column representing a sample. % % The dimension of the principal subspace is determined in different % ways, depending on the 2nd argument pd: % % - if pd is a positive integer, then the dimension of the principal % subspace is pd. Note that in this case, pd should have % pd <= min(d, n-1), where n is the number of columns in X. % % - if 0 < pd < 1, then it determines a minimum subspace that % preserves at least ratio pd of the total variance. % (e.g if pd = 0.9, then it preserves 90% of the variance). % % - pd can be [] (empty) or omitted, then it determines % a subspace that preserves 99.9% of the variance. % (eqivalent to setting pd to 0.999). % % - pd can be a function handle that supports the % usage as follows: % % d = pd(eigvals); % % It takes as input a sorted (in descending order) % vector of eigenvalues, and returns the dimension % of the principal subspace. % % In the output, S is a struct with the following fields: % - tag: a string: 'pca-std' % - d: the dimension of the input space % - dp: the dimension of the principal subspace % - B: the basis matrix [size: d x dp] % - pevs: the eigenvalues of the principal subspace [1 x dp] % - res: the residue energy (sum of residual eigenvalues) % % In addition, one can specify the following options % in name/value pairs (optionally). % % - 'method': the method to train PCA model, which % can be either of the following strings: % - 'auto': automatically decide a proper % method. (default) % - 'std': the standard method, which % solves the eigen-problem of X*X' % - 'svd': the method based on SVD % decompostion. % - 'trans': the method based on solves % the eigen-problem of X'*X, % which is efficient when n < d. % % - 'weights': The weights of samples. If this option % is specified, then the model will be % trained on weighted samples. % % The weights should be a 1 x n row % vector, with weights(i) being the % weight of the i-th sample. % % - 'center': The pre-computed center of the data % in the input space. % % It can be either a d x 1 vector, or 0. % % If not specified, the sample mean will % serve as the center. % % History % ------- % - Created by Dahua Lin, on May 30, 2008 % - Modified by Dahua Lin, on Jun 6, 2008 % - Modified by Dahua Lin, on Nov 20, 2010 % %% parse and verify input arguments % verify X if ~(isfloat(X) && isreal(X) && ndims(X) == 2) error('pca_std:invalidarg', 'X should be a real matrix.'); end [d, n] = size(X); % verify pd dim_ub = min(d, n-1); if nargin < 2 || isempty(pd) pd = 0.999; else if (isnumeric(pd) && isscalar(pd) && pd > 0) || ... isa(pd, 'function_handle') if isnumeric(pd) && pd >= 1 if ~(pd == fix(pd) && pd <= dim_ub) error('pca_std:invalidarg', ... 'When pd >= 1, pd should be an integer and pd <= min(d, n-1)'); end end else error('pca_std:invalidarg', 'pd is invalid.'); end end [method, weights, cen] = parse_options(varargin); %% pre-process samples % shift-center if isempty(cen) if isempty(weights) cen = sum(X, 2) / n; else cen = X * (weights' / sum(weights)); end end if ~isequal(cen, 0) X = bsxfun(@minus, X, cen); end % weight samples if isempty(weights) tw = n; else tw = sum(weights); X = bsxfun(@times, X, weights); end %% perform spectral analysis % decide method if strcmp(method, 'auto') if n^2 * (d + n) < d^3 method = 'trans'; else method = 'std'; end end % compute switch method case 'std' M = X * X'; M = 0.5 * (M + M'); [U, D] = eig(M); clear M; devs = diag(D); clear D; case 'trans' M = X' * X; M = 0.5 * (M + M'); [V, D] = eig(M); clear M; devs = diag(D); clear D; U = X * V; clear V; U = bsxfun(@times, U, 1./sqrt(sum(U.*U, 1))); case 'svd' [U, D] = svd(X, 'econ'); devs = diag(D) .^ 2; clear D; end % re-arrange in descending order [sevs, si] = sort(devs, 1, 'descend'); sevs = max(sevs(1:dim_ub), 0); U = U(:, si(1:dim_ub)); sevs = sevs * (1 / tw); tvar = sum(sevs); % select principal subspace if isnumeric(pd) if pd >= 1 p = pd; else vr = cumsum(sevs) * (1 / tvar); p = find(vr >= pd, 1); if isempty(p); p = dim_ub; end end else p = pd(sevs); end if p < dim_ub pevs = sevs(1:p); Up = U(:, 1:p); res = tvar - sum(pevs); else pevs = sevs; Up = U; res = 0; end % make output S.tag = 'pca-std'; [S.d, S.pd] = size(Up); S.B = Up; S.cen = cen; S.pevs = pevs.'; S.res = res; %% Sub functions function [method, weights, cen] = parse_options(params) % parse options % default options method = 'auto'; weights = []; cen = []; % parse options if ~isempty(params) names = params(1:2:end); values = params(2:2:end); nopts = numel(names); if ~(numel(values) == nopts && iscellstr(names)) error('pca_std:invalidsyntax', ... 'The name-value list is invalid.'); end for i = 1 : nopts name = lower(names{i}); v = values{i}; switch name case 'method' if ~(ischar(v) && ismember(v, {'auto','std','svd','trans'})) error('pca_std:invalidoption', ... 'The method option value should be a string.'); end method = v; case 'weights' if ~(isfloat(v) && isvector(v) && numel(v) == n) error('pca_std:invalidoption', ... 'The weights should be a numeric vector of length n.'); end if size(v, 1) > 1; v = v.'; end weights = v; case 'center' if ~(isfloat(v) && isreal(v) && ... (isequal(v, 0) || isequal(size(v), [d 1]))) error('pca_std:invalidoption', ... 'The center should be either 0 or d x 1 real vector.'); end cen = v; otherwise error('pca_std:invalidoption', ... 'Unknown option %s for estimating PCA', name); end end end
zzhangumd-smitoolbox
classics/subspace/pca_std.m
MATLAB
mit
7,573
function W = cov_whiten(C, k, method, v) % Solves a whitening transform % % Given a Gaussian variable X with covariance C = U D U'. % Let W = D^{-1/2} * U', then WX has covarance I. % This transform W is called the whitening transform. % % W = cov_whiten(C); % W = cov_whiten(C, []); % W = cov_whiten(C, k); % % computes the whitening transform W from covariance matrix C. % Note that the rows of W are sorted in descending order of norm. % % The second argument that only the first k rows are kepts in W. % If it is empty or omitted, then all rows are retained. % % W = cov_whiten(C, k, 'bound', lb); % W = cov_whiten(C, k, 'reg', r); % % In practice, it is often the case that C is singular or % ill-conditioned. To handle this case, we provide two approaches: % % (1) bounding: bound the eigenvalues away from zero by force % all eigenvalues below thres = lb * max(eigenvalue) % to thres. If lb is omitted, default lb = 1e-3. % % (2) regularization: add r * max(eigenvalue) to all diagonal % entries to C. If r is omitted, default r = 1e-3. % % Remarks % ------- % - The caller should ensure that the input matrix C is positive % semi definite. % % Created by Dahua Lin, on Nov 23, 2010 % %% verify input argument d = size(C, 1); if ~(isfloat(C) && ndims(C) == 2 && isreal(C) && size(C,2) == d) error('cov_whiten:invalidarg', ... 'C should be a real square matrix.'); end if nargin < 2 || isempty(k) k = d; else if ~(isnumeric(k) && isscalar(k) && k == fix(k) && k >= 1 && k <= d) error('cov_whiten:invalidarg', ... 'k should be a positive integer scalar in [1, d].'); end end if nargin < 3 method = []; else if ~ischar(method) error('cov_whiten:invalidarg', 'The 3rd argument should be a string.'); end switch method case 'bound' if nargin < 4 v = 1e-3; end case 'reg' if nargin < 4 v = 1e-3; end otherwise error('cov_whiten:invalidarg', ... 'The 3rd argument can only be ''bound'' or ''reg''.'); end end %% main [U, D] = eig(C); evs = diag(D); if ~isempty(method) switch method case 'bound' t = max(evs) * v; evs(evs < t) = t; case 'reg' r = max(evs) * v; evs = evs + r; end end w = 1 ./ sqrt(evs); [w, si] = sort(w, 1, 'descend'); if k < d w = w(1:k); si = si(1:k); end U = U(:, si); W = bsxfun(@times, w, U');
zzhangumd-smitoolbox
classics/subspace/cov_whiten.m
MATLAB
mit
2,741
function ica_demo(method) % A simple program to demonstrate how ICA is used to decouple noisy signals % % ica_demo(method); % % You can choose the method of running ICA: 'defl' or 'symm'. % % Created by Dahua Lin, on Dec 31, 2011 %% prepare signals t = (0 : 0.02 : 2 * pi).'; d = length(t); n = 500; X1 = bsxfun(@plus, sin(t), randn(d, n) * 1e-1); X2 = bsxfun(@plus, cos(t), randn(d, n) * 1e-1); X = [X1 X2]; sX = sqrt(mean(sum(X.^2, 1))); %% run Fast ICA W = ica_fast(X, 2, [], 'method', method, 'verbose', true); %% visualize figure; plot(t, X, 'g.', 'MarkerSize', 3); hold on; plot(t, W * sX, 'r-', 'LineWidth', 2);
zzhangumd-smitoolbox
classics/subspace/ica_demo.m
MATLAB
mit
635
function [W, H, objv, converged] = nnmf_std(X, r, W0, varargin) %NNMF_STD Non-Negative Matrix Factorization % % [W, H] = NNMF_STD(X, r, W0, ...); % [W, H, objv, converged] = NNMF_STD( ... ); % % Perform Non-negative matrix factorization using standard methods. % % Let X be an m x n matrix, then the goal is to seek two factor % matrices W (of size m x r) and H (of size r x n), such that % W * H is close to X, under some criterion. % % Input arguments: % - X: The input matrix of size m x n % - r: The rank of the approximation (r <= min(m, n)) % - W0: The initial guess of W (empty or an m x r matrix) % % If W0 is left empty, it will be initialized randomly. % % Output arguments: % - W: The solved W-matrix % - H: The solved H-matrix % - objv: The objective value for the solution % - converged: whether the optimization converges % % % One can specify other options to control the algorithm, in form % of name/value pairs: % % - 'method': The method used to solve the problem % - 'als': alternate convex optimization % (only for the case with obj='euc') % - 'mult': multiplicative update % default: 'als' when obj is 'euc', 'mult' otherwise. % % - 'obj': The objective type % - 'euc': Euclidean mean squared error (default) % - 'kl': (average) K-L divergence % % - 'maxiter': The maximum number of iterations (default = 100) % % - 'tol': The tolerance of change of W upon convergence. % (default = 1e-6) % % - 'nrm': The way to normalize the results % - 'WL1': The L1-norm of each column of W is % normalized to one (default) % - 'WL2': The L2-norm of each column of W is % normalized to one % % - 'display' The level of display % - 'off': No display (default) % - 'final': Only display upon completion % - 'iter': Display information for each iteration % % Created by Dahua Lin, on Feb 17, 2012 % %% verify input arguments if ~(isfloat(X) && isreal(X) && ismatrix(X)) error('nnmf_std:invalidarg', 'X should be a real matrix.'); end [m, n] = size(X); if ~(isnumeric(r) && isscalar(r) && r >= 1 && r <= min(m, n)) error('nnmf_std:invalidarg', ... 'r should be a positive integer with r <= min(m, n).'); end if nargin < 3 || isempty(W0) W0 = []; else if ~(isfloat(W0) && isreal(W0) && isequal(size(W0), [m r])) error('nnmf_std:invalidarg', ... 'W0 should be a real matrix of size m x r.'); end end [method, obj, maxiter, tol, nrm, displevel] = parse_options(varargin); %% main % initialize if isempty(W0) W0 = rand(m, r); end wnrms = col_norms(W0, nrm); W = bsxfun(@times, W0, 1 ./ wnrms); if method == 2 H = (W' * W) \ (W' * X); H(H < 0) = 0; end % main loop converged = false; t = 0; if displevel < 2 objv = []; else objv = nan; end if displevel >= 2 fprintf('%6s %16s (changes) %8s\n', ... 'Iter', 'objective', 'ch.W'); fprintf('--------------------------------------------------------\n'); end epv = 1e-12; while ~converged && t < maxiter t = t + 1; Wpre = W; % do updating if method == 1 % als if obj == 1 % mse H = (W' * W) \ (W' * X); H(H < 0) = 0; W = (X * H') / (H * H'); W(W < 0) = 0; else % kl W = solve_W_kl(X, H); H = solve_H_kl(X, W); end else % mult if obj == 1 H = H .* ((W' * X) ./ ((W' * W) * H + epv)); W = W .* (X * H') ./ (W * (H * H') + epv); else C = W' * (X ./ (W * H + epv)); H = H .* bsxfun(@times, C, 1 ./ sum(W, 1)'); C = (X ./ (W * H + epv)) * H'; W = W .* bsxfun(@times, C, 1 ./ sum(H, 2)'); end end % normalize wnrms = col_norms(W, nrm); W = bsxfun(@times, W, 1 ./ wnrms); H = bsxfun(@times, H, wnrms.'); % determine convergence chW = norm(W - Wpre, inf); converged = abs(chW) < tol; if displevel >= 2 objv_pre = objv; objv = eval_objv(X, W, H, obj); ch = objv - objv_pre; fprintf('%6d %15.6f (%10.3e) %10.3e\n', ... t, objv, ch, chW); end end if nargout >= 3 && isempty(objv) objv = eval_objv(X, W, H, obj); end if displevel >= 1 if converged fprintf('NNMF converged (with %d iters)\n\n', t); else fprintf('NNMF did not converge (with %d iters)\n\n', t); end end %% Auxiliary functions function v = col_norms(W, nrm) % calculate per-column norms if nrm == 1 v = sum(W, 1); else v = sqrt(sum(W.^2, 1)); end function v = eval_objv(X, W, H, obj) % evaluate objective function Y = W * H; if obj == 1 v = norm(X - Y, 'fro')^2 / numel(X); else si = find(X > 0); v = sum(X(si) .* (log(X(si)) - log(Y(si)))) + sum(Y(:) - X(:)); v = v / numel(X); end %% Option parsing function [method, obj, maxiter, tol, nrm, displevel] = parse_options(params) % parse options method = []; obj = 1; maxiter = 100; tol = 1e-6; nrm = 1; displevel = 0; if ~isempty(params) names = params(1:2:end); vals = params(2:2:end); if ~(numel(names) == numel(vals) && iscellstr(names)) error('nnmf_std:invalidarg', 'Syntax errors for the name/value pairs.'); end for i = 1 : numel(names) cn = names{i}; cv = vals{i}; switch lower(cn) case 'method' if ~ischar(cn) error('nnmf_std:invalidarg', ... 'The method should be a string'); end switch cv case 'als' method = 1; case 'mult' method = 2; otherwise error('nnmf_std:invalidarg', ... 'The method %s is invalid', cv); end case 'obj' if ~ischar(cn) error('nnmf_std:invalidarg', ... 'The value of obj should be a string'); end switch cv case 'euc' obj = 1; case 'kl' obj = 2; otherwise error('nnmf_std:invalidarg', ... 'The value of obj %s is invalid', cv); end case 'maxiter' if ~(isnumeric(cv) && isscalar(cv) && cv >= 1) error('nnmf_std:invalidarg', ... 'The maxiter should be a positive scalar.'); end maxiter = cv; case 'tol' if ~(isfloat(cv) && isreal(cv) && isscalar(cv) && cv > 0) error('nnmf_std:invalidarg', ... 'The tol should be a positive real scalar.'); end tol = cv; case 'nrm' if ~ischar(cn) error('nnmf_std:invalidarg', ... 'The value of nrm should be a string'); end switch upper(cv) case 'WL1' nrm = 1; case 'WL2' nrm = 2; otherwise error('nnmf_std:invalidarg', ... 'The value of nrm %s is invalid', cv); end case 'display' if ~ischar(cn) error('nnmf_std:invalidarg', ... 'The value of display should be a string'); end switch cv case 'off' displevel = 0; case 'final' displevel = 1; case 'iter' displevel = 2; otherwise error('nnmf_std:invalidarg', ... 'The value of display: %s is invalid', cv); end end end end if isempty(method) method = obj; else if obj == 2 && method == 1 error('nnmf_std:invalidarg', ... 'The method als cannot be used when obj is ''kl''.'); end end
zzhangumd-smitoolbox
classics/subspace/nnmf_std.m
MATLAB
mit
9,289
function W = ica_fast(X, k, W0, varargin) %ICA_FAST Fast Independent Component Analysis (Fast ICA) % % W = ICA_FAST(X, k); % W = ICA_FAST(X, k, [], ...); % W = ICA_FAST(X, k, W0, ...); % % Performs Fast ICA on a given set of data. % % Input arguments: % - X: the sample matrix, where each column is a sample. % - k: the number of components to derive. % - W0: the initial guess of the weight matrix W. % % Output argument: % - W: the matrix comprised of weight vectors. Each column % of W is a weight vector, and the size of W is d x k. % % One can specify other options in form of name/value pairs to % control the algorithm. % % - 'method' The method to solve multiple weight vectors. % - 'defl': choose the vectors one by one % - 'symm': perform symmetric decorrelation % (default is 'defl') % % - 'g' the name of the nonlinearity function g: % - 'pow3': g(u)=u^3 % - 'tanh': g(u)=tanh(a*u) % - 'gauss': g(u)=u*exp(-a*u^2/2) % - 'skew': g(u)=u^2 % The default choice is 'pow3'. % % - 'gparam' the parameter (a) of the nonlinearity function. % (default value = 1) % % - 'tol' the tolerance of change at convergence. % (default = 1e-6) % % - 'maxiters' the maximum number of iterations (default = 200) % % - 'verbose' whether to show procedural information. % (default = false) % % Created by Dahua Lin, on Dec 31, 2012 % %% verify input arguments if ~(isfloat(X) && isreal(X) && ndims(X) == 2) error('ica_fast:invalidarg', 'X should be a real matrix.'); end d = size(X, 1); if ~(isnumeric(k) && isscalar(k) && k == fix(k) && k <= d) error('ica_fast:invalidarg', 'k should be a positive integer with k <= d.'); end if nargin >= 3 && ~isempty(W0) if ~(isfloat(W0) && isreal(W0) && isequal(size(W0), [d k])) error('ica_fast:invalidarg', 'W0 should be a d x k real matrix.'); end else W0 = []; end [use_symm, gfun, tol, maxiters, verbose] = getopts(varargin); %% main % initialize if isempty(W0) W = orth(randn(d, k)); else W = W0; end % main loop if verbose disp('Fast ICA Running:'); end if k == 1 if verbose fprintf('Solving single component ...\n'); end W = defl_optimize(X, W, [], gfun, maxiters, tol, verbose); else if use_symm if verbose fprintf('Solving all components with symmetric decorrelation ...\n'); end W = symm_optimize(X, W, gfun, maxiters, tol, verbose); else if verbose fprintf('Solving component %d ...\n', 1); end W(:,1) = defl_optimize(X, W(:,1), [], gfun, maxiters, tol, verbose); for i = 2 : k fprintf('Solving component %d ...\n', i); W(:,i) = defl_optimize(X, W(:,i), W(:,1:i-1), gfun, ... maxiters, tol, verbose); end end end if verbose disp('Fast ICA finished.'); end %% Core optimization routines function w = defl_optimize(X, w, B, gfun, maxiters, tol, verbose) % optimizing a particular w n = size(X, 2); t = 0; converged = false; if ~isempty(B) w = w - B * (B' * w); end w = w * (1 / norm(w)); while ~converged && t < maxiters t = t + 1; w_pre = w; [v, f] = gfun(w' * X); w = (X * v') * (1/n) - (sum(f) / n) * w; if ~isempty(B) w = w - B * (B' * w); end w = w * (1 / norm(w)); dev = norm(w - w_pre); converged = dev < tol; if verbose fprintf('\tIter %d: change = %.4g\n', t, dev); end end if verbose if converged fprintf('\tConverged.\n'); else fprintf('\tNOT converged.\n'); end end function W = symm_optimize(X, W, gfun, maxiters, tol, verbose) % optimizing the whole W in parellel n = size(X, 2); t = 0; converged = false; W = bsxfun(@times, W, 1 ./ sqrt(sum(W.^2, 1))); while ~converged && t < maxiters t = t + 1; W_pre = W; [V, F] = gfun(W' * X); W = (X * V') * (1/n) - bsxfun(@times, W, (sum(F,2) / n).'); [U,S,V] = svd(W, 0); %#ok<ASGLU> W = U * V'; dev = max(sqrt(sum((W - W_pre).^2, 1))); converged = dev < tol; if verbose fprintf('\tIter %d: change = %.4g\n', t, dev); end end if verbose if converged fprintf('\tConverged.\n'); else fprintf('\tNOT converged.\n'); end end %% nonlinearity functions (g) function [V, F] = nf_pow3(Y) V = Y.^3; F = 3 * (Y.^2); function [V, F] = nf_tanh(Y, a) if a == 1 AY = Y; else AY = a * Y; end V = tanh(AY); F = a ./ (cosh(AY) .^ 2); function [V, F] = nf_gauss(Y, a) E = exp((-a/2) * (Y.^2)); V = Y .* E; F = (1 - a * (Y.^2)) .* E; function [V, F] = nf_skew(Y) V = Y.^2; F = 2 * Y; %% option parsing function [use_symm, gfun, tol, maxiters, verbose] = getopts(params) use_symm = false; g = 'pow3'; a = 1; tol = 1e-6; maxiters = 200; verbose = false; if ~isempty(params) onames = params(1:2:end); ovals = params(2:2:end); for i = 1 : numel(onames) cn = onames{i}; cv = ovals{i}; switch cn case 'method' if ischar(cv) if strcmpi(cv, 'defl') use_symm = false; elseif strcmpi(cv, 'symm') use_symm = true; else error('ica_fast:invalidarg', ... 'Invalid method %s', cv); end else error('ica_fast:invalidarg', ... 'The method should be a string.'); end case 'g' if ischar(cv) g = lower(cv); else error('ica_fast:invalidarg', ... 'The value of the option g should be a string.'); end case 'gparam' if ~(isfloat(cv) && isscalar(cv) && isreal(cv)) error('ica_fast:invalidarg', ... 'The value of gparam should be a real scalar.'); end a = cv; case 'tol' if ~(isfloat(cv) && isscalar(cv) && isreal(cv) && cv > 0) error('ica_fast:invalidarg', ... 'The value of tol should be a positive real scalar.'); end tol = cv; case 'maxiters' if ~(isnumeric(cv) && isscalar(cv) && cv >= 1) error('ica_fast:invalidarg', ... 'The value of maxiters should be a number no less than 1.'); end maxiters = cv; case 'verbose' if ~(islogical(cv) && isscalar(cv)) error('ica_fast:invalidarg', ... 'The value of verbose should be a logical scalar.'); end verbose = cv; end end end switch g case 'pow3' gfun = @nf_pow3; case 'tanh' gfun = @(x) nf_tanh(x, a); case 'gauss' gfun = @(x) nf_gauss(x, a); case 'skew' gfun = @(x) nf_skew(x); otherwise error('ica_fast:invalidarg', ... 'Invalid g-function name %s', g); end
zzhangumd-smitoolbox
classics/subspace/ica_fast.m
MATLAB
mit
7,793
function [mu, Sw, Sb] = scattermat(X, K, L, w) % Compute scatter matrices for labeled Data % % [mu, Sw, Sb] = scattermat(X, K, L); % [mu, Sw, Sb] = scattermat(X, K, L, w); % % computes within-class (and between-class) scatter matrices % from labeled data. % % Inputs: % - X: a d x n matrix, with each column being a sample. % - K: the number of classes % - L: the 1 x n label vector. L(i) is the label of sample X(:,i), % whose value should be in {1, 2, ..., K}. % - w: the weights of samples (a vector of size 1 x n). % If omitted, all samples have the same weight. % % Outputs: % - mu: the means of the samples % - Sw: the within-class scatter matrix (i.e. pooled covariance) % - Sb: the between-class scatter matrix (i.e. covariance of mean) % % Created by Dahua Lin, on Nov 22, 2010. % %% verify input arguments if ~(isfloat(X) && isreal(X) && ndims(X) == 2) error('scattermat:invalidarg', 'X should be a real matrix.'); end [d, n] = size(X); if ~(isnumeric(K) && isscalar(K) && K == fix(K) && K >= 1) error('scattermat:invalidarg', 'K should be a positive integer scalar.'); end if ~(isnumeric(L) && isequal(size(L), [1 n])) error('scattermat:invalidarg', 'L should be a 1 x n numeric vector.'); end if nargin < 4 w = []; else if ~(isempty(w) || (isfloat(w) && isequal(size(w), [1 n]))) error('scattermat:invalidarg', 'w should be a 1 x n numeric vector.'); end end %% main % partition data G = intgroup(K, L); % compute mean mu = zeros(d, K); tw = zeros(1, K); if isempty(w) for k = 1 : K gk = G{k}; tw(k) = numel(gk); if tw(k) > 0 mu(:,k) = sum(X(:,gk), 2) * (1/tw(k)); end end else for k = 1 : K gk = G{k}; if ~isempty(gk) wk = w(gk); tw(k) = sum(wk); else tw(k) = 0; end if tw(k) > 0 mu(:,k) = X(:,gk) * (wk.' / tw(k)); end end end wa = sum(tw); % compute Sw Z = X - mu(:, L); if isempty(w) Sw = Z * Z'; else Sw = Z * bsxfun(@times, Z, w)'; Sw = 0.5 * (Sw + Sw'); end Sw = Sw * (1 / wa); if nargin < 3 return; end % compute Sb cw = tw / wa; mu0 = mu * cw'; Sb = mu * bsxfun(@times, mu, cw)' - mu0 * mu0'; Sb = 0.5 * (Sb + Sb');
zzhangumd-smitoolbox
classics/subspace/scattermat.m
MATLAB
mit
2,392
function c = fisherlda_binary(X, L, varargin) %FISHERLDA_BINARY Fisher's Linear Discriminant Analysis on two-classes % % c = FISHERLDA_BINARY(X, L ...); % performs two-class linear discrminant analysis (LDA). % % In the input, X is the data matrix, with each column being a % sample. Let the size of X be d x n, then there are n samples. % L should be a numeric or logical row vector of size 1 x n. % L(i) is the label for the sample X(:,i), which can be either % 0 or 1. % % The output c is a d x 1 discriminant coefficient vector, % which is orthogonal to the boundary plane. % % One can specify further options when needed. Available % options are listed below. % % - 'reg': the regularization coefficient, which would be % added to the diagonal entries of the estimated % common covariance. (default = 0) % % - 'weights': the weights of samples, which should be a % row vector of size 1 x n. % (default = [], indicating all samples have the % the same weight). % % Created by Dahua Lin, on Nov 22, 2010 % %% verify input arguments if ~(isfloat(X) && isreal(X) && ndims(X) == 2) error('fisherlda_binary:invalidarg', 'X should be a real matrix.'); end n = size(X, 2); if ~((islogical(L) || isnumeric(L)) && isequal(size(L), [1 n])) error('fisherlda_binary:invalidarg', ... 'L should be a logical/numeric vector of size 1 x n.'); end if ~islogical(L); L = logical(L); end r = 0; ws = []; if ~isempty(varargin) onames = varargin(1:2:end); ovals = varargin(2:2:end); if ~(numel(onames) == numel(ovals) && iscellstr(onames)) error('fisherlda_binary:invalidarg', ... 'The option list is invalid.'); end for i = 1 : numel(onames) name = onames{i}; v = ovals{i}; switch name case 'reg' if ~(isfloat(v) && isscalar(v) && v > 0) error('fisherlda_binary:invalidarg', ... 'reg should be a real positive scalar.'); end r = v; case 'weights' if ~(isfloat(v) && isequal(size(v), [1 n])) error('fisherlda_binary:invalidarg', ... 'weights should be a 1 x n numeric vector.'); end ws = v; end end end %% main % partition data X0 = X(:, ~L); X1 = X(:, L); if isempty(X0) error('fisherlda_binary:invalidarg', 'No samples are with label 0.'); end if isempty(X1) error('fisherlda_binary:invalidarg', 'No samples are with label 1.'); end if isempty(ws) n0 = size(X0, 2); n1 = size(X1, 2); else w0 = ws(~L); w1 = ws(L); t0 = sum(w0); t1 = sum(w1); end % estimate mean and covariance if isempty(ws) mu0 = sum(X0, 2) * (1/n0); mu1 = sum(X1, 2) * (1/n1); C0 = X0 * X0' - (n0 * mu0) * mu0'; C1 = X1 * X1' - (n1 * mu1) * mu1'; Sigma = (C0 + C1) * (1 / (n0 + n1)); else mu0 = X0 * (w0' / t0); mu1 = X1 * (w1' / t1); C0 = X0 * bsxfun(@times, X0, w0)' - (t0 * mu0) * mu0'; C1 = X1 * bsxfun(@times, X1, w1)' - (t1 * mu1) * mu1'; Sigma = (C0 + C1) * (1 / (t0 + t1)); end if r ~= 0 Sigma = adddiag(Sigma, r); end % solve discriminant direction c = Sigma \ (mu1 - mu0); c = c / norm(c);
zzhangumd-smitoolbox
classics/subspace/fisherlda_binary.m
MATLAB
mit
3,478
function [T, Tmu] = fisherldax(X, K, L, varargin) %FISHERLDAX (Generalized) Multi-class Fisher's Linear Discriminant Analysis % % T = FISHERLDAX(X, K, L, ...); % [T, Tmu] = FISHERLDAX(X, K, L, ...); % % Performs multi-class Fisher's linear discriminant analysis on % given Data to derive a discriminant subspace. % % Suppose there are totally n samples on a d-dimensional space. % % Input arguments: % - X: The sample matrix of size d x n. Each column of X % is a sample. % - K: The number of classes. % - L: The label vector of length n. In particular, L(i) % is the class label for X(:,i). % % Output arguments: % - T: A transform matrix of size p x d (p < d), which % transforms a d-dimensional input vector x into % a p-dimensional discriminant feature y, as y = T * x. % % - Tmu: The transformed mean vectors, of size p x K. % % One can further specify some of the following options to % control the algorithm in form of name/value pairs. % For options that are not explicitly specified, the default % values will be used. % % - 'maxdim': the maximum dimension of target space. % default = [], indicate to keep all dimensions. % If this option is specified, at most maxdim dimensions % are preserved. % % - 'weights': the sample weights. % default = [], indicate that all samples have the % same weight. % % - 'wdim': the dimension of whitened space. default = d. % % - 'reg': the regularization coefficient in whitening Sw. % default = 1e-3 (i.e. add 1e-3 * max(eigenvalue) % to diagonal entries of Sw before solving the % whitening transform). % % - 'bound': the bounding coefficient in whitening Sw. % default = [], indicate no bounding. % If this option is specified to v, the function will % enforce a lower bound = v * max(eigenvalue) to % the eigenvalues of Sw before solving the whitening % transform. % % - 'ranktol': the rank tolerance. The eigen-direction whose % eigenvalue < ranktol * max(eigenvalue) is considered % to be in the null space. default = 1e-8; % % Remarks % ------- % Here, we briefly introduce our implementation of LDA, in order % to show a clear picture of what the options mean, and how to % use them. The procedure has three main stages: % % Stage 0: compute the mean vectors, and Scattering matrices, % including the within-class scatter matrix Sw, and % the between-class scatter matrix Sb. If the samples % are weighted, the weights will be utilized in the % computation in this stage. % % Stage 1: Solve the whitening transform for Sw. In this stage, % either regularization or bounding can be done, depending % on whether reg or bound options are specified with % non-empty values. If they are simultaneously specified, % it applys bounding. In addition, we use wdim option % to control the dimension of whitened space. % % Stage 2: After the whitening transform W is obtained, we compute % the matrix W * Sb * W', and solve the principal subspace % of the whitened space with respect to this matrix. % The option ranktol (togther with maxdim) is used to % determine the dimension of the transformed space. % % Suppose the projection transform solved in stage 2 is P, then the % final transform that this function will return is P * W. % % History % ------- % - Created by Dahua Lin, on Nov 31, 2010. % - Modified by Dahua Lin, on Dec 31, 2011. % %% verify input arguments if ~(isfloat(X) && isreal(X) && ndims(X) == 2) error('fisherldax:invalidarg', 'X should be a real matrix.'); end [d, n] = size(X); if ~(isnumeric(K) && isscalar(K) && K == fix(K) && K >= 1) error('fisherldax:invalidarg', 'K should be a positive integer scalar.'); end if ~(isnumeric(L) && isequal(size(L), [1 n])) error('fisherldax:invalidarg', 'L should be a 1 x n numeric vector.'); end % options [maxdim, w, wdim, reg, bound, rktol] = getopts(d, varargin); %% main % Stage 0: Compute Sw and Sb [mu, Sw, Sb] = scattermat(X, K, L, w); % Stage 1: Solve whitening transform w.r.t. Sw if isempty(bound) if isempty(reg) W = cov_whiten(Sw, wdim); else W = cov_whiten(Sw, wdim, 'reg', reg); end else W = cov_whiten(Sw, wdim, 'bound', bound); end % Stage 2: Solve projection w.r.t B = W * Sb * W' B = W * Sb * W'; B = 0.5 * (B + B'); [U, D] = eig(B); evs = diag(D); [evs, si] = sort(evs, 1, 'descend'); if ~isempty(rktol) si = si(evs >= rktol * evs(1)); end if numel(si) > maxdim; si = si(1:maxdim); end P = U(:, si)'; % Output T = P * W; if nargout >= 2 Tmu = T * mu; end %% sub functions function [maxdim, w, wdim, reg, bound, rktol] = getopts(d, params) maxdim = []; w = []; wdim = d; reg = 1e-3; bound = []; rktol = 1e-8; % parse options if ~isempty(params) onames = params(1:2:end); ovals = params(2:2:end); if ~(numel(onames) == numel(ovals) && iscellstr(onames)) error('fisherldax:invalidarg', 'The option list is invalid.'); end for i = 1 : numel(onames) name = onames{i}; v = ovals{i}; switch lower(name) case 'maxdim' if ~(isnumeric(v) && isscalar(v) && v == fix(v) && v >= 1) error('fisherldax:invalidopt', ... 'maxdim should be a positive integer scalar.'); end maxdim = v; case 'weights' if ~(isempty(v) || (isfloat(v) && isequal(size(v), [1 n]))) error('fisherldax:invalidopt', ... 'weights should be either empty or an 1 x n numeric vector.'); end w = v; case 'wdim' if ~(isnumeric(v) && isscalar(v) && v == fix(v) && v >= 1 && v <= d) error('fisherldax:invalidopt', ... 'wdim should be an integer scalar in [1, d].'); end wdim = v; case 'reg' if ~(isempty(v) || (isfloat(v) && isscalar(v) && isreal(v) && v > 0)) error('fisherldax:invalidopt', ... 'reg should be either empty or a positive scalar.'); end reg = v; case 'bound' if ~(isempty(v) || (isfloat(v) && isscalar(v) && isreal(v) && v > 0)) error('fisherldax:invalidopt', ... 'bound should be either empty or a positive scalar.'); end bound = v; case 'rktol' if ~(isempty(v) || (isfloat(v) && isscalar(v) && isreal(v) && v > 0)) error('fisherldax:invalidopt', ... 'ranktol should be either empty or a positive scalar.'); end rktol = v; otherwise error('fisherldax:invalidarg', 'Unknown option name %s', name); end end end
zzhangumd-smitoolbox
classics/subspace/fisherldax.m
MATLAB
mit
7,604
function fisherlda_binary_demo() % A simple program to demonstrate the use of fisherlda_binary % % fisherlda_binary_demo; % % Created by Dahua Lin, on Nov 22, 2010 % % prepare model mu = randn(2, 2) * 4; sigma = randn(2, 2); sigma = sigma * sigma'; % prepare data n = 2000; T = chol(sigma, 'lower'); X1 = bsxfun(@plus, mu(:, 1), T * randn(2, n)); X2 = bsxfun(@plus, mu(:, 2), T * randn(2, n)); X = [X1 X2]; L = [zeros(1, n), ones(1, n)]; % solve LDA c0 = sigma \ (mu(:,2) - mu(:,1)); c0 = c0 / norm(c0); % the truly optimal direction. c = fisherlda_binary(X, L, 'reg', 1e-8); fprintf('true optima = %s\n', num2str(c0.', '%.4f ')); fprintf('solved result = %s\n', num2str(c.', '%.4f ')); % visualize figure; plot(X(1, L==0), X(2, L==0), 'g.', 'MarkerSize', 5); hold on; plot(X(1, L==1), X(2, L==1), 'b.', 'MarkerSize', 5); hold on; plot(mu(1, :), mu(2, :), 'r+', 'LineWidth', 2, 'MarkerSize', 15); axis equal; a0 = mean(mu, 2); impline(c(1), c(2), -c'*a0, [], 'Color', 'r');
zzhangumd-smitoolbox
classics/subspace/fisherlda_binary_demo.m
MATLAB
mit
998
function objf = comb_lossfun(X, Y, K, w, lossfun) %COMB_LOSSFUN Combined loss function % % Generally, the total loss (risk) on a given set of (weighted) samples % is given by % % sum_{i=1}^n w_i loss(theta' * x_i, y_i). % % Here, theta is a coefficient vector, x_i is the i-th sample (which % is associated with a weight w_i). y_i is the expected response. % A loss value can be calculated using the function loss, which % takes two arguments: the prediction theta' * x_i, and the expected % response y_i. % % Here, vector/matrix dimensions: % - x_i: a sample vector: d x 1 % When there are n samples, they are grouped in a matrix % of size d x n. % % - theta: the parameter vector/matrix: d x K. % % - y_i: a response vector: q x 1 % When there are n samples, all y_i vectors are grouped % in a matrix of size q x n. % % Note that in general, d and q need not be equal. % % % objf = COMB_LOSSFUN(X, Y, K, w, lossfun); % % Constructs an objective function handle that evaluates the % total loss at all given samples for each parameter theta. % % Suppose there are n training pairs of samples and responses. % % Input arguments: % - X: the sample (feature) matrix, size: d x n. % % - Y: the response matrix, size: q x n. % % - K: the number of columns in the parameter matrix. % % - w: the sample weights, size: 1 x n. % w can also be [], indicating all sample weights are 1. % % - lossfun: the function handle of the loss function. It will be % invoked in the following way: % % [v, g] = lossfun(theta' * X, Y). % % Here, v should be a 1 x n row vector containing the % objective values, and g should be a K x n matrix % containing the gradient w.r.t. the first argument. % % % Output arguments: % - objf: an objective function handle which can be used as % follows: % % v = objf(theta). % [v, g] = objf(theta). % % Here, v is the objective value, and g is the gradient % vector of length d x K. % % Note that objf can serve as an input to optimization functions % such as fminunc. The solution will be a vector of length d x K, % which is a concatenation of all columns of theta. % % History % ------- % - Created by Dahua Lin, on Jan 24, 2011 % %% main if size(w, 2) > 1 w = w.'; end objf = @(theta) rlmin_obj(theta, X, Y, K, w, lossfun); %% The objective function function [v, g] = rlmin_obj(theta, X, Y, K, w, lossfun) d = size(X, 1); if K > 1 theta = reshape(theta, d, K); end Z = theta' * X; out_g = nargout >= 2; if out_g [L, Gz] = lossfun(Z, Y); % Gz: K x n else L = lossfun(Z, Y); end if isempty(w) v = sum(L); if out_g g = X * Gz'; end else v = L * w; if out_g if K == 1 g = X * (Gz' .* w); else g = X * bsxfun(@times, Gz', w); end end end if out_g && K > 1 g = g(:); end
zzhangumd-smitoolbox
classics/regression/comb_lossfun.m
MATLAB
mit
3,295
function f = glinreg_objfun(X, Y, w, rho, rc) %GLINREG_OBJFUN Generalized linear regression objective function % % A generalized linear regression problem is an optimization problem % formulated as minimizing the following objective % % f(theta, theta0) = % \sum_{i=1}^n + w_i * rho((theta' * x_i + theta_0) - y_i) % + (rc/2) * ||theta||^2 % % Suppose the dimension of the feature space is d, and that of the % output space is q. Then each x_i is a d x 1 vector, and each y_i % is a q x 1 vector, and theta is a d x q matrix, and theta_0 is % a q x 1 vector. % % Here, rho is a function that takes a q x 1 difference vector as % input and yields a loss value. % % The solution is a vector of length (d+1) x q. Suppose sol is % the solution vector, then % % if q == 1 % theta = sol(1:d); % theta0 = sol(d+1); % else % A = reshape(sol, d+1, q); % theta = A(1:d, :); % theta0 = A(d+1, :); % end % % % f = GLINREG_OBJFUN(X, Y, w, rho, rc); % % Returns the objective function f for the generalized linear % regression problem formulated above. % % Input arguments: % % - X: The feature matrix, size: d x n % % - Y: The matrix of expected output, size: q x n % % - w: The sample weights, empty or a 1 x n vector. % % - rho: The loss function handle, which takes difference % vectors as input, and outputs the loss values. % % - rc: The regularization coefficient: a scalar or a d x 1 % vector. % % Output arguments: % - f: The objective function handle, which can be used as % % v = f(sol); % [v, g] = f(sol); % % Here, v and g are respectively the functon value and % gradient evaluated at sol. % % Created by Dahua Lin, on Jan 15, 2012 % %% verify input if ~(isfloat(X) && isreal(X) && ndims(X) == 2) error('glinreg_objfun:invalidarg', 'X should be a real matrix.'); end if ~(isfloat(Y) && isreal(Y) && ndims(Y) == 2) error('glinreg_objfun:invalidarg', 'X should be a real matrix.'); end n = size(X, 2); if size(Y, 2) ~= n error('glinreg_objfun:invalidarg', 'X and Y have different number of columns.'); end if ~isempty(w) if ~(isfloat(w) && isreal(w) && isvector(w) && numel(w) == n) error('glinreg_objfun:invalidarg', 'w should be a real vector of length n.'); end end if ~isa(rho, 'function_handle') error('glinreg_objfun:invalidarg', 'rho should be a function handle.'); end if ~(isfloat(rc) && isscalar(rc) && isreal(rc)) error('glinreg_objfun:invalidarg', 'rc should be a real scalar.'); end %% main n = size(X, 2); Xa = [X; ones(1, n)]; f_loss = comb_lossfun(Xa, Y, size(Y, 1), w, @(z, y) rho(z - y)); if rc == 0 f = f_loss; else d = size(X, 1); q = size(Y, 1); c = [ones(d, 1); 0]; if q > 1 c = c(:, ones(1,q)); c = c(:); end f = comb_objfun(1, f_loss, rc, tikregf(c)); end
zzhangumd-smitoolbox
classics/regression/glinreg_objfun.m
MATLAB
mit
3,080
function robustlinreg_demo %ROBUSTLINREG_DEMO Demo of robust linear regression % % robustlinreg_demo; % % This is a small program that demonstrates the use of robust % linear regression. % % Created by Dahua Lin, on Jan 15, 2012 % %% prepare data n = 500; noise = 0.05; outlier_fraction = 0.3; outliers = randpick(n, round(n * outlier_fraction)); a0 = rand(); b0 = rand(); x = randn(1, n); y = (a0 * x + b0) + randn(1, n) * noise; out_dev = 5; y(outliers) = y(outliers) + rand(1, numel(outliers)) * out_dev; %% regression % generalized linear regression using quadratic loss [a1, b1] = glinreg(x, y, [], @quadloss, 1e-4); % generalized linear regression using huber loss [a2, b2] = glinreg(x, y, [], @(e) huberloss(e, 1e-2), 1e-4); % generalized linear regression using bisquare loss [a3, b3] = glinreg(x, y, [], @(e) bisquareloss(e, 1), 1e-4); write_line('true', a0, b0); write_line('quad loss', a1, b1); write_line('huber loss', a2, b2); write_line('bisquare loss', a3, b3); %% visualization xmin = min(x); xmax = max(x); figure; plot(x, y, '.'); hold on; plot_line(a1, b1, xmin, xmax, 'r-'); hold on; plot_line(a2, b2, xmin, xmax, 'm-'); hold on; plot_line(a3, b3, xmin, xmax, 'g-'); %% auxiliary functions function plot_line(a, b, xmin, xmax, symb) x0 = xmin; x1 = xmax; y0 = a * x0 + b; y1 = a * x1 + b; plot([x0 x1], [y0 y1], symb, 'LineWidth', 1.5); function write_line(name, a, b) fprintf('line (%s): y = %.4f x + %.4f\n', name, a, b);
zzhangumd-smitoolbox
classics/regression/robustlinreg_demo.m
MATLAB
mit
1,489
function f = mlogireg_objfun(X, y, w, rc) %MLOGIREG_OBJFUN Multi-class logistic regression objective function % % The objective function for an K-class logistic regression problem is % % f(theta) = - sum_i w_i log p_i + (rc/2) * ||theta||^2 % % Here, if the i-th sample is in the k-th class, then % % p_i = exp(z_{ki}) / sum_{l=1}^m exp(theta_l' * z_{li}) % % where z_{ki} = theta_k' * x_i + theta_{k0} % % % f = MLOGIREG_OBJFUN(X, y, w, rc); % constructs the objective for multi-class logistic regression. % % This function returns a function handle f which represent the % objective as formalized above. % % Input arguments: % - X: The sample matrix of size d x n. % % - y: y can be in either of the following forms. % - a label vector of size 1 x n. Here, y(i) can take % value in {1, ..., K}. The function would set K % to be max(y). % - an assignment matrix of size K x n. Here, y(:,i) % corresponds to X(:,i). Note that each column of y % must sums to one. % % - w: The weights of the samples. If all samples have the % same weight, then w can be empty or omitted. % Otherwise, w should be a vector of length n. % % - rc: The regularization coefficient. % % The output argument f is a function handle, which can be invoked % as follows: % % v = f(a); % [v, g] = f(a); % % Here, f takes as input the parameter a, and returns the objective % value v, or optionally the gradient g. % This function handle can be used as an objective function in % numeric optimization. % % History % ------- % - Created by Dahua Lin, on Jan 25, 2001. % %% verify input arguments if ~(isfloat(X) && isreal(X) && ndims(X) == 2) error('mlogireg_objfun:invalidarg', 'X should be a real matrix.'); end [d, n] = size(X); if ~(isfloat(y) && isreal(y) && ndims(y) == 2 && size(y, 2) == n) error('mlogireg_objfun:invalidarg', 'y should be a real matrix with n columns.'); end K = size(y, 1); if K == 1 % label vector K = max(y); end if nargin < 3 || isempty(w) w = []; else if ~(isfloat(w) && isvector(w) && numel(w) == n) error('mlogireg_objfun:invalidarg', 'w should be a vector of length n.'); end end if nargin < 4 rc = 0; else if ~(isfloat(rc) && isscalar(rc) && rc >= 0) error('mlogireg_objfun:invalidarg', 'rc should be a non-negative scalar.'); end end %% main Xa = [X; ones(1, n)]; f_loss = comb_lossfun(Xa, y, K, w, @mlogistic_loss); if rc == 0 f = f_loss; else c = [ones(d, K); zeros(1, K)]; f_reg = tikregf(c(:)); f = comb_objfun(1, f_loss, rc, f_reg); end
zzhangumd-smitoolbox
classics/regression/mlogireg_objfun.m
MATLAB
mit
2,856
function [theta, theta0] = logireg(X, y, w, rc, initsol, varargin) %LOGIREG Logistic regression % % [theta, theta0] = LOGIREG(X, y); % [theta, theta0] = LOGIREG(X, y, w); % [theta, theta0] = LOGIREG(X, y, w, rc, ...); % [theta, theta0] = LOGIREG(X, y, w, rc, initsol, ...); % % Performs logistic regression to find a decision boundary % between two classes. % % Input arguments: % - X: The feature matrix. Size: d x n, where d is the % feature dimension, and n is the number of samples % in X. % % - y: The vector of class labels, whose values can be % either 1 or -1. The length of y should be n. % % - w: The sample weights. It is either empty (indicating % that all samples have the same weight), or a vector % of length n that gives sample-specific weights. % % - rc: The regularization coefficient. % (If omitted, rc is set to zero). % % - initsol: The initial solution in form of {theta, theta0}. % This can be omitted or input as an empty array, in % which case, both theta and theta0 are initialized % to be zeros. % % One can further specify the following options in form of % name/value pairs to control the optimization procedure. % % - MaxIter: the maximum number of iterations {100} % - TolFun: the termination tolerance of objective value change {1e-8} % - TolX: the termination tolerance of solution change {1e-7} % - Display: the level of display {'none'}|'proc'|'iter' % % Output arguments: % - theta: The coefficient vector. Size: d x 1 % - theta0: The offset scalar. % % The linear predictor is then given by % % theta' * x + theta0 % % One can determine which class x belongs to based on the sign % of this predictor. % % Created by Dahua Lin, on Jan 17, 2012 % %% pre-process inputs if nargin < 3 w = []; end if nargin < 4 rc = 0; end d = size(X, 1); if nargin < 5 || isempty(initsol) initsol = zeros(d+1, 1); else if ~(iscell(initsol) && numel(initsol) == 2) error('logireg:invalidarg', 'initisol is invalid for logireg.'); end t = initsol{1}; t0 = initsol{2}; if ~(isfloat(t) && isequal(size(t), [d 1]) && ... isfloat(t0) && isscalar(t0)) error('logireg:invalidarg', 'initisol is invalid for logireg.'); end initsol = [t; t0]; end opts = smi_optimset('bfgsfmin', varargin{:}); %% main f = logireg_objfun(X, y, w, rc); sol = bfgsfmin(f, initsol, opts); theta = sol(1:d); theta0 = sol(d+1);
zzhangumd-smitoolbox
classics/regression/logireg.m
MATLAB
mit
2,751
function mlogireg_demo() %MLOGIREG_DEMO Demo of Multi-class logistic regression % % mlogireg_demo; % % This is a simple program that demonstrates the use of % multi-class logistic regression (mlogiregf) % % History % ------- % - Created by Dahua Lin, on Jan 25, 2011 % - Modified by Dahua Lin, on Jan 15, 2012 % %% prepare data n = 300; K = 3; d = 6; a = 2; b = 1; c = randn(2, K) * d; X = zeros(2, n * K); for k = 1 : K X(:, (k-1) * n + (1:n)) = gen_data(n, c(1,k), c(2,k), a, b, rand() * pi); end y = exelem((1:K), 1, n); %% regression [theta, theta0] = mlogireg(X, y, [], 1e-3, [], ... 'MaxIter', 300, 'TolFun', 1e-8, 'TolX', 1e-8, 'Display', 'iter'); %% Visualize data figure; % data colors = {'r', 'g', 'b', 'm'}; for k = 1 : K cr = colors{mod(k-1, K) + 1}; cX = X(:, (k-1) * n + (1:n)); hold on; plot(cX(1, :), cX(2, :), '.', 'Color', cr); end % contour xmin = min(X(1,:)); xmax = max(X(1,:)); ymin = min(X(2,:)); ymax = max(X(2,:)); x0 = xmin - 0.1 * (xmax - xmin); x1 = xmax + 0.1 * (xmax - xmin); y0 = ymin - 0.1 * (ymax - ymin); y1 = ymax + 0.1 * (ymax - ymin); xx = linspace(x0, x1, 500); yy = linspace(y0, y1, 500); [xx, yy] = meshgrid(xx, yy); Xm = [xx(:), yy(:)]'; U = bsxfun(@plus, theta' * Xm, theta0); P = nrmexp(U, 1); mp = max(P, [], 1); hold on; contour(xx, yy, reshape(mp, size(xx)), 0.3:0.1:0.9); % set range axis([x0 x1 y0 y1]); axis equal; colorbar; function X = gen_data(n, x0, y0, a, b, t) X = randn(2, n); X = bsxfun(@times, [a; b], X); R = [cos(t) -sin(t); sin(t) cos(t)]; X = bsxfun(@plus, R * X, [x0; y0]);
zzhangumd-smitoolbox
classics/regression/mlogireg_demo.m
MATLAB
mit
1,622
function [v, G] = quadloss(Z, Y) %QUADLOSS Quadratic loss function % % v = QUADLOSS(D); % v = QUADLOSS(Z, Y); % % [v, G] = QUADLOSS(D); % [v, G] = QUADLOSS(Z, Y); % % Evaluates the quadratic loss, defined to be % % v = (1/2) * ||z - y||^2. % % Input arguments: % - D: The matrix of difference vectors [D := Z - Y] % - Z: The matrix of predicted vectors [d x n] % - Y: The matrix of expected vectors [d x n] % % Output arguments: % - v: The vector of loss values [1 x n] % - G: The gradient vectors w.r.t. Z [d x n] % % % Created by Dahua Lin, on Jan 15, 2012 % %% main if nargin == 1 G = Z; else G = Z - Y; end if size(G, 1) == 1 v = 0.5 * G.^2; else v = 0.5 * sum(G.^2, 1); end
zzhangumd-smitoolbox
classics/regression/quadloss.m
MATLAB
mit
801
function [v, g] = logistic_loss(z, y) %LOGISTIC_LOSS The logistic loss function % % v = LOGISTIC_LOSS(z, y); % [v, g] = LOGISTIC_LOSS(z, y); % % Evaluates the logistic loss function, which is defined to be % % loss(z, y) = log(1 + exp(-z * y)); % % Input arguments: % - z: The linear predictors [1 x n] % - y: The expected response [1 x n]. % Typically, the values of y can be either 1 or -1. % % Output arguments: % - v: The loss values [1 x n] % - g: The derivatives [1 x n] % % Created by Dahua Lin, on Jan 1, 2012 %% main u = 1 + exp(-z .* y); v = log(u); if nargout >= 2 g = (1 - 1 ./ u) .* (-y); end
zzhangumd-smitoolbox
classics/regression/logistic_loss.m
MATLAB
mit
729
function logireg_demo() % A simple script to demonstrate the use of logireg % % logireg_demo; % % Created by Dahua Lin, on Jan 25, 2011 % %% prepare data n = 1000; t = rand() * (2 * pi); tc = t + pi/2 + randn() * 0.5; d = 3; xc = randn() * 10; yc = randn() * 10; dir = [cos(tc) sin(tc)] * d; X0 = gen_data(n, xc + dir(1), yc + dir(2), 3, 1, t); X1 = gen_data(n, xc - dir(1), yc - dir(2), 3, 1, t); %% model and solve X = [X0, X1]; y = [-ones(1, n), ones(1, n)]; [theta, theta0] = logireg(X, y, [], 1e-3, [], ... 'MaxIter', 300, 'TolFun', 1e-8, 'TolX', 1e-8, 'Display', 'iter'); fprintf('Boundary: %.4f x + %.4f y + %0.4f = 0\n', ... theta(1), theta(2), theta0); %% visualize % data points figure; plot(X0(1,:), X0(2,:), 'b.', 'MarkerSize', 5); hold on; plot(X1(1,:), X1(2,:), 'r.', 'MarkerSize', 5); xmin = min(X(1,:)); xmax = max(X(1,:)); ymin = min(X(2,:)); ymax = max(X(2,:)); % contour hold on; xx = linspace(xmin, xmax, 300); yy = linspace(ymin, ymax, 300); [xx, yy] = meshgrid(xx, yy); zz = [xx(:), yy(:)]; pv = 1 ./ (1 + exp(-(zz * theta + theta0))); hold on; contour(xx, yy, reshape(pv, size(xx)), 0.1:0.1:0.9); colorbar; axis([xmin, xmax, ymin, ymax]); axis equal; function X = gen_data(n, x0, y0, a, b, t) X = randn(2, n); X = bsxfun(@times, [a; b], X); R = [cos(t) -sin(t); sin(t) cos(t)]; X = bsxfun(@plus, R * X, [x0; y0]);
zzhangumd-smitoolbox
classics/regression/logireg_demo.m
MATLAB
mit
1,375
function [o1, o2] = llsq(X, y, w, r) %LLSQ Linear least square problem % % The function solves the (weighted) linear least square problem, as % % minimize (1/2) * sum_i w_i ||x_i' * a - y_i||^2 + (1/2) * r * ||a||^2 % % It is well known that the solution to this problem is % % optimal a = inv(X' * W * X + rI) * (X' * W * y). % % % a = llsq(X, y); % a = llsq(X, y, w); % a = llsq(X, y, w, r); % % solves the problem as formalized above and returns the optimal a. % % Input arguments: % - X: the design matrix. Suppose there are n independent % variables, each with d components, then X should be % an n x d matrix. % % - y: the response vector/matrix. In standard formulation, % y should be an n x q vector, with y(i,:) corresponding to % X(i, :). Here, q is the vector space dimension for the % response. % % - w: the weights. w can be in either of the following form: % - a scalar: All rows in X and y have the same weight w. % - a vector of length n: The i-th row has weight w(i). % - an positive semi-definite n x n matrix: This is a % generalization of the standard formulation which allows % correlation between rows. % % Omitting w is equivalent to setting w to 1, in which case, % the function essentially solves the ordinary least square % problem. % % - r: the regularization coefficient. r can be either of the % following: % - a scalar: as in the formulation above % - a vector of length d: assigning different regularization % coefficients for different components % - a postive definite matrix of size d x d: performing % generic Tikhonov regularization, in which the % regularization term is (1/2) * a' * r * a. % % Omitting r is equivalent to setting r to 0, in which case, % no regularization is performed. % % [H, f] = llsq(X, y, w); % % returns the Hessian matrix and gradient vector(s) instead of % solving the problem. % % Here, H = X' * W * X + rI, and f = X' * W * y. % % History % ------- % - Created by Dahua Lin, on Jan 5, 2011 % %% verify input if ~(isfloat(X) && ndims(X) == 2) error('llsq:invalidarg', 'X should be a numeric matrix.'); end n = size(X, 1); if ~(isfloat(y) && ndims(y) == 2) error('llsq:invalidarg', 'y should be a numeric matrix.'); end if n ~= size(y, 1) error('llsq:invalidarg', 'X and y should have the same number of rows.'); end if nargin < 3 || isempty(w) w = 1; else if ~(isfloat(w) && ndims(w) == 2) error('llsq:invalidarg', 'w should be a numeric scalar/vector/matrix.'); end end if nargin < 4 r = 0; else if ~(isfloat(r) && ndims(r) == 2) error('llsq:invalidarg', 'r should be a numeric scalar/vector/matrix.'); end end %% main % compute H and f if isscalar(w) H = X' * X; f = X' * y; if w ~= 1 H = w * H; f = w * f; end elseif isvector(w) if numel(w) ~= n error('llsq:invalidarg', 'The length of w is invalid.'); end if size(w, 2) > 1; w = w.'; end % turn w into a column H = X' * bsxfun(@times, w, X); H = 0.5 * (H + H'); f = X' * bsxfun(@times, w, y); else if ~(size(w,1) == n && size(w, 2) == n) error('llsq:invalidarg', 'The size of w is invalid.'); end H = X' * (W * X); H = 0.5 * (H + H'); f = X' * (W * y); end % regularize H if ~isequal(r, 0) if isscalar(r) || isvector(r) H = adddiag(H, r); else H = H + r; end end % solve and return if nargout < 2 o1 = H \ f; else o1 = H; o2 = f; end
zzhangumd-smitoolbox
classics/regression/llsq.m
MATLAB
mit
3,925
function [v, G] = huberloss(Z, Y, r) %HUBERLOSS Huber loss function % % v = HUBERLOSS(E, r); % v = HUBERLOSS(Z, Y, r); % % [v, G] = HUBERLOSS(E, r); % [v, G] = HUBERLOSS(Z, Y, r); % % Evaluates the huber loss function, defined to be % % v = (1/2) * e^2, when |e| < r % = r * e - r^2 / 2. when |e| >= r % % If e is a vector, then v is the sum of the loss values at % all components. The derivative is given by % % g = e, when |e| < r % = r * sign(e), when |e| >= r % % Created by Dahua Lin, on Jan 15, 2012 % %% main if nargin == 2 E = Z; r = Y; elseif nargin == 3 E = Z - Y; end Ea = abs(E); Eb = min(Ea, r); v = 0.5 * Eb .* (2 * Ea - Eb); if size(v, 1) > 1 v = sum(v, 1); end if nargout >= 2 G = Eb .* sign(E); end
zzhangumd-smitoolbox
classics/regression/huberloss.m
MATLAB
mit
849
function [v, G] = mlogistic_loss(Z, Y) %MLOGISTIC_LOSS Multi-class Logistic loss function % % v = MLOGISTIC_LOSS(Z, Y); % [v, G] = MLOGISTIC_LOSS(Z, Y); % % Evaluates the multi-class logistic loss function, defined as % % loss(z, y) = - sum_{k=1}^K (y_k * log(p_k)) % % with p_k = exp(z_k) / sum_{l=1}^K exp(z_l). % % Here, both z and y are K-dimensional vector. In classification % problems, y are typically indicator vectors. % % % Input arguments: % - Z: The matrix of linear predictors: K x n % - Y: Can be in either of the following forms: % - a K x n matrix of indicator vectors (or soft % assignment vectors). Each column of Y sums to 1. % - a 1 x n vector of class labels. % % Output arguments: % - v: The loss values [1 x n] % - g: The gradients [K x n] % % Created by Dahua Lin, on Jan 1, 2012 % %% main [K, n] = size(Z); zm = max(Z, [], 1); Z1 = bsxfun(@minus, Z, zm); E1 = exp(Z1); se = sum(E1, 1); if nargout >= 2 P = bsxfun(@times, E1, 1 ./ se); end if size(Y, 1) == 1 I = Y + (0:n-1) * K; v = log(se) - Z1(I); if nargout >= 2 G = P; G(I) = G(I) - 1; end elseif size(Y, 1) == K v = log(se) - sum(Y .* Z1, 1); if nargout >= 2 G = P - Y; end else error('mlogistic_loss:invalidarg', 'The size of Y is invalid.'); end
zzhangumd-smitoolbox
classics/regression/mlogistic_loss.m
MATLAB
mit
1,465
function [theta, theta0] = mlogireg(X, y, w, rc, initsol, varargin) %MLOGIREG Multi-class logistric regression % % [theta, theta0] = MLOGIREG(X, y); % [theta, theta0] = MLOGIREG(X, y, w); % [theta, theta0] = MLOGIREG(X, y, w, rc, ...); % [theta, theta0] = MLOGIREG(X, y, w, rc, initsol, ...); % % Performs multi-class logistic regression to find the discriminant % functions for classification. % % Input arguments: % - X: The feature matrix. Size: d x n, where d is the % feature dimension, and n is the number of samples % in X. % % - y: y can be in either of the following forms. % - a label vector of size 1 x n. Here, y(i) can take % value in {1, ..., K}. The function would set K % to be max(y). % - an assignment matrix of size K x n. Here, y(:,i) % corresponds to X(:,i). Note that each column of y % must sums to one. % % - w: The sample weights. It is either empty (indicating % that all samples have the same weight), or a vector % of length n that gives sample-specific weights. % % - rc: The regularization coefficient. % (If omitted, rc is set to zero). % % - initsol: The initial solution in form of {theta, theta0}. % This can be omitted or input as an empty array, in % which case, both theta and theta0 are initialized % to be zeros. % % One can further specify the following options in form of % name/value pairs to control the optimization procedure. % % - MaxIter: the maximum number of iterations {100} % - TolFun: the termination tolerance of objective value change {1e-8} % - TolX: the termination tolerance of solution change {1e-7} % - Display: the level of display {'none'}|'proc'|'iter' % % Output arguments: % - theta: The coefficient matrix. Size: d x K % - theta0: The vector of offsets. Size: K x 1. % % The following expression yields a vector comprised of K scores, % with respect to the K classes. % % theta' * x + theta0 % % Created by Dahua Lin, on Jan 17, 2011 % %% preprocess inputs if nargin < 3 w = []; end if nargin < 4 rc = 0; end d = size(X, 1); if size(y, 1) == 1 K = max(y); else K = size(y, 1); end if nargin < 5 || isempty(initsol) initsol = zeros((d+1) * K, 1); else if ~(iscell(initsol) && numel(initsol) == 2) error('mlogireg:invalidarg', 'initisol is invalid for logireg.'); end t = initsol{1}; t0 = initsol{2}; if ~(isfloat(t) && isequal(size(t), [d K]) && ... isfloat(t0) && isequal(size(t0), [K 1])) error('mlogireg:invalidarg', 'initisol is invalid for logireg.'); end initsol = [t; t0.']; initsol = initsol(:); end opts = smi_optimset('bfgsfmin', varargin{:}); %% main f = mlogireg_objfun(X, y, w, rc); sol = bfgsfmin(f, initsol, opts); sol = reshape(sol, d+1, K); theta = sol(1:d, :); theta0 = sol(d+1, :).';
zzhangumd-smitoolbox
classics/regression/mlogireg.m
MATLAB
mit
3,211
function [theta, theta0] = glinreg(X, Y, w, rho, rc, initsol, varargin) %GLINREG Logistic regression % % [theta, theta0] = GLINREG(X, Y, [], rho); % [theta, theta0] = GLINREG(X, Y, w, rho); % [theta, theta0] = GLINREG(X, Y, w, rho, rc, ...); % [theta, theta0] = GLINREG(X, Y, w, rho, rc, initsol, ...); % % Performs generalized linear regression. % % Input arguments: % - X: The feature matrix. Size: d x n, where d is the % feature dimension, and n is the number of samples % in X. % % - Y: The matrix of output vectors. Size: q x n, where q % is the dimension of the output space. % % - w: The sample weights. It is either empty (indicating % that all samples have the same weight), or a vector % of length n that gives sample-specific weights. % % - rho: The loss function handle, which takes difference % vectors as input, and outputs the loss values. % % - rc: The regularization coefficient. % (If omitted, rc is set to zero). % % - initsol: The initial solution in form of {theta, theta0}. % This can be omitted or input as an empty array, in % which case, both theta and theta0 are initialized % to be zeros. % % One can further specify the following options in form of % name/value pairs to control the optimization procedure. % % - MaxIter: the maximum number of iterations {100} % - TolFun: the termination tolerance of objective value change {1e-8} % - TolX: the termination tolerance of solution change {1e-7} % - Display: the level of display {'none'}|'proc'|'iter' % % Output arguments: % - theta: The coefficient vector. Size: d x q % - theta0: The offset scalar. Size: q x 1. % % The predicted output for a given input x is % % theta' * x + theta0 % % Created by Dahua Lin, on Jan 17, 2012 % %% preprocess arguments if nargin < 3 w = []; end if nargin < 5 rc = 0; end d = size(X, 1); q = size(Y, 1); if nargin < 6 || isempty(initsol) initsol = zeros((d+1) * q, 1); else if ~(iscell(initsol) && numel(initsol) == 2) error('glinreg:invalidarg', 'initisol is invalid for logireg.'); end t = initsol{1}; t0 = initsol{2}; if ~(isfloat(t) && isequal(size(t), [d q]) && ... isfloat(t0) && isequal(size(t0), [q 1])) error('glinreg:invalidarg', 'initisol is invalid for logireg.'); end initsol = [t; t0.']; initsol = initsol(:); end opts = smi_optimset('bfgsfmin', varargin{:}); %% main f = glinreg_objfun(X, Y, w, rho, rc); sol = bfgsfmin(f, initsol, opts); theta = sol(1:d, :); theta0 = sol(d+1, :).';
zzhangumd-smitoolbox
classics/regression/glinreg.m
MATLAB
mit
2,865
function [v, G] = bisquareloss(Z, Y, r) %BISQUARELOSS Bisquare loss function % % v = BISQUARELOSS(E, r); % v = BISQUARELOSS(Z, Y, r); % % [v, G] = BISQUARELOSS(E, r); % [v, G] = BISQUARELOSS(Z, Y, r); % % Evaluates the bisquare loss, defined to be % % v = (r^2/6) * min{(1 - (1 - (e/r)^2)^3), 1} % % If e is a vector, then v is the sum of the loss values at % all components. The derivative is given by % % g = e * ( 1 - (e/r)^2 )^2, when |e| < r % = 0 when |e| >= r % % Created by Dahua Lin, on Jan 15, 2012 % %% main if nargin == 2 E = Z; r = Y; elseif nargin == 3 E = Z - Y; end if r == 1 B = max(1 - E.^2, 0); else B = max(1 - (E * (1/r)).^2, 0); end B2 = B.^2; v = (r^2/6) * (1 - B2 .* B); if size(v, 1) > 1 v = sum(v, 1); end if nargout >= 2 G = E .* B2; end
zzhangumd-smitoolbox
classics/regression/bisquareloss.m
MATLAB
mit
893
function f = logireg_objfun(X, y, w, rc) %LOGIREG_OBJFUN Logistic regression objective function % % The objective function of logistic regression is given by % % f(theta) = - \sum_i w_i ( y_i log(p_i) + (1 - y_i) log(1 - p_i) ) % + (rc / 2) * ||theta||^2 % % Here, p_i = 1 / (1 + exp(-z_i)) and z_i = theta' * x_i + theta0 % % f = LOGIREG_OBJFUN(X, y); % f = LOGIREG_OBJFUN(X, y, w); % f = LOGIREG_OBJFUN(X, y, [], rc); % f = LOGIREG_OBJFUN(X, y, w, rc); % % The function returns a function handle f that represents the % objective function as formalized above. % % Input arguments: % - X: The sample matrix of size d x n. % % - y: The indicator vector of length n. % y(i) = 1 indicates that the i-th sample in X is a % postive sample, and y(i) = -1 indicates that it is % a negative sample. % % Actually, y(i) can be any real value in [0, 1], in % which case, it may represent a soft tendency rather % than a hard assignment. % % - w: The weights of the samples. If all samples have the % same weight, then w can be empty or omitted. % Otherwise, w should be a vector of length n. % % - rc: The regularization coefficient. % % The output argument f is a function handle, which can be invoked % as follows: % % v = f(a); % [v, g] = f(a); % % Here, f takes as input the parameter a, in form of [theta; theta0] % and returns the objective value v, or optionally the gradient g. % This function handle can be used as an objective function in % numeric optimization. % % History % ------- % - Created by Dahua Lin, on Jan 25, 2011. % - Modified by Dahua Lin, on Jan 1, 2012. % %% verify input arguments if ~(isfloat(X) && ndims(X) == 2) error('logireg_objfun:invalidarg', 'X should be a numeric matrix.'); end [d, n] = size(X); if ~((islogical(y) || isnumeric(y)) && isvector(y) && numel(y) == n) error('logireg_objfun:invalidarg', ... 'y should be a logical or numeric vector of length n'); end if size(y, 1) > 1 y = y.'; end if ~isfloat(y) y = double(y); end if nargin < 3 || isempty(w) w = []; else if ~(isfloat(w) && isvector(w) && numel(w) == n) error('logireg_objfun:invalidarg', 'w should be a vector of length n.'); end end if nargin < 4 rc = 0; else if ~(isfloat(rc) && isscalar(rc) && rc >= 0) error('logireg_objfun:invalidarg', 'rc should be a non-negative scalar.'); end end %% main Xa = [X; ones(1, n)]; f_loss = comb_lossfun(Xa, y, 1, w, @logistic_loss); f_reg = tikregf([ones(d, 1); 0]); f = comb_objfun(1, f_loss, rc, f_reg);
zzhangumd-smitoolbox
classics/regression/logireg_objfun.m
MATLAB
mit
2,968
function f = tikregf(c) %TIKREGF Function handle for regularization % % f = TIKREGF(c); % f = TIKREGF(Q); % % Constructs and returns a function handle for Tikhonov % regularization. % % Tikhonov regularization function is generally defined to be % % f(x) = (1/2) * x' * Q * x. % % Here, Q is a positive semi-definite matrix. Often times, a % simplified version, weighted L2-regularization, is used % % f(x) = (1/2) * sum_i c_i (x_i)^2. % % % Input arguments: % - c: the coefficients for (weighted) L2 regularization, % which can be in either of the following forms: % - a scalar: all coeffficients are the same % - a vector that explicitly give all coefficients % % - Q: the coefficient matrix for Tikhonov regularization % % The output f is a function handle, which can be used as follows % % v = f(x); % [v, g] = f(x); % [v, g, H] = f(x); % % Here, x, the input to f, should be a matrix of size d x n, where % n is the number of parameters packed in x (e.g. in multi-class % classifier training, n can be greater than 1). % % f returns: % - v: the function value evaluated at x % - g: the gradient vector at x (if needed) % - H: the Hessian matrix at x (if needed) % % Created by Dahua Lin, on Jan 14, 2012 % %% verify input arguments cty = 0; if isfloat(c) && ndims(c) == 2 if isscalar(c) cty = 1; elseif isvector(c) cty = 2; if size(c, 2) > 1 c = c.'; end elseif size(c,1) == size(c,2) cty = 3; Q = c; end end if ~cty error('tikregf:invalidarg', 'The input to tikregf is invalid.'); end %% main if cty == 1 f = @(x) reg_L2_sca(x, c); elseif cty == 2 f = @(x) reg_L2_vec(x, c); else f = @(x) reg_Q(x, Q); end %% regularization functions function [v, g, H] = reg_L2_sca(x, c) v = (c/2) * (x' * x); if nargout >= 2 g = c * x; end if nargout >= 3 H = diag(c * ones(1, numel(x))); end function [v, g, H] = reg_L2_vec(x, c) g = c .* x; v = (x' * g) / 2; if nargout >= 3 H = diag(c); end function [v, g, H] = reg_Q(x, Q) g = Q * x; v = (x' * g) / 2; H = Q;
zzhangumd-smitoolbox
classics/regression/tikregf.m
MATLAB
mit
2,334
function s = kmseeds(data, K, method, varargin) %KMSEEDS Selecting seeds for clustering % % s = KMSEEDS({X}, K, method, ...); % s = KMSEEDS({X, costfun}, K, method, ...); % s = KMSEEDS(D, K, method, ...); % % Selects K seeds from a set of samples for K-means or K-medoid % clustering. % % Input arguments: % - X: The matrix comprising samples as columns % % - costfun: The function handle to evaluate costs between % samples and centers. % (If omitted, it is considered to be @pwsqL2dist). % % - D: The pairwise distance matrix [n x n] % % - K: The number of clusters. % % - method: The name of method used to select the seeds: % % - 'random': Randomly select K seeds % % - 'km++': K-means++ selection protocol % The probability being selected is % proportional to the square of min % distance to existing seeds % % - 'farthest': Greedily select the sample with % greatest min-dist to existing seeds % as the next seed. % % One can specify other options to control the selection, in form % of name/value pairs: % % - 'pre': Pre-selected seed indices, a vector with K' indices. % (default = [], indicating no pre-selected seeds) % % - 'pre-vec': Pre-selected seed vectors, a matrix composed of % K' vectors that have been selected as seeds. % % Note that is 'pre' is given, then 'pre-vec' is ignored. In % addition, 'pre-vec' can only be used when X is given. % % Also, when there are pre-selected seeds, this function returns % K new seeds that are not in the pre-selected set. % % Created by Dahua Lin, on Mar 27, 2012 % %% verify input arguments if iscell(data) && (numel(data) == 1 || numel(data) == 2) X = data{1}; if numel(data) == 1 costfun = @pwsqL2dist; else costfun = data{2}; if ~isa(costfun, 'function_handle') error('kmseeds:invalidarg', 'costfun must be a function handle.'); end end if ~(isfloat(X) && isreal(X) && ndims(X) == 2) error('kmseeds:invalidarg', 'X should be a real matrix.'); end [d, n] = size(X); has_X = 1; elseif isnumeric(data) D = data; if ~(isfloat(D) && isreal(D) && ndims(D) == 2 && size(D,1) == size(D,2)) error('kmseeds:invalidarg', 'D should be a real squared matrix.'); end n = size(D, 2); has_X = 0; else error('kmseeds:invalidarg', 'The first argument is invalid.'); end if ~(isnumeric(K) && isscalar(K) && K == fix(K) && K >= 1 && K <= n) error('kmseeds:invalidarg', 'K should be an integer in [1, n].'); end if ~ischar(method) error('kmseeds:invalidarg', 'method should be a char string.'); end pre = []; pre_v = []; if ~isempty(varargin) onames = varargin(1:2:end); ovals = varargin(2:2:end); for i = 1 : numel(onames) cn = onames{i}; cv = ovals{i}; switch lower(cn) case 'pre' if ~(isnumeric(cv) && (isvector(cv) || isempty(cv))) error('kmseeds:invalidarg', ... 'pre should be a numeric vector.'); end pre = cv; case 'pre-v' if ~has_X error('kmseeds:invalidarg', ... 'pre-v only applies when X is given.'); end if ~(isnumeric(cv) && isfloat(cv) && isreal(cv) && ... ndims(cv) == 2 && size(cv, 1) == d) error('kmseeds:invalidarg', ... 'The value given to pre-v is invalid.'); end pre_v = cv; end end end %% main % preparation if has_X dfun = @(i) costfun(X(:,i), X); else dfun = @(i) D(i, :); end min_dists = []; if ~isempty(pre) if has_X D0 = costfun(X(:, pre), X); else D0 = D(pre, :); end min_dists = min(D0, [], 1); elseif ~isempty(pre_v) D0 = costfun(pre_v, X); min_dists = min(D0, [], 1); end % do selection s = zeros(1, K); switch method case 'random' if isempty(min_dists) s = randpick(n, K); else s0 = find(min_dists > 0); s = s0(randpick(numel(s), K)); end case 'km++' s = do_progsel(dfun, n, K, min_dists, @kmpp_choose); case 'farthest' s = do_progsel(dfun, n, K, min_dists, @farthest_choose); otherwise error('kmseeds:invalidarg', 'Unknown method %s', method); end %% core functions function s = do_progsel(dfun, n, K, min_dists, cfun) s = zeros(1, K); if isempty(min_dists) s(1) = randi(n, 1); min_dists = dfun(s(1)); else s(1) = cfun(min_dists); min_dists = min(min_dists, dfun(s(1))); end for k = 2 : K s(k) = cfun(min_dists); min_dists = min(min_dists, dfun(s(k))); end function i = kmpp_choose(dists) p = dists * (1/sum(dists)); i = ddsample(p.', 1); function i = farthest_choose(dists) [~, i] = max(dists);
zzhangumd-smitoolbox
classics/cluster/kmseeds.m
MATLAB
mit
5,501
function kmedoid_std_demo(n, K) % Demo of kmedoid_std in clustering 2D points % % kmedoid_std_demo(n, K); % % Input arguments: % - n: The number of sample points % - K: The number of clusters % % Created by Dahua Lin, on Mar 27, 2012 % %% prepare data X = rand(2, n); %% run cfun = @(i, j) pwsqL2dist(X(:,i), X(:,j)); [M, L] = kmedoid_std({cfun, n}, K, 'Display', 'iter'); assert(isequal(size(M), [1 K])); assert(isequal(size(L), [1 n])); assert(all(L >= 1 & L <= K & L == fix(L))); %% visualize figure; plot(X(1,:), X(2,:), '.'); hold on; M = X(:, M); plot(M(1,:), M(2,:), 'ro', 'MarkerSize', 12, 'LineWidth', 2);
zzhangumd-smitoolbox
classics/cluster/kmedoid_std_demo.m
MATLAB
mit
649
function kmeans_std_demo(n, K) % Demo of kmeans_std in clustering 2D points % % kmeans_std_demo(n, K); % % Input arguments: % - n: The number of sample points % - K: The number of clusters % % Created by Dahua Lin, on Mar 27, 2012 % %% prepare data X = rand(2, n); %% run [M, L] = kmeans_std(X, K, 'Display', 'iter'); assert(isequal(size(M), [2 K])); assert(isequal(size(L), [1 n])); assert(all(L >= 1 & L <= K & L == fix(L))); %% visualize figure; plot(X(1,:), X(2,:), '.'); hold on; plot(M(1,:), M(2,:), 'r+', 'MarkerSize', 12, 'LineWidth', 2);
zzhangumd-smitoolbox
classics/cluster/kmeans_std_demo.m
MATLAB
mit
580
function S = afpsmat(S0, q) %AFPSMAT Affinity propagation similarity matrix % % S = AFPSMAT(S0); % % Given an input similarity matrix, it generates a modified matrix % for the use in affinity propagation. % % In particular, it sets the median of the pairwise similarities % to each diagonal entry of S. % % S = AFPSMAT(S0, q); % % It sets the diagonal entries to the q-quantile of the pairwise % similarities. % % AFPSMAT(S0, 0.5) is equivalent to AFPSMAT(S0); % % % Remarks % ------- % if you have a pairwise distance(dissimilarity) matrix D, you % can input -D as a similarity matrix. % % Created by Dahua Lin, on Mar 28, 2012 % %% verify input arguments n = size(S0, 1); if ~(isfloat(S0) && isreal(S0) && ~issparse(S0) && size(S0, 2) == n) error('afpsmat:invalidarg', ... 'S0 should be a non-sparse real square matrix.'); end if nargin < 2 q = 0.5; else if ~(isfloat(q) && isscalar(q) && isreal(q) && q > 0 && q < 1) error('afpsmat:invalidarg', ... 'q should be a real scalar with 0 < q < 1.'); end end %% main ss = S0; ss(1:(n+1):n^2) = []; if q == 0.5 dv = median(ss); else dv = quantile(ss, q); end S = S0; S(1:(n+1):n^2) = dv;
zzhangumd-smitoolbox
classics/cluster/afpsmat.m
MATLAB
mit
1,266
function [M, L] = afpclus(S, varargin) %AFPCLUS Clustering by Affinity Propagation % % [M, L] = AFPCLUS(S, ...); % % Performs Affinity propagation to cluster data samples. % % Input arguments: % - S: The similarity matrix, of size n x n. % Here, n is the number of samples. % % Note: S(i,i) is the preference to make the % i-th sample to be one of the centers. % % % Output arguments: % - M: The vector of center indices [1 x K] % % - L: The assignment vector [1 x n]. In particular, % L(i) = k indicates that the i-th sample is % associated with the examplar M(k). % % One can specify other options to control the procedure, in form % of name/value pairs: % % - 'MaxIter': The maximum number of iterations (default = 500) % % - 'LearnRate': The learning rate (default = 0.5) % updated = (1 - rate) * old + rate * new. % % - 'ExamIntv': The interval of examination (default = 10) % % The assignment is examined per ExamIntv iterations. % If the assignment within this period does not % change, the function considers the procedure % as converged. % % - 'Display': The level of displaying (default = 'off') % - 'off': display nothing % - 'final': display when the procedure finishes % - 'phase': display at each phase % (the examination marks the end of % a phase) % % Created by Dahua Lin, on Mar 28, 2012 %% parse input arguments n = size(S, 1); if ~(isfloat(S) && isreal(S) && ~issparse(S) && size(S, 2) == n) error('afpclus:invalidarg', 'S should be a real square matrix,'); end [maxiter, lrate, exam_intv, displevel] = check_opts(varargin); %% main % initialize A = zeros(n, n); R = zeros(n, n); % main loop t = 0; converged = false; while ~converged && t <= maxiter % compute responsibility R_pre = R; R = compute_r(S, A); if lrate < 1 R = (1 - lrate) * R_pre + lrate * R; end % compute availability A_pre = A; A = compute_a(R); if lrate < 1 A = (1 - lrate) * A_pre + lrate * A; end % examine if t == 0 M = get_centers(A, R); last_exam = 0; elseif t == last_exam + exam_intv M_last = M; M = get_centers(A, R); converged = isequal(M, M_last); last_exam = t; if displevel >= 2 ch = nnz(get_ass(S, M) - get_ass(S, M_last)); fprintf('Iter %5d: K = %4d (# change = %d)\n', ... t, numel(M), ch); end end t = t + 1; end if displevel >= 1 fprintf('Affinity propagation: # iters = %d, converged = %d\n', ... t, converged); end % Extract results M = get_centers(A, R).'; if ~isempty(M) K = numel(M); [~, L] = max(S(:,M), [], 2); L(M) = 1:K; L = L.'; else L = []; end %% core updating functions function R = compute_r(S, A) n = size(S, 1); AS = A + S; [Y, I] = max(AS, [], 2); u = (1:n)' + (I - 1) * n; AS(u) = -inf; Y2 = max(AS, [], 2); R = bsxfun(@minus, S, Y); R(u) = S(u) - Y2; function A = compute_a(R) n = size(R, 1); Rp = max(R, 0); didx = 1 : (n+1) : n^2; Rp(didx) = R(didx); A = bsxfun(@minus, sum(Rp, 1), Rp); dA = A(didx); A = min(A, 0); A(didx) = dA; function M = get_centers(A, R) M = find(diag(A) + diag(R) > 0); function L = get_ass(S, M) if ~isempty(M) K = numel(M); [~, c] = max(S(:,M), [], 2); c(M) = 1:K; L = M(c); else n = size(S, 1); L = zeros(n, 1); end %% Option setting function function [maxiter, lrate, exam_intv, displevel] = check_opts(nvlist) maxiter = 500; lrate = 0.5; exam_intv = 10; displevel = 0; if ~isempty(nvlist) onames = nvlist(1:2:end); ovals = nvlist(2:2:end); for i = 1 : numel(onames) cn = onames{i}; cv = ovals{i}; switch lower(cn) case 'maxiter' if ~(isnumeric(cv) && isscalar(cv) && cv >= 1) error('afpclus:invalidarg', ... 'MaxIter should be a positive integer.'); end maxiter = cv; case 'learnrate' if ~(isfloat(cv) && isreal(cv) && isscalar(cv) && ... cv > 0 && cv <= 1) error('afpclus:invalidarg', ... 'LearnRate should be a real scalar in (0, 1].'); end lrate = cv; case 'examintv' if ~(isnumeric(cv) && isscalar(cv) && cv == fix(cv) && cv >= 1) error('afpclus:invalidarg', ... 'ExamIntv should be a positive integer.'); end exam_intv = cv; case 'display' if ~ischar(cv) error('afpclus:invalidarg', ... 'Display should be a char string.'); end switch cv case 'off' displevel = 0; case 'final' displevel = 1; case 'phase' displevel = 2; otherwise error('afpclus:invalidarg', ... 'The value of Display is invalid.'); end otherwise error('afpclus:invalidarg', 'Unknown option name %s', cn); end end end
zzhangumd-smitoolbox
classics/cluster/afpclus.m
MATLAB
mit
6,008
function afpclus_demo(n, q) % Demo of afpclus in clustering 2D points % % afpclus_demo(n); % afpclus_demo(n, q); % % Input arguments: % - n: The number of sample points % - q: The quantile ratio (greater q encourages more centers) % (default = 0.5) % % Created by Dahua Lin, on Mar 27, 2012 % %% prepare data if nargin < 2 q = 0.5; end X = rand(2, n); %% run D = pwsqL2dist(X); S = afpsmat(-D, q); tic; [M, L] = afpclus(S, 'Display', 'phase'); et = toc; fprintf('Took %.4f sec.\n\n', et); %% visualize figure; A = sparse(1:n, M(L), true, n, n); gplot(A, X.'); hold on; plot(X(1,:), X(2,:), '.'); M = X(:, M); hold on; plot(M(1,:), M(2,:), 'ro', 'MarkerSize', 12, 'LineWidth', 2);
zzhangumd-smitoolbox
classics/cluster/afpclus_demo.m
MATLAB
mit
736
function d = clusvid(L1, L2) %CLUSVID variation information distance between clusters % % d = CLUSVID(L1, L2); % computes the variation information distance between two % clusters, which respectively label the same set of samples % with labels L1 and L2. % % In the input L1 and L2 should be vectors of the same size. % % History % ------- % - Created by Dahua Lin, on May 26, 2010 % %% verify input arguments if ~(isvector(L1) && isvector(L2) && isnumeric(L1) && isnumeric(L2) && ... isequal(size(L1), size(L2))) error('clusvid:invalidarg', ... 'L1 and L2 should be numeric vectors of the same size.'); end %% main b1 = min(L1) - 1; b2 = min(L2) - 1; if b1 ~= 0 L1 = L1 - b1; end if b2 ~= 0 L2 = L2 - b2; end m1 = max(L1); m2 = max(L2); n = numel(L1); p1 = intcount([1, m1], L1) / n; p2 = intcount([1, m2], L2) / n; P12 = cocounts([m1, m2], L1, L2); P12 = P12 * (1 / sum(P12(:))); ev1 = calc_ent(p1); ev2 = calc_ent(p2); ev12 = calc_ent(P12); d = 2 * ev12 - (ev1 + ev2); %% subfunction function ev = calc_ent(p) % A sub-function to calculate entropy p = p(p > 0); ev = - sum(p .* log(p));
zzhangumd-smitoolbox
classics/cluster/clusvid.m
MATLAB
mit
1,171
function [M, L, info] = kmedoid_std(C, M0, varargin) %KMEDOID_STD Implements standard K-medoid clustering % % [M, L] = KMEDOID_STD(C, M0, ...); % [M, L] = KMEDOID_STD(C, K, ...); % [M, L] = KMEDOID_STD({cfun, n}, M0, ...); % [M, L] = KMEDOID_STD({cfun, n}, K, ...); % % performs K-medoid clustering based on the pairwise cost matrix C. % % Suppose there are n samples. % % Input arguments: % - C: The cost matrix, of size n x n. % C(i, j) is the cost of assigning i-th sample to the % cluster with the j-th sample as the center. % % - cfun: The pairwise cost function. % % - n: The number of samples % % - M0: The initial selected medoids (an index vector of % length K > 1) % % - K: The number of medoids. % % If K instead of M0 is given, then M0 will be generated by randomly % picking K samples. One can also use kmseeds to pick the initial % medoids. % % Output arguments: % - M: The resultant medoids (a row vector of indices) % - L: The assignment of samples to medoids [1 x n]. % % Options: % % The user can specify options (in name/value pairs) to % control the algorithm. The options are listed as below: % % - MaxIter: the maximum number of iterations (default = 100) % % - TolC: the maximum allowable number of label changes at % convergence. (default = 0) % % - TolFun: the maximum allowable change of objective value at % convergence (default = 1e-8) % % - Display: the level of displaying (default = 'off') % - 'off': display nothing % - 'final': display a brief summary when the procedure % finishes % - 'iter': display at each iteration % % The user can also use kmopts function to construct % an option struct and use it as an input argument in the place % of the name/value pairs. % % % [M, L, info] = KMEDOID_STD( ... ); % % Additionally returns a struct with the information of the procedure % - niters: The number of iterations % - objv: The objective value (total costs) % - converged: Whether the procedure converged. % History % - Created by Dahua Lin, on Jun 4, 2008 % - Modified by Dahua Lin, on Sep 28, 2010 % - Modified by Dahua Lin, on Mar 28, 2012 % %% parse and verify input if isnumeric(C) n = size(C, 1); if ~(isfloat(C) && isreal(C) && ndims(C) == 2 && size(C,2) == n) error('kmedoid_std:invalidarg', ... 'C should be a real square matrix.'); end use_mat = true; elseif iscell(C) && numel(C) == 2 n = C{2}; C = C{1}; if ~(isa(C, 'function_handle') && isnumeric(n) && isscalar(n)) error('kmedoid:invalidarg', 'The first argument is invalid.'); end use_mat = false; else error('kmedoid_std:invalidarg', 'The first argument is invalid.'); end if isscalar(M0) K = M0; M0 = []; elseif isnumeric(M0) && isvector(M0) K = numel(M0); if size(M0, 1) > 1 M0 = M0.'; end else error('kmedoid_std:invalidarg', 'The second argument is invalid.'); end if ~(isnumeric(K) && (K >= 1 && K <= n) && K == fix(K)) error('kmedoid_std:invalidarg', 'The value of K is invalid.'); end % get options opts = kmopts(varargin{:}); tolfun = opts.tolfun; tolc = opts.tolc; maxiter = opts.maxiter; displevel = opts.displevel; %% main % initialize medoids if isempty(M0) M0 = randpick(n, K); end M = M0; % initialize assignments and objective costs = calc_costs(C, M, n, use_mat); [min_costs, L] = min(costs, [], 2); L = L.'; objv = sum(min_costs); % main loop t = 0; converged = false; if displevel >= 2 print_iter_header(); end while ~converged && t < maxiter t = t + 1; % identify affected clusters if t == 1 aff_cs = 1 : K; else aff_cs = find(intcount(K, [L(chs), L_pre(chs)])); end % update centers gs = intgroup(K, L); for k = aff_cs gk = gs{k}; Ck = C(gk, gk); [~, si] = min(sum(Ck, 1)); M(k) = gk(si); end % re-compute costs if numel(aff_cs) >= K / 2 costs = calc_costs(C, M, n, use_mat); else costs(:, aff_cs) = calc_costs(C, M(:, aff_cs), n, use_mat); end % re-assign samples to centers L_pre = L; [min_costs, L] = min(costs, [], 2); L = L.'; % determine convergence objv_pre = objv; objv = sum(min_costs); v_ch = objv - objv_pre; chs = find(L ~= L_pre); converged = (abs(v_ch) <= tolfun || numel(chs) <= tolc); % print iteration info if displevel >= 2 print_iter(t, numel(chs), aff_cs, objv, v_ch); end end if displevel >= 1 print_final(t, objv, converged); end if nargout >= 3 info.niters = t; info.objv = objv; info.converged = converged; end %% Auxiliary functions function costs = calc_costs(C, M, n, use_mat) if use_mat costs = C(:, M); else costs = C(1:n, M); end %% Printing functions function print_iter_header() fprintf(' Iter # ch.assign (aff.clus) objv (change) \n'); fprintf('------------------------------------------------------\n'); function print_iter(it, ch, afc, objv, vch) fprintf('%5d %7d (%5d) %12.6g (%.4g)\n', it, ch, numel(afc), objv, vch); function print_final(it, objv, converged) fprintf('K-medoid: total_cost = %.6g, converged = %d [total # iters = %d]\n', ... objv, converged, it);
zzhangumd-smitoolbox
classics/cluster/kmedoid_std.m
MATLAB
mit
6,087
function S = kmopts(varargin) %KMOPTS Options for K-means and K-medoid % % S = KMOPTS; % % returns the default option struct. % % S = KMOPTS('name1', value1, 'name2', value2, ...); % % constructs an option struct, modifying part of the option values % using the input values. % % S = KMOPTS(S0, 'name1', value1, 'name2', value2, ...); % % constructs a new option struct, updating the values in an old % option struct given by S0. % % Please refer to the help of kmeans_ex for details. % % History % ------- % - Created by Dahua Lin, on Sep 27, 2010 % - Modified by Dahua Lin, on Mar 27, 2012 % %% parse inputs if nargin == 0 S = default_opts(); return; elseif ischar(varargin{1}) S = default_opts(); nvlist = varargin; elseif isstruct(varargin{1}) S = varargin{1}; if ~(isscalar(S) && isfield(S, 'tag') && strcmp(S.tag, 'kmopts')) error('kmopts:invalidarg', 'The struct S0 is invalid.'); end if numel(varargin) == 1 return; end nvlist = varargin(2:end); else error('kmopts:invalidarg', 'Invalid input arguments.'); end %% main % update struct onames = nvlist(1:2:end); ovals = nvlist(2:2:end); n = length(onames); if ~(iscellstr(onames) && n == length(ovals)) error('kmopts:invalidarg', ... 'The name/value pair list is invalid.'); end for i = 1 : n name = lower(onames{i}); v = ovals{i}; switch name case 'maxiter' if ~(isnumeric(v) && isscalar(v) && v > 0) opterr('%s must be a positive scalar.', name); end case {'tolc', 'tolfun'} if ~(isnumeric(v) && isscalar(v) && isreal(v) && v >= 0) opterr('%s must be a non-negative real scalar.', name); end case 'display' if ~ischar(v) opterr('display must be a char string.'); end v = lower(v); switch v case 'off' S.displevel = 0; case 'final' S.displevel = 1; case 'iter' S.displevel = 2; otherwise error('The value of display is invalid.'); end otherwise error('kmopts:invalidarg', 'Invalid option name %s', name); end S.(name) = v; end %% sub function function S = default_opts() S = struct( ... 'tag', 'kmopts', ... 'maxiter', 100, ... 'tolfun', 1e-8, ... 'tolc', 0, ... 'display', 'off', ... 'displevel', 0); function opterr(msg, varargin) error('kmopts:invalidopt', msg, varargin{:});
zzhangumd-smitoolbox
classics/cluster/kmopts.m
MATLAB
mit
2,826
function [M, L, info] = kmeans_std(X, M0, varargin) %KMEANS_STD Standard K-means algorithm % % [M, L] = KMEANS_STD(X, K, ...); % [M, L] = KMEANS_STD(X, M0, ...); % [M, L] = KMEANS_STD({X, w}, K, ...); % [M, L] = KMEANS_STD({X, w}, M0, ...); % % This function implements the standard K-means algorithm. % % Input: % - X: The matrix of input samples. Each column in X corresponds % to one sample. % % - w: The weights of samples (when the samples are weighted) % % - K: The number of clusters. % % - M0: The initial centers. % % Note that if K instead of M0 is input, the function will randomly % select K samples from X as the initial centers. One can also % use the function kmseed to generate the initial centers. % % Output: % - M: The resultant means, which is a matrix of size d x K, % where d is the space dimension, and K is the number of % clusters. % % - L: The assignment of samples to clusters. Suppose X contains % n samples, then L is a 1 x n row vector, whose values are % in {1, 2, ..., K}, and L(i) corresponds to X(:,i). % % % Options: % % The user can specify options (in name/value pairs) to % control the algorithm. The options are listed as below: % % - MaxIter: the maximum number of iterations (default = 100) % % - TolC: the maximum allowable number of label changes at % convergence. (default = 0) % % - TolFun: the maximum allowable change of objective value at % convergence (default = 1e-8) % % - Display: the level of displaying (default = 'off') % - 'off': display nothing % - 'final': display a brief summary when the procedure % finishes % - 'iter': display at each iteration % % The user can also use kmopts function to construct % an option struct and use it as an input argument in the place % of the name/value pairs. % % % [M, L, info] = KMEANS_STD( ... ); % % additionally returns the information of the K-means procedure. % % info is a struct with the following fields: % - niters: The number of elapsed iterations % - objv: The objective value at last step (total cost) % - converged: Whether the procedure converged % % History % ------- % - Created by Dahua Lin, on Sep 27, 2010 % - Modified by Dahua Lin, on Mar 27 2012 % %% parse and verify input if isnumeric(X) wx = []; elseif iscell(X) && numel(X) == 2 wx = X{2}; X = X{1}; end if ~(isfloat(X) && isreal(X) && ndims(X) == 2) error('kmeans_std:invalidarg', 'X should be a real matrix.'); end [d, n] = size(X); if ~isempty(wx) if ~(isfloat(wx) && isreal(wx) && isvector(wx) && numel(wx) == n) error('kmeans_std:invalidarg', ... 'w should be a real vector of length n.'); end if size(wx, 2) > 1 wx = wx.'; % turn w into a column vector end end if isscalar(M0) K = M0; M0 = []; else K = size(M0, 2); if ~(isfloat(M0) && ndims(M0) == 2 && size(M0, 1) == d) error('kmeans_std:invalidarg', 'M0 should be a d x K numeric matrix.'); end end if ~(isnumeric(K) && (K >= 1 && K <= n) && K == fix(K)) error('kmeans_std:invalidarg', 'The value of K is invalid.'); end % get options opts = kmopts(varargin{:}); tolfun = opts.tolfun; tolc = opts.tolc; maxiter = opts.maxiter; displevel = opts.displevel; %% main % initialize centers if isempty(M0) seeds = randpick(n, K); M0 = X(:, seeds); end M = M0; % initialize assignments and objective cpre = calc_costs_pre(X); costs = calc_costs(M, X, cpre); [min_costs, L] = min(costs, [], 1); objv = calc_objv(min_costs, wx); % main loop t = 0; converged = false; if displevel >= 2 print_iter_header(); end while ~converged && t < maxiter t = t + 1; % identify affected clusters if t == 1 aff_cs = 1 : K; else aff_cs = find(intcount(K, [L(chs), L_pre(chs)])); end % update centers to_rp = false(1, K); gs = intgroup(K, L); for k = aff_cs gk = gs{k}; if ~isempty(gk) M(:,k) = calc_mean(X, wx, gk); else to_rp(k) = 1; % indicate to repick the k-th center end end % repick new centers if needed if any(to_rp) rps = find(to_rp); M(:, rps) = X(:, randpick(n, numel(rps))); end % re-compute costs if numel(aff_cs) >= K / 2 costs = calc_costs(M, X, cpre); else costs(aff_cs, :) = calc_costs(M(:, aff_cs), X, cpre); end % re-assign samples to centers L_pre = L; [min_costs, L] = min(costs, [], 1); % determine convergence objv_pre = objv; objv = calc_objv(min_costs, wx); v_ch = objv - objv_pre; chs = find(L ~= L_pre); converged = (abs(v_ch) <= tolfun || numel(chs) <= tolc); % print iteration info if displevel >= 2 print_iter(t, numel(chs), aff_cs, objv, v_ch); end end if displevel >= 1 print_final(t, objv, converged); end if nargout >= 3 info.niters = t; info.objv = objv; info.converged = converged; end %% Auxiliary functions function v = calc_mean(X, w, si) if isempty(w) cn = numel(si); cw = constmat(cn, 1, 1/cn); else cw = w(si); cw = cw * (1 / sum(cw)); end v = X(:, si) * cw; function cpre = calc_costs_pre(X) cpre.sX2 = sum(X.^2, 1); function C = calc_costs(M, X, cpre) C = (-2) * (M' * X); C = bsxfun(@plus, C, sum(M .^ 2, 1).'); C = bsxfun(@plus, C, cpre.sX2); function v = calc_objv(cs, w) if isempty(w) v = sum(cs); else v = cs * w; end %% Printing functions function print_iter_header() fprintf(' Iter # ch.assign (aff.clus) objv (change) \n'); fprintf('------------------------------------------------------\n'); function print_iter(it, ch, afc, objv, vch) fprintf('%5d %7d (%5d) %12.6g (%.4g)\n', it, ch, numel(afc), objv, vch); function print_final(it, objv, converged) fprintf('K-means: total_cost = %.6g, converged = %d [total # iters = %d]\n', ... objv, converged, it);
zzhangumd-smitoolbox
classics/cluster/kmeans_std.m
MATLAB
mit
6,483
function K = gausskernel(X, Y, sigma) %GAUSSKERNEL The Gaussian kernel (radial basis function) % % K = GAUSSKERNEL(X, [], sigma); % K = GAUSSKERNEL(X, Y, sigma); % % Evaluates the Gaussian kernel in a pairwise manner. % % The Gaussian kernel is defined to be % % k(x, y) = exp( - ||x - y||^2 / (2 * sigma^2) ). % % Here, each column of X and Y is a sample. Suppose X has m columns % and Y has n columns, then K is a matrix of size m x n. % % If Y is input as empty, it means that X and Y are the same. % % Created by Dahua Lin, on Dec 31, 2011 % %% main if isempty(Y) sx = sum(X.^2, 1); D = bsxfun(@minus, bsxfun(@plus, sx.', sx), 2 * (X' * X)); else sx = sum(X.^2, 1); sy = sum(Y.^2, 1); D = bsxfun(@minus, bsxfun(@plus, sx.', sy), 2 * (X' * Y)); end K = exp(- D * (1 / (2 * sigma^2)));
zzhangumd-smitoolbox
classics/kernels/gausskernel.m
MATLAB
mit
880
function K = polykernel(X, Y, a, b, d) %POLYKERNEL The polynomial kernel % % K = POLYKERNEL(X, [], a, b, d); % K = POLYKERNEL(X, Y, a, b, d); % % Evaluates the polynomial kernel in a pairwise manner. % % The polynomial kernel is defined to be % % k(x, y) = (a * (x' * y) + b)^d. % % Here, each column of X and Y is a sample. Suppose X has m columns % and Y has n columns, then K is a matrix of size m x n. % % If Y is input as empty, it means that X and Y are the same. % % Created by Dahua Lin, on Dec 31, 2011 % %% main if isempty(Y) P = X' * X; else P = X' * Y; end K = (a * P + b) .^ d;
zzhangumd-smitoolbox
classics/kernels/polykernel.m
MATLAB
mit
662
function K = sigmoidkernel(X, Y, a, b) %SIGMOIDKERNEL Sigmoid kernel % % K = SIGMOIDKERNEL(X, [], a, b); % K = SIGMOIDKERNEL(X, Y, a, b); % % Evaluates the sigmoid kernel in a pairwise manner. % % The polynomial kernel is defined to be % % k(x, y) = tanh(a * (x' * y) + b) % % Here, each column of X and Y is a sample. Suppose X has m columns % and Y has n columns, then K is a matrix of size m x n. % % If Y is input as empty, it means that X and Y are the same. % % Created by Dahua Lin, on Dec 31, 2011 % %% main if isempty(Y) P = X' * X; else P = X' * Y; end K = tanh(a * P + b);
zzhangumd-smitoolbox
classics/kernels/sigmoidkernel.m
MATLAB
mit
656
function invmqkernel(X, Y, a, b) %INVMQKERNEL The inverse multiquadric kernel % % K = INVMQKERNEL(X, [], a, b); % K = INVMQKERNEL(X, Y, a, b); % % Evaluates the inverse multi-quadric kernel in a pairwise manner. % % The inverse multi-quadric kernel is defined to be % % k(x, y) = 1 / (a * ||x - y||^2 + b) % % Here, each column of X and Y is a sample. Suppose X has m columns % and Y has n columns, then K is a matrix of size m x n. % % If Y is input as empty, it means that X and Y are the same. % % Created by Dahua Lin, on Dec 31, 2011 % %% main if isempty(Y) sx = sum(X.^2, 1); D = bsxfun(@minus, bsxfun(@plus, sx.', sx), 2 * (X' * X)); else sx = sum(X.^2, 1); sy = sum(Y.^2, 1); D = bsxfun(@minus, bsxfun(@plus, sx.', sy), 2 * (X' * Y)); end K = 1 ./ (a * D + b);
zzhangumd-smitoolbox
classics/kernels/invmqkernel.m
MATLAB
mit
853
function tf = is_svm_dual_sol(S) %IS_SVM_PROBLEM Whether the input argument is an SVM dual-solution struct % % tf = is_svm_dual_sol(S); % returns whether S is a valid SVM problem struct. % % Created by Dahua Lin, on Jan 17, 2012 % %% main tf = isstruct(S) && numel(S) == 1 && isfield(S, 'tag') && ... strcmp(S.tag, 'svm-dual-sol');
zzhangumd-smitoolbox
classics/svm/is_svm_dual_sol.m
MATLAB
mit
347
function b = svm_dual_offset(S, K, alpha, si) %SVM_DUAL_OFFSET Solve the offset value for dual SVM training % % b = SVM_DUAL_OFFSET(S, K, alpha, si); % % solves the offset value b for dual SVM training. % % Note that b is fixed to 0 for SVM ranking. % % Inputs % - S: The SVM problem struct % - K: The kernel matrix over the entire training set % - alpha: The solved alpha vector. % - si: The indices of support vectors. % % Created by Dahua Lin, on Jan 18, 2012 % %% main switch S.type case 'class' b = offset_for_class(S, K, alpha, si); case 'regress' b = offset_for_regress(S, K, alpha, si); case 'rank' b = 0; otherwise error('svm_dual_offset:invalidarg', ... 'Unsupported SVM type %s for svm_dual_offset.', S.type); end %% Core functions function b = offset_for_class(S, K, alpha, si) y = S.y.'; c = S.C.'; ep = min(1e-9 * c, 1e-6); ui = find(alpha > ep & alpha < c - ep); a = y(si) .* alpha(si); if ~isempty(ui) b = median(y(ui) - K(ui, si) * a); else b = 0; warning('svm_dual_offset:nosuppvec', ... 'No training samples found residing on the margin.'); end function b = offset_for_regress(S, K, alpha, si) n = S.n; a1 = alpha(1:n); a2 = alpha(n+1:end); if isscalar(S.C) c = S.C; else c = S.C.'; end ep = min(1e-9 * c, 1e-6); s1 = find(a1 < c - ep | a2 > ep); s2 = find(a1 > ep | a2 < c - ep); if ~isempty(s1) && ~isempty(s2) tol = S.tol; y = S.y.'; ad = a1 - a2; Ks = K(:, si); ad = ad(si); m1 = max(y(s1) - Ks(s1, :) * ad - tol); m2 = min(y(s2) - Ks(s2, :) * ad - tol); b0 = (m1 + m2) / 2; u = Ks * ad; b = fminsearch(@(x) fun_r(x, u, y, c), b0); else b = 0; warning('svm_dual_offset:nosuppvec', ... 'No proper training samples to bound of value of b.'); end function v = fun_r(b, u, y, c) % objective fun for searching b loss = max(abs(u + b - y), 0); if isscalar(c) v = c * sum(loss); else v = sum(loss .* c); end
zzhangumd-smitoolbox
classics/svm/svm_dual_offset.m
MATLAB
mit
2,141