To get the names of the selected features (non-zero coefficients) from a Lasso regression in Python, you can use the following code:
main.py324 chars6 lines
Here, X
is your feature matrix and y
is your target variable. The alpha
parameter controls the strength of the L1 penalty in the Lasso regression, and you can set it to a value of your choice.
Once you fit the Lasso model, you can obtain the names of the selected features by using the coefficients that are non-zero (i.e., the features with non-zero coefficients are the ones that were selected). In the code, we obtain the column names of the feature matrix X
where the coefficients are non-zero using the condition lasso.coef_ != 0
.
Note: Make sure to preprocess your feature matrix appropriately before fitting the Lasso regression.
gistlibby LogSnag