Skip to content

Commit 50981f1

Browse files
mariomario
authored andcommitted
adjusted regress to also act as ridge regression
1 parent 51833ca commit 50981f1

File tree

1 file changed

+34
-4
lines changed

1 file changed

+34
-4
lines changed

code/python/cni_toolbox/gadgets.py

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,26 +49,56 @@ def two_gamma(timepoints):
4949
return hrf
5050

5151

52-
def regress(Y, X):
52+
53+
def regress(Y, X, l = 0.):
54+
5355
'''
5456
Parameters
5557
----------
5658
Y : floating point array (observations-by-outcomes)
5759
outcome variables
5860
X : floating pint array (observation-by-predictors)
5961
predictors
62+
l : float
63+
(optional) ridge penalty parameter
6064
6165
Returns
6266
-------
63-
floating point array (predictors-by-outcomes)
67+
beta : floating point array (predictors-by-outcomes)
6468
beta coefficients
6569
'''
70+
71+
if X.ndim>1:
72+
n_observations, n_predictors = X.shape
73+
74+
else:
75+
n_observations = X.size
76+
n_predictors = 1
6677

67-
return np.matmul(
78+
79+
if n_observations < n_predictors:
80+
U, D, V = np.linalg.svd(X, full_matrices = False)
81+
82+
D = np.diag(D)
83+
beta = np.matmul(
84+
np.matmul(
85+
np.matmul(
86+
np.matmul(
87+
V.transpose(),
88+
sc.linalg.inv(
89+
D**2 +
90+
l * np.eye(n_observations))),
91+
D),
92+
U.transpose()), Y)
93+
else:
94+
beta = np.matmul(
6895
np.matmul(
6996
sc.linalg.inv(
70-
np.matmul(X.transpose(), X)),
97+
np.matmul(X.transpose(), X) +
98+
l * np.eye(n_predictors)),
7199
X.transpose()), Y)
100+
101+
return beta
72102

73103
def correct_autocorr(X, W):
74104
'''

0 commit comments

Comments
 (0)