Table of Contents

    Lasso Regression

    MACHINE LEARNING

    Lasso Regression

    A regularized regression technique that performs both shrinkage and automatic feature selection.

    What is Lasso Regression?

    Lasso Regression (Least Absolute Shrinkage and Selection Operator) is a type of regularized linear regression that adds an L1 penalty to the cost function. It shrinks coefficients and can make some of them exactly zero, effectively performing feature selection.

    In simple words — Lasso Regression automatically removes unimportant features by reducing their coefficients to zero.

    Why Lasso Regression?

    Standard Linear Regression can struggle with:

    Linear Regression Problems

    • Includes all features (even useless ones)
    • Overfits easily
    • Cannot perform feature selection
    • Sensitive to noise

    Lasso Solves It

    • Eliminates irrelevant features
    • Reduces overfitting
    • Performs feature selection
    • Simplifies the model

    Mathematical Formula

    Standard Linear Regression Loss:

    LINEAR LOSS
    $$ \text{Loss} = \sum_{i=1}^{n} (y_i - \hat{y}_i)^2 $$

    Lasso Regression Loss (with L1 penalty):

    LASSO LOSS (L1 REGULARIZATION)
    $$ \text{Loss} = \sum_{i=1}^{n} (y_i - \hat{y}_i)^2 + \lambda \sum_{j=1}^{p} |b_j| $$

    Where:

    • yᵢ = actual value
    • ŷᵢ = predicted value
    • |bⱼ| = absolute value of feature coefficient
    • λ (lambda / alpha) = regularization strength
    L1 penalty uses the absolute value of coefficients, which can force some coefficients to become exactly zero — unlike Ridge.

    How Lasso Performs Feature Selection

    The L1 penalty creates sharp corners in the cost function. When the optimizer reaches a corner, some coefficients become exactly zero, effectively removing those features from the model.

    • Small α → fewer features eliminated.
    • Large α → many features eliminated.
    • Very large α → all coefficients → 0 (model fails).

    Role of α (Alpha / Lambda)

    α Value Effect Result
    α = 0Same as Linear RegressionNo feature selection
    Small αSlight shrinkageFew coefficients near 0
    Moderate αStrong shrinkageSome coefficients become 0
    Large αHeavy regularizationMany features removed
    Very Large αAll coefficients become 0Useless model

    How Lasso Regression Works

    Step-by-Step Process

    • Fit a regression model with all features.
    • Calculate sum of squared errors (loss).
    • Add L1 penalty: λ × Σ|bⱼ|.
    • Minimize total loss using coordinate descent.
    • Some coefficients become exactly 0 (removed).
    • Predict using remaining important features.

    Python Example

    Prerequisites: Python 3.x, pandas, numpy, scikit-learn.
    pip install pandas numpy scikit-learn
    import pandas as pd
    from sklearn.linear_model import Lasso
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import mean_squared_error, r2_score
    
    # Sample dataset
    data = {
        "Area":     [1000, 1500, 2000, 2500, 3000, 3500, 4000],
        "Bedrooms": [2, 3, 3, 4, 4, 5, 5],
        "Age":      [10, 5, 15, 8, 3, 2, 1],
        "Garden":   [0, 1, 0, 1, 1, 0, 1],
        "Price":    [40, 55, 65, 80, 100, 120, 140]
    }
    df = pd.DataFrame(data)
    
    X = df[["Area", "Bedrooms", "Age", "Garden"]]
    y = df["Price"]
    
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
    
    # Train Lasso Regression
    lasso = Lasso(alpha=1.0)
    lasso.fit(X_train, y_train)
    
    # Predict
    y_pred = lasso.predict(X_test)
    
    print("Coefficients:", lasso.coef_)
    print("Intercept:", lasso.intercept_)
    print("MSE:", mean_squared_error(y_test, y_pred))
    print("R²:", r2_score(y_test, y_pred))
    Output Some coefficients may become exactly 0 — meaning those features were automatically removed by the model.

    Comparing Different Alpha Values

    for alpha in [0.01, 0.1, 1, 10, 100]:
        model = Lasso(alpha=alpha)
        model.fit(X_train, y_train)
        print(f"Alpha={alpha}, Coefficients={model.coef_}")
    Observation As α increases, more coefficients become 0 — the model becomes simpler with fewer features.

    Linear vs Lasso Regression

    Aspect Linear Regression Lasso Regression
    Regularization None L1 (absolute coefficients)
    Feature Selection No Yes (auto)
    Overfitting High Reduced
    Coefficients All non-zero Some become 0

    Ridge vs Lasso Regression

    Aspect Ridge (L2) Lasso (L1)
    Penalty Type Sum of squared coefficients Sum of absolute coefficients
    Shrinkage Reduces but never zero Can shrink to exactly zero
    Feature Selection No Yes
    Best For Many correlated features Many irrelevant features
    Complexity Stable Sparse model

    Bias-Variance Tradeoff

    Linear Regression

    • Low Bias
    • High Variance
    • Overfits

    Lasso Regression

    • Higher Bias
    • Lower Variance
    • Better generalization

    Real-Life Analogy

    Lasso Regression = Smart Packing

    Imagine packing a suitcase for travel. Lasso decides which clothes are essential and discards the rest. Similarly, Lasso Regression keeps only the most useful features and removes unnecessary ones.

    Real-World Applications

    Finance

    • Predict stock returns
    • Risk modeling

    Healthcare

    • Identify important biomarkers
    • Predict patient outcomes

    Marketing

    • Identify top sales drivers
    • Customer behavior analysis

    Real Estate

    • Predict house prices
    • Identify important property factors

    Genomics

    • Identify important genes
    • Reduce thousands of features

    Big Data

    • Handle high-dimensional data
    • Eliminate noise features

    Advantages

    • Performs automatic feature selection.
    • Reduces overfitting.
    • Simplifies models with many features.
    • Easier to interpret due to fewer features.
    • Great for high-dimensional datasets.

    Disadvantages

    Limitation 1 May randomly select one feature from a group of correlated features.
    Limitation 2 Sensitive to the choice of α.
    Limitation 3 Can underfit if α is too large.
    Limitation 4 Doesn't perform as well as Ridge when all features are useful.

    Common Mistakes to Avoid

    Mistake 1 Not standardizing features before applying Lasso.
    Mistake 2 Using a fixed α without cross-validation.
    Mistake 3 Applying Lasso to highly correlated features without checking.
    Mistake 4 Choosing very large α — leads to underfitting.

    Auto-Tuning with LassoCV

    from sklearn.linear_model import LassoCV
    
    lasso_cv = LassoCV(alphas=[0.01, 0.1, 1, 10, 100], cv=5)
    lasso_cv.fit(X_train, y_train)
    
    print("Best Alpha:", lasso_cv.alpha_)
    print("Best Score:", lasso_cv.score(X_test, y_test))
    Why Useful Automatically chooses the best α via cross-validation.

    Best Practices

    Quick Tips

    • Standardize features before applying Lasso.
    • Use LassoCV to find best α automatically.
    • Compare Lasso with Ridge and ElasticNet.
    • Visualize coefficients to understand selection.
    • Use Lasso when features are many and some irrelevant.
    • Always validate with cross-validation.

    Importance of Lasso Regression

    Automatic Feature Selection

    • Removes irrelevant features
    • Cleaner, simpler model

    Reduces Overfitting

    • L1 regularization
    • Improves generalization

    Foundation for ElasticNet

    • Combined with Ridge for best of both
    • Used in advanced ML pipelines

    Better Interpretability

    • Shows important predictors
    • Easy to explain to stakeholders

    Golden Rule

    REMEMBER
    Too Many FeaturesUse LassoAuto Feature Selection

    Key Takeaway

    Lasso Regression is a powerful regression technique that combines prediction accuracy with automatic feature selection. By using L1 regularization, it builds simpler, faster, and more interpretable models — especially when dealing with high-dimensional or noisy datasets.