100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Regularization (L1/L2) Cheat Sheet

Regularization (L1/L2) Cheat Sheet

Covers L1 (Lasso) and L2 (Ridge) regularization for linear models, including Elastic Net, scikit-learn code, and hyperparameter tuning tips.

2 PagesIntermediateMar 5, 2026

Ridge & Lasso in scikit-learn

Fit L2 and L1 regularized linear models with proper feature scaling.

python
from sklearn.linear_model import Ridge, Lassofrom sklearn.preprocessing import StandardScaler# Always scale features before regularizationscaler = StandardScaler()X_train_scaled = scaler.fit_transform(X_train)X_test_scaled = scaler.transform(X_test)# Ridge (L2) - shrinks coefficients toward zeroridge = Ridge(alpha=1.0)  # alpha = lambda, higher = more regularizationridge.fit(X_train_scaled, y_train)# Lasso (L1) - can shrink coefficients to exactly zero (feature selection)lasso = Lasso(alpha=0.1)lasso.fit(X_train_scaled, y_train)print(lasso.coef_)  # some coefficients will be 0.0

Elastic Net & Logistic Regression

Combine L1/L2 penalties and apply regularization to classification models.

python
from sklearn.linear_model import ElasticNet, ElasticNetCV, LogisticRegression# Elastic Net combines L1 and L2 penalties# l1_ratio=1 -> pure Lasso, l1_ratio=0 -> pure Ridgeen = ElasticNet(alpha=0.1, l1_ratio=0.5)en.fit(X_train_scaled, y_train)# Cross-validated search over alpha and l1_ratioen_cv = ElasticNetCV(l1_ratio=[.1, .5, .7, .9, .95, 1], cv=5)en_cv.fit(X_train_scaled, y_train)# Regularized logistic regression (classification)# penalty: 'l1', 'l2', 'elasticnet', None# C = 1 / lambda -> smaller C = stronger regularizationclf_l2 = LogisticRegression(penalty='l2', C=1.0, solver='lbfgs')clf_l1 = LogisticRegression(penalty='l1', C=0.5, solver='liblinear')

Core Concepts

The math and intuition behind L1 and L2 penalties.

  • L1 penalty (Lasso)- Adds λΣ|wᵢ| to the loss function; produces sparse solutions by driving some weights exactly to 0
  • L2 penalty (Ridge)- Adds λΣwᵢ² to the loss function; shrinks all weights smoothly toward 0 but rarely to exactly 0
  • Elastic Net- Combines L1 and L2: λ₁Σ|wᵢ| + λ₂Σwᵢ²; useful when features are correlated
  • alpha / lambda (λ)- Regularization strength; higher values increase bias and reduce variance
  • C (scikit-learn)- Inverse of regularization strength in LogisticRegression/SVC; smaller C means a stronger penalty
  • Bias-variance tradeoff- Regularization increases bias but reduces variance, often lowering test error
  • Feature scaling- Required before regularization since penalty magnitude depends on coefficient scale

Hyperparameter Tuning

Practical guidance for choosing regularization strength.

  • GridSearchCV- Search alpha over a log scale, e.g. np.logspace(-4, 4, 50)
  • RidgeCV / LassoCV- Built-in cross-validated estimators that select alpha automatically
  • Standardization- Use StandardScaler so all coefficients are penalized on the same scale
  • Sparse solutions- Use Lasso/L1 when you expect only a subset of features to matter
  • Multicollinearity- Ridge handles correlated features better than Lasso, which picks one arbitrarily

Weight Decay in Neural Nets: SGD vs Adam vs AdamW

L2 regularization and 'weight decay' are only mathematically equivalent for plain SGD — Adam breaks that equivalence.

python
import torch.optim as optim# With plain SGD, adding L2 penalty to the loss (lambda * ||w||^2) and# subtracting lambda * w directly from the weights each step are equivalent.sgd = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)# With Adam, weight_decay implemented as an L2 term gets divided by the# adaptive per-parameter second-moment estimate, so it's no longer a# clean, uniform shrinkage -- large-gradient parameters get under-regularized.adam_coupled = optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-4)  # biased# AdamW decouples weight decay from the gradient-based update entirely:# w = w - lr * (adam_update + weight_decay * w)# This restores the intended uniform shrinkage and is the standard choice# for training transformers.adamw = optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)

Proximal Gradient Descent (ISTA) for L1

L1's non-differentiability at zero means plain gradient descent can't be used directly; the soft-thresholding operator solves it.

python
import numpy as npdef soft_threshold(x, thresh):    # Proximal operator of the L1 norm: shrinks values toward 0 and    # zeroes out anything within [-thresh, thresh]    return np.sign(x) * np.maximum(np.abs(x) - thresh, 0.0)def ista_lasso(X, y, alpha=0.1, lr=None, n_iters=500):    n, p = X.shape    if lr is None:        lr = 1.0 / np.linalg.norm(X, 2) ** 2  # step <= 1/L, L = largest eigenvalue of X^T X    w = np.zeros(p)    for _ in range(n_iters):        grad = X.T @ (X @ w - y) / n            # gradient of the smooth MSE term only        w = soft_threshold(w - lr * grad, alpha * lr)  # proximal step handles the L1 term    return w

