The function takes in a matrix of predictors and a vector of outcomes, and returns the minimum and
maximum values of the regularization parameter lambda that should be used in a logistic regression
model.
The function is based on the paper Regularization Paths for Generalized Linear Models via
Coordinate Descent by Friedman, Hastie, and Tibshirani.
Parameters: |
-
X
–
-
y
–
-
alpha
–
the elastic net mixing parameter. Defaults to 1
|
Returns: |
-
–
the minimum and maximum values of the regularization parameter lambda.
|
Source code in postpacu/utils.py
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135 | def get_lr_penalty(X, y, alpha=1):
"""
The function takes in a matrix of predictors and a vector of outcomes, and returns the minimum and
maximum values of the regularization parameter lambda that should be used in a logistic regression
model.
The function is based on the paper [Regularization Paths for Generalized Linear Models via
Coordinate Descent](http://www.jstatsoft.org/v33/i01/paper) by Friedman, Hastie, and Tibshirani.
Args:
X: the data matrix
y: the target variable
alpha: the elastic net mixing parameter. Defaults to 1
Returns:
the minimum and maximum values of the regularization parameter lambda.
"""
# recreate lambda.max from R glmnet according to paper description
# http://www.jstatsoft.org/v33/i01/paper
# lambda.min in glmnet does not work as paper describes;
# however, I'm sticking with the paper's description here for lambda_min
# returns C_min, C_max for use in sklearn logistic regression
# ensure numeric stability -- matching what glmnet does
if alpha < 0.000001:
alpha = 0.000001
# paper says scale y, but that's for regression
# I can only recreate glmnet binomial lambda.max result by setting proportions of classes
# see discussion:
# https://stackoverflow.com/questions/25257780/how-does-glmnet-compute-the-maximal-lambda-value
counter = Counter(y)
negative_prop = counter[0] / (counter[1] + counter[0])
positive_prop = 1 - negative_prop
if y.ndim == 1:
y = np.asarray(y)
y = y[:, np.newaxis]
if X.shape[0] < X.shape[1]:
lambda_min_ratio = 0.01
else:
lambda_min_ratio = 1e-04
sdX = np.apply_along_axis(mysd, 0, X)
sX = scale(X, with_std=False) / sdX[None, :]
sy = np.where(y == 0, -1 * positive_prop, negative_prop)[:]
lambda_max = max(abs(np.sum(sX * sy, axis=0))) / (len(sy) * alpha)
lambda_min = lambda_min_ratio * lambda_max
# sklearn "C" and glmnet "lambda" are inverse of one another
return 1 / lambda_max, 1 / lambda_min
|