comparison toolboxes/FullBNT-1.0.7/KPMstats/linear_regression.m @ 0:e9a9cd732c1e tip

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