Regularization Path with LARS

Compute the full Lasso solution path across all alpha values in one pass instead of refitting per alpha.

python
from sklearn.linear_model import lars_pathimport matplotlib.pyplot as plt# LARS (Least Angle Regression) computes the exact piecewise-linear path# of Lasso coefficients as alpha decreases from infinity to 0, in roughly# the same cost as a single OLS fit -- far cheaper than grid-searching alpha.alphas, active, coefs = lars_path(X_train_scaled, y_train, method="lasso")for i in range(coefs.shape[0]):    plt.plot(alphas, coefs[i], label=f"feature {i}")plt.xscale("log")plt.xlabel("alpha (log scale)")plt.ylabel("coefficient value")plt.title("Lasso regularization path")# Reading the plot: features whose coefficient lines hit 0 first (at the# largest alpha) are the least important under L1 selection

Group Lasso & Streaming Elastic Net

Regularize predefined groups of features together, and fit elastic-net-penalized models on data too large to fit in memory.

python
from sklearn.linear_model import SGDClassifierfrom group_lasso import GroupLasso  # pip install group-lasso# Group Lasso: penalizes the L2 norm of each feature group, zeroing out# entire groups (e.g. all one-hot columns from a single categorical) together# rather than individual dummy columnsgl = GroupLasso(    groups=group_ids,          # array mapping each column to its group id    group_reg=0.05,    l1_reg=0.0,    supress_warning=True,)gl.fit(X_train_scaled, y_train)# SGDClassifier scales elastic-net-penalized linear models to datasets that# don't fit in memory via mini-batch / partial_fit updatessgd_en = SGDClassifier(    loss="log_loss", penalty="elasticnet", alpha=1e-4, l1_ratio=0.15,    max_iter=1000, tol=1e-3,)for X_batch, y_batch in stream_batches():    sgd_en.partial_fit(X_batch, y_batch, classes=[0, 1])

Theoretical Foundations

The statistical and optimization theory underlying L1/L2, beyond the sklearn API.

  • Bayesian interpretation- L2 regularization corresponds to a Gaussian prior on the weights (MAP estimation); L1 corresponds to a Laplace prior, whose sharp peak at 0 is why it induces sparsity
  • Why L1 gives sparsity, L2 doesn't- the L1 ball has corners on the coordinate axes, so the loss contour is likely to first touch it exactly at a corner (a zero coefficient); the L2 ball is smooth, so the tangent point rarely lands on an axis
  • L0 penalty- directly penalizes the count of nonzero weights; NP-hard to optimize exactly, which is why L1 is used as its convex relaxation
  • Implicit regularization- early stopping, dropout, and even SGD's inherent noise all act as regularizers without an explicit penalty term in the loss
  • Ridge closed-form solution- w = (XᵀX + λI)⁻¹Xᵀy; adding λI to XᵀX before inverting also stabilizes the solution when features are collinear or n < p
  • Effective degrees of freedom- for Ridge, df(λ) = Σ dᵢ²/(dᵢ²+λ) using the singular values dᵢ of X; quantifies how much regularization shrinks model complexity as a continuous (not integer) quantity
  • Double descent- in modern over-parameterized models, test error can decrease again past the interpolation threshold even without explicit regularization, complicating the classic bias-variance-driven tuning intuition
Pro Tip

When features are highly correlated, prefer Elastic Net over pure Lasso - Lasso tends to arbitrarily select one feature from a correlated group and zero out the rest, which hurts interpretability and stability.

Was this cheat sheet helpful?

Explore Topics

#RegularizationL1L2#RegularizationL1L2CheatSheet#DataScience#Intermediate#Ridge#Lasso#Scikit#Learn#MachineLearning#CheatSheet#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Does SkillVeris have a tech blog, and what does it cover?
Yes, the SkillVeris blog has over 500 articles covering AI and machine learning, programming, web development, DevOps, cloud, security, databases and career guidance. Articles are practical and answer-first, and many use the Learn Through Hobbies approach, teaching technical concepts through cricket, music, gaming or cooking analogies. Everything is free to read.
What is the SkillVeris tech glossary and how big is it?
The SkillVeris glossary is a free reference of roughly 2,000-plus technology terms, each with a clear plain-language definition. It spans AI, programming, web, DevOps, cloud, security and database vocabulary, so whenever a lesson, article or job description uses jargon you do not recognise, the glossary gives you a fast, reliable answer.
Are the developer cheat sheets on SkillVeris free to download?
The cheat sheets are completely free to use, like everything else on SkillVeris. Each sheet condenses a language or tool into its essential syntax, commands and patterns for quick reference while coding. They are designed for rapid lookup during real work, complementing the deeper explanations found in study notes and courses.
Which programming references and cheat sheets are available?
Cheat sheets cover the platform's main domains, including programming languages, AI and ML tooling, web development, DevOps, cloud, security and databases, matching the topics of the 37 live courses. Each sheet lists related reading links and hashtags, so you can jump from a quick reference into fuller study notes or blog articles.
How do I find the meaning of a technical term quickly?
Search the SkillVeris glossary, which holds around 2,000-plus terms with concise, plain-language definitions. Each entry gets to the point in its first sentence, then links to related reading like blog posts or study notes for deeper context. It is faster and more consistent than sifting through scattered search results.
Is the SkillVeris blog good for beginners learning to code?
Yes, many blog articles are written specifically for beginners, and the Learn Through Hobbies style makes them unusually approachable: you might learn Python concepts through cricket or understand APIs through cooking. With 500-plus articles across skill levels, beginners can start with fundamentals and keep reading as they advance, entirely free.
Can cheat sheets replace full courses for learning a language?
No, cheat sheets are references, not teaching tools; they assume you already understand the concepts and just need syntax or commands fast. To actually learn a language, take a structured SkillVeris course with its 24–40 lessons and assessments, then keep the cheat sheet beside you while practising in Code Lab.
How often are new blog articles published on SkillVeris?
The blog grows regularly and already exceeds 500 articles, with new posts added as courses launch and technologies evolve. Topics track the platform's catalogue across AI, programming, web development, DevOps, cloud and security, so checking the Blog section periodically surfaces fresh tutorials, explainers and career-focused pieces, all free to read.
Does the glossary cover AI and machine learning terms?
Yes, AI and machine learning vocabulary is a major part of the roughly 2,000-plus term glossary, covering everything from foundational terms to modern concepts around LLMs, RAG and MLOps. Definitions are plain-language and answer-first, which helps when dense AI papers or course lessons throw unfamiliar jargon at you.
Are there cheat sheets for interview preparation?
Cheat sheets work well as interview-day refreshers because they compress syntax, commands and key concepts into scannable references. For dedicated preparation, combine them with the SkillVeris interview questions feature, which includes readiness scoring, plus study notes for depth. Reviewing a relevant cheat sheet just before an interview steadies recall under pressure.
Can I read the tech blog without signing up?
Yes, the blog is freely readable, and SkillVeris never charges for content. All 500-plus articles are open, covering tutorials, concept explainers and career advice. Creating a free account adds value elsewhere on the platform, like course progress tracking and certificates, but reading the blog requires no commitment at all.
How is the SkillVeris glossary different from Wikipedia?
The glossary is purpose-built for learners: definitions are short, plain-language and answer-first, sized for a quick lookup mid-lesson rather than a deep encyclopedic read. Entries also cross-link to related SkillVeris study notes, blog posts and courses, so a definition becomes a doorway into structured learning instead of a dead end.
Do blog articles use the Learn Through Hobbies method?
Many blog articles teach technical topics through hobby analogies, a hallmark of the SkillVeris blog, so you will find articles explaining programming through cricket, machine learning through music, or system design through cooking. The analogy is the teaching device; the article still delivers the real technical concept underneath.
Where can I find quick programming references while coding?
Open the SkillVeris cheat sheets, which are built exactly for that moment: compact, scannable references for syntax, commands and common patterns across languages and tools. Keep the relevant sheet in a browser tab while you work in Code Lab or your own editor, and dip into the glossary for terminology.
Is there a glossary entry for terms I meet in job descriptions?
Very likely yes, with roughly 2,000-plus terms across AI, programming, web, DevOps, cloud, security and databases, the glossary covers most jargon that appears in tech job descriptions. Decoding a listing this way helps you judge role fit honestly and prepares you to discuss those terms in interviews.
Are the blog articles written for the Indian tech audience?
The blog serves Indian learners plus a worldwide audience. Content stays globally relevant while acknowledging realities that matter in India, such as free access being essential for students and freshers, and career guidance that connects naturally to the SkillVeris jobs portal, which aggregates roles across India, UK, USA, Germany and Remote.
Can I suggest a topic for the blog or glossary?
SkillVeris content grows in response to what learners need, so feedback is welcome through the platform's support channels. If a term is missing from the glossary or a topic deserves an article, telling the team helps prioritise it. Meanwhile, the AI Mentor can answer the question immediately, 24/7, at any depth.
Do cheat sheets and glossary entries link to deeper learning?
Yes, every cheat sheet and glossary entry carries related reading links into study notes, blog articles and courses, plus concept hashtags for discovering similar content. This cross-linking means a thirty-second lookup can smoothly become a structured learning session whenever you decide you want more than a quick answer.
What makes SkillVeris programming references trustworthy?
The references are written to strict internal quality standards, kept consistent with the platform's 37 live courses, and never padded with invented statistics or hype. Definitions and cheat sheets are reviewed against the same content contracts that govern courses, and the answer-first style makes any inaccuracy easy to spot and correct.
How do the blog, glossary and cheat sheets fit into my learning routine?
Use them as satellites around your main course: read blog articles for context and motivation, hit the glossary the instant jargon appears, and keep cheat sheets open while coding. Together with study notes, Code Lab and the 24/7 AI Mentor, they turn passive reading into a complete, free learning system.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse