forked from viggin/yan-prtools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
regress_ridge_tr.m
39 lines (32 loc) · 1.18 KB
/
regress_ridge_tr.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
function [model] = regress_ridge_tr(X,Y,param)
%Ridge regression.
% Can set separate regularization for each ft according to prior knowledge.
% Can also set weight for each sample.
%
% X : each row is a sample.
% Y : a column vector.
% PARAM: struct of parameters. The beginning part of this code (before
% defParam) explains each parameter, and also sets the default parameters.
% You can change parameter p to x by setting PARAM.p = x. For parameters
% that are not set, default values will be used.
% Return:
% MODEL: a struct containing coefficients.
%
% Ke YAN, 2016, Tsinghua Univ. http://yanke23.com, [email protected]
[nSmp,nFt] = size(X);
ftPenal = ones(1,nFt); % penalization weight of each feature. The larger,
% the feature will be less relied in the model
smpWt = ones(nSmp,1); % importance of each sample. The larger the more important
lambda = 1; % regularization parameter
defParam
W = diag(smpWt.^2);
b0 = mean(Y);
Yz = Y-b0; % shift Y
[Xz, muZ, sigmaZ] = zscore(X); % scale X
R = diag(ftPenal.^2)*lambda; % Tikhonov Regularization Matrix
b = (Xz'*W*Xz + R) \ (Xz' *W* Yz);
% scale and shift back
bs = b;
bs(sigmaZ~=0) = b(sigmaZ~=0)./sigmaZ(sigmaZ~=0)';
model.b = [b0-muZ*bs; bs];
end