annotate toolboxes/FullBNT-1.0.7/KPMstats/linear_regression.m @ 0:cc4b1211e677 tip

initial commit to HG from Changeset: 646 (e263d8a21543) added further path and more save "camirversion.m"
author Daniel Wolff
date Fri, 19 Aug 2016 13:07:06 +0200
parents
children
rev   line source
Daniel@0 1 function [muY, SigmaY, weightsY] = linear_regression(X, Y, varargin)
Daniel@0 2 % LINEAR_REGRESSION Fit params for P(Y|X) = N(Y; W X + mu, Sigma)
Daniel@0 3 %
Daniel@0 4 % X(:, t) is the t'th input example
Daniel@0 5 % Y(:, t) is the t'th output example
Daniel@0 6 %
Daniel@0 7 % Kevin Murphy, August 2003
Daniel@0 8 %
Daniel@0 9 % This is a special case of cwr_em with 1 cluster.
Daniel@0 10 % You can also think of it as a front end to clg_Mstep.
Daniel@0 11
Daniel@0 12 [cov_typeY, clamp_weights, muY, SigmaY, weightsY,...
Daniel@0 13 cov_priorY, regress, clamp_covY] = process_options(...
Daniel@0 14 varargin, ...
Daniel@0 15 'cov_typeY', 'full', 'clamp_weights', 0, ...
Daniel@0 16 'muY', [], 'SigmaY', [], 'weightsY', [], ...
Daniel@0 17 'cov_priorY', [], 'regress', 1, 'clamp_covY', 0);
Daniel@0 18
Daniel@0 19 [nx N] = size(X);
Daniel@0 20 [ny N2] = size(Y);
Daniel@0 21 if N ~= N2
Daniel@0 22 error(sprintf('nsamples X (%d) ~= nsamples Y (%d)', N, N2));
Daniel@0 23 end
Daniel@0 24
Daniel@0 25 w = 1/N;
Daniel@0 26 WYbig = Y*w;
Daniel@0 27 WYY = WYbig * Y';
Daniel@0 28 WY = sum(WYbig, 2);
Daniel@0 29 WYTY = sum(diag(WYbig' * Y));
Daniel@0 30 if ~regress
Daniel@0 31 % This is just fitting an unconditional Gaussian
Daniel@0 32 weightsY = [];
Daniel@0 33 [muY, SigmaY] = ...
Daniel@0 34 mixgauss_Mstep(1, WY, WYY, WYTY, ...
Daniel@0 35 'cov_type', cov_typeY, 'cov_prior', cov_priorY);
Daniel@0 36 % There is a much easier way...
Daniel@0 37 assert(approxeq(muY, mean(Y')))
Daniel@0 38 assert(approxeq(SigmaY, cov(Y') + 0.01*eye(ny)))
Daniel@0 39 else
Daniel@0 40 % This is just linear regression
Daniel@0 41 WXbig = X*w;
Daniel@0 42 WXX = WXbig * X';
Daniel@0 43 WX = sum(WXbig, 2);
Daniel@0 44 WXTX = sum(diag(WXbig' * X));
Daniel@0 45 WXY = WXbig * Y';
Daniel@0 46 [muY, SigmaY, weightsY] = ...
Daniel@0 47 clg_Mstep(1, WY, WYY, WYTY, WX, WXX, WXY, ...
Daniel@0 48 'cov_type', cov_typeY, 'cov_prior', cov_priorY);
Daniel@0 49 end
Daniel@0 50 if clamp_covY, SigmaY = SigmaY; end
Daniel@0 51 if clamp_weights, weightsY = weightsY; end
Daniel@0 52
Daniel@0 53 if nx==1 & ny==1 & regress
Daniel@0 54 P = polyfit(X,Y); % Y = P(1) X^1 + P(2) X^0 = ax + b
Daniel@0 55 assert(approxeq(muY, P(2)))
Daniel@0 56 assert(approxeq(weightsY, P(1)))
Daniel@0 57 end
Daniel@0 58
Daniel@0 59 %%%%%%%% Test
Daniel@0 60 if 0
Daniel@0 61 c1 = randn(2,100); c2 = randn(2,100);
Daniel@0 62 y = c2(1,:); X = [ones(size(c1,2),1) c1'];
Daniel@0 63 b = regress(y(:), X); % stats toolbox
Daniel@0 64 [m,s,w] = linear_regression(c1, y);
Daniel@0 65 assert(approxeq(b(1),m))
Daniel@0 66 assert(approxeq(b(2), w(1)))
Daniel@0 67 assert(approxeq(b(3), w(2)))
Daniel@0 68 end