MLCrack

    CLASSICAL ML Β· INTERVIEW QUESTION

    Explain regularization. Compare L1 (Lasso) and L2 (Ridge) regularization.

    🟑 intermediate · Supervised Learning

    Hint: L1 creates sparsity, L2 shrinks weights uniformly.

    Answer

    Regularization adds a penalty to the loss function to prevent overfitting by constraining model complexity.

    Lreg=Ldata+Ξ»β‹…R(w)\mathcal{L}_{\text{reg}} = \mathcal{L}_{\text{data}} + \lambda \cdot R(w)

    L1 vs L2 Comparison

    L1 (Lasso)L2 (Ridge)
    Penalty$R = \sumw_i
    EffectDrives weights to exactly zeroShrinks weights toward zero
    ResultSparse model (feature selection)All features kept, smaller weights
    GeometryDiamond constraint (sparse corners)Circle constraint (no axis preference)
    Best forMany irrelevant featuresAll features potentially useful

    Elastic Net combines both: Ξ±β‹…L1+(1βˆ’Ξ±)β‹…L2\alpha \cdot L1 + (1-\alpha) \cdot L2

    python
    from sklearn.linear_model import Lasso, Ridge, ElasticNet # L1 regularization (sparse features) lasso = Lasso(alpha=0.1) # L2 regularization (multicollinearity) ridge = Ridge(alpha=1.0) # Elastic Net (grouped features) enet = ElasticNet(alpha=0.1, l1_ratio=0.5)

    Ξ»\lambda is chosen via cross-validation. Higher Ξ»\lambda = stronger regularization = simpler model.