Skip to content

Commit 2d90b88

Browse files
committed
explain of l1 regularization
1 parent 534e31c commit 2d90b88

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

ml-concepts/l1_regularization.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from sklearn.linear_model import Lasso
2+
from sklearn.model_selection import train_test_split
3+
from sklearn.datasets import fetch_california_housing
4+
from sklearn.metrics import mean_squared_error
5+
6+
data = fetch_california_housing()
7+
X = data.data
8+
y = data.target
9+
10+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
11+
12+
# define the L1 / lasso regression model with a chosen alpha (λ)
13+
lasso = Lasso(alpha=0.1)
14+
15+
lasso.fit(X_train, y_train)
16+
17+
y_pred = lasso.predict(X_test)
18+
19+
# eval the model
20+
mse = mean_squared_error(y_test, y_pred)
21+
print(f'Mean Squared Error: {mse}')
22+
23+
print('Coefficients:', lasso.coef_)

0 commit comments

Comments
 (0)