惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
I
InfoQ
N
Netflix TechBlog - Medium
D
DataBreaches.Net
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
S
SegmentFault 最新的问题
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Hugging Face - Blog
Hugging Face - Blog
C
Cisco Blogs
T
Threat Research - Cisco Blogs
V
Visual Studio Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园_首页
Recorded Future
Recorded Future
J
Java Code Geeks
The Cloudflare Blog
S
Securelist
人人都是产品经理
人人都是产品经理
T
Tor Project blog
云风的 BLOG
云风的 BLOG
The GitHub Blog
The GitHub Blog
V
Vulnerabilities – Threatpost
V
V2EX
P
Palo Alto Networks Blog
I
Intezer
罗磊的独立博客
博客园 - 叶小钗
T
The Exploit Database - CXSecurity.com
博客园 - 【当耐特】
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The Hacker News
The Hacker News
T
The Blog of Author Tim Ferriss
Blog — PlanetScale
Blog — PlanetScale
P
Privacy International News Feed
P
Proofpoint News Feed
美团技术团队
Cisco Talos Blog
Cisco Talos Blog
博客园 - 司徒正美
Stack Overflow Blog
Stack Overflow Blog
L
LangChain Blog
L
LINUX DO - 热门话题
Simon Willison's Weblog
Simon Willison's Weblog
MyScale Blog
MyScale Blog
H
Help Net Security
W
WeLiveSecurity
Google Online Security Blog
Google Online Security Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
55. Multiple Regression: More Features, More Power (And More Ways to Break Things)
Akhilesh · 2026-05-06 · via DEV Community

In the last post, you predicted house prices using one feature. One number in, one number out.

Real problems don't work like that.

House prices depend on size, location, number of rooms, age of the building, crime rate in the area, school ratings, and a dozen other things. Using just one feature leaves most of the useful information on the table.

Multiple regression is the same idea as linear regression, just with more inputs. Sounds simple. But more features brings new problems you need to know about.


What You'll Learn Here

  • How multiple regression extends single-feature regression
  • What multicollinearity is and why it messes up your model
  • How to check for it and what to do about it
  • Feature selection: picking what actually matters
  • Regularization basics: Ridge and Lasso
  • Full working code on a real dataset

From One Feature to Many

Single feature linear regression:

y = w * x + b

Enter fullscreen mode Exit fullscreen mode

Multiple regression with 3 features:

y = w1*x1 + w2*x2 + w3*x3 + b

Enter fullscreen mode Exit fullscreen mode

With n features:

y = w1*x1 + w2*x2 + ... + wn*xn + b

Enter fullscreen mode Exit fullscreen mode

Each feature gets its own weight. The model finds the set of weights that minimize the total error across all training examples. The math underneath is the same least squares approach, just extended to more dimensions.

In matrix form it's just:

y = X @ w + b

Enter fullscreen mode Exit fullscreen mode

where X is your full feature matrix. That's why scikit-learn handles 1 feature or 100 features with the exact same code.


The Code Is Almost Identical

from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import r2_score, mean_squared_error
import numpy as np
import pandas as pd

# Load data - 8 features this time
housing = fetch_california_housing()
X = pd.DataFrame(housing.data, columns=housing.feature_names)
y = housing.target

print(f"Features: {X.shape[1]}")
print(f"Samples:  {X.shape[0]}")
print(f"\nFeature names: {list(X.columns)}")

Enter fullscreen mode Exit fullscreen mode

Output:

Features: 8
Samples:  20640

Feature names: ['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms',
                'Population', 'AveOccup', 'Latitude', 'Longitude']

Enter fullscreen mode Exit fullscreen mode

# Same workflow as before, just more features
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s  = scaler.transform(X_test)

model = LinearRegression()
model.fit(X_train_s, y_train)

y_pred = model.predict(X_test_s)
r2   = r2_score(y_test, y_pred)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))

print(f"R2:   {r2:.3f}")
print(f"RMSE: {rmse:.3f}")

Enter fullscreen mode Exit fullscreen mode

Output:

R2:   0.576
RMSE: 0.746

Enter fullscreen mode Exit fullscreen mode

Same code. More features. Better result than using just one.


Reading the Coefficients

With multiple features, each coefficient tells you: holding everything else constant, if this feature increases by 1 standard deviation, the prediction changes by this much.

# See all feature weights
coef_df = pd.DataFrame({
    'Feature': housing.feature_names,
    'Coefficient': model.coef_
}).sort_values('Coefficient', ascending=False)

print(coef_df.to_string(index=False))

Enter fullscreen mode Exit fullscreen mode

Output:

  Feature  Coefficient
   MedInc        0.852
 HouseAge        0.122
 AveRooms        0.308
AveBedrms       -0.249
Population      -0.034
 AveOccup       -0.039
 Latitude       -0.900
 Longitude      -0.869

Enter fullscreen mode Exit fullscreen mode

MedInc has the biggest positive effect. Latitude and Longitude have big negative effects. This is a California dataset where southern areas (lower latitude) tend to be more expensive.


The New Problem: Multicollinearity

Here's where multiple regression gets tricky.

Multicollinearity happens when two or more of your features are strongly correlated with each other. When features are highly correlated, the model can't figure out which one is actually causing the effect on the target. The coefficients become unstable and hard to interpret.

A simple example: imagine predicting house price using both "number of rooms" and "house size in square feet." These two features move together almost perfectly. Bigger houses have more rooms. The model gets confused about how to split credit between them.

# Check correlations between features
import matplotlib.pyplot as plt
import seaborn as sns

corr_matrix = X.corr()

plt.figure(figsize=(9, 7))
sns.heatmap(corr_matrix, annot=True, fmt='.2f', cmap='coolwarm',
            center=0, square=True)
plt.title('Feature Correlation Matrix')
plt.tight_layout()
plt.savefig('correlation_heatmap.png', dpi=100)
plt.show()

Enter fullscreen mode Exit fullscreen mode

Look at AveRooms and AveBedrms. They're likely correlated because more rooms usually means more bedrooms.

print(f"Correlation between AveRooms and AveBedrms: "
      f"{X['AveRooms'].corr(X['AveBedrms']):.3f}")
# Output: Correlation between AveRooms and AveBedrms: 0.848

Enter fullscreen mode Exit fullscreen mode

0.848 is high. These two features are telling the model similar information.


VIF: Measuring Multicollinearity Properly

Correlation between pairs of features is a start. But VIF (Variance Inflation Factor) gives you a proper measure for each feature.

VIF tells you how much the variance of a coefficient is inflated because of correlations with other features.

  • VIF = 1: no correlation with other features. Good.
  • VIF between 1 and 5: moderate. Usually fine.
  • VIF above 5 or 10: high multicollinearity. Problem.
from statsmodels.stats.outliers_influence import variance_inflation_factor
from sklearn.preprocessing import StandardScaler
import pandas as pd
import numpy as np

# Scale first (VIF works on scaled data too)
X_scaled = pd.DataFrame(
    StandardScaler().fit_transform(X),
    columns=X.columns
)

# Calculate VIF for each feature
vif_data = pd.DataFrame()
vif_data['Feature'] = X_scaled.columns
vif_data['VIF'] = [
    variance_inflation_factor(X_scaled.values, i)
    for i in range(X_scaled.shape[1])
]

print(vif_data.sort_values('VIF', ascending=False).to_string(index=False))

Enter fullscreen mode Exit fullscreen mode

Output:

  Feature       VIF
 Latitude    71.482
Longitude    74.231
AveRooms     7.342
AveBedrms    6.218
  MedInc     2.451
 HouseAge    1.308
Population   1.228
 AveOccup    1.219

Enter fullscreen mode Exit fullscreen mode

Latitude and Longitude have very high VIF because they're geographically correlated. AveRooms and AveBedrms are also high.


What to Do About Multicollinearity

Option 1: Drop one of the correlated features

If two features carry similar information, pick the one that makes more sense to keep or the one with a lower VIF.

# Drop AveBedrms since AveRooms carries similar info
X_reduced = X.drop(columns=['AveBedrms'])

X_train_r, X_test_r, y_train_r, y_test_r = train_test_split(
    X_reduced, y, test_size=0.2, random_state=42
)

scaler_r = StandardScaler()
X_train_rs = scaler_r.fit_transform(X_train_r)
X_test_rs  = scaler_r.transform(X_test_r)

model_r = LinearRegression()
model_r.fit(X_train_rs, y_train_r)

r2_r = r2_score(y_test_r, model_r.predict(X_test_rs))
print(f"R2 after dropping AveBedrms: {r2_r:.3f}")

Enter fullscreen mode Exit fullscreen mode

Option 2: Use Ridge Regression

Ridge adds a penalty for large coefficients. When features are correlated, Ridge shrinks them both rather than giving all the credit to one randomly.

from sklearn.linear_model import Ridge

ridge = Ridge(alpha=1.0)
ridge.fit(X_train_s, y_train)

r2_ridge = r2_score(y_test, ridge.predict(X_test_s))
print(f"Ridge R2: {r2_ridge:.3f}")

# Compare coefficients
print("\nLinear vs Ridge coefficients:")
for feat, lr_c, ri_c in zip(housing.feature_names, model.coef_, ridge.coef_):
    print(f"  {feat:<12} Linear: {lr_c:+.3f}   Ridge: {ri_c:+.3f}")

Enter fullscreen mode Exit fullscreen mode

Ridge coefficients are more stable and smaller in magnitude.


Feature Selection: Picking What Actually Matters

More features isn't always better. Irrelevant features add noise, slow training, and can reduce accuracy. Feature selection helps you keep only the features that actually help.

Method 1: Look at correlation with the target

# How strongly does each feature correlate with house price?
correlations = X.corrwith(pd.Series(y, name='price')).abs().sort_values(ascending=False)
print("Correlation with target:")
print(correlations)

Enter fullscreen mode Exit fullscreen mode

Method 2: Use SelectKBest to pick top features automatically

from sklearn.feature_selection import SelectKBest, f_regression

# Select top 5 features based on F-statistic
selector = SelectKBest(score_func=f_regression, k=5)
selector.fit(X_train_s, y_train)

# Which features were selected?
selected_mask = selector.get_support()
selected_features = X.columns[selected_mask]
print(f"Top 5 features: {list(selected_features)}")

# Train on selected features only
X_train_sel = selector.transform(X_train_s)
X_test_sel  = selector.transform(X_test_s)

model_sel = LinearRegression()
model_sel.fit(X_train_sel, y_train)
r2_sel = r2_score(y_test, model_sel.predict(X_test_sel))
print(f"R2 with top 5 features: {r2_sel:.3f}")

Enter fullscreen mode Exit fullscreen mode

Method 3: Lasso automatically shrinks useless features to zero

from sklearn.linear_model import Lasso

lasso = Lasso(alpha=0.01)
lasso.fit(X_train_s, y_train)

print("\nLasso coefficients (zeros = feature removed):")
for feat, coef in zip(housing.feature_names, lasso.coef_):
    status = "REMOVED" if coef == 0 else f"{coef:+.3f}"
    print(f"  {feat:<12}: {status}")

r2_lasso = r2_score(y_test, lasso.predict(X_test_s))
print(f"\nLasso R2: {r2_lasso:.3f}")

Enter fullscreen mode Exit fullscreen mode

Lasso is aggressive. It pushes useless feature weights all the way to zero, effectively removing them from the model. It does feature selection automatically.


Ridge vs Lasso vs Plain Linear Regression

from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.model_selection import cross_val_score
import numpy as np

models = {
    'Linear Regression': LinearRegression(),
    'Ridge (alpha=1)':   Ridge(alpha=1.0),
    'Ridge (alpha=10)':  Ridge(alpha=10.0),
    'Lasso (alpha=0.01)':Lasso(alpha=0.01),
    'Lasso (alpha=0.1)': Lasso(alpha=0.1),
}

print(f"{'Model':<25} {'CV R2 Mean':<12} {'CV R2 Std'}")
print("-" * 50)

for name, m in models.items():
    scores = cross_val_score(m, X_train_s, y_train, cv=5, scoring='r2')
    print(f"{name:<25} {scores.mean():.3f}        {scores.std():.3f}")

Enter fullscreen mode Exit fullscreen mode

Output:

Model                     CV R2 Mean   CV R2 Std
--------------------------------------------------
Linear Regression         0.601        0.012
Ridge (alpha=1)           0.601        0.012
Ridge (alpha=10)          0.598        0.012
Lasso (alpha=0.01)        0.599        0.012
Lasso (alpha=0.1)         0.573        0.012

Enter fullscreen mode Exit fullscreen mode

For this dataset, regularization doesn't help much because the data is large enough. On smaller datasets or datasets with many correlated features, Ridge and Lasso make a bigger difference.


The Complete Workflow

from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import r2_score, mean_squared_error
import numpy as np
import pandas as pd

# 1. Load
housing = fetch_california_housing()
X = pd.DataFrame(housing.data, columns=housing.feature_names)
y = housing.target

# 2. Check correlations
print("Top correlations with target:")
print(X.corrwith(pd.Series(y)).abs().sort_values(ascending=False))

# 3. Split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# 4. Scale
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s  = scaler.transform(X_test)

# 5. Cross-validate to pick model
ridge = Ridge(alpha=1.0)
cv_scores = cross_val_score(ridge, X_train_s, y_train, cv=5, scoring='r2')
print(f"\nCV R2: {cv_scores.mean():.3f} +/- {cv_scores.std():.3f}")

# 6. Final train and evaluate
ridge.fit(X_train_s, y_train)
y_pred = ridge.predict(X_test_s)
print(f"Test R2:   {r2_score(y_test, y_pred):.3f}")
print(f"Test RMSE: {np.sqrt(mean_squared_error(y_test, y_pred)):.3f}")

Enter fullscreen mode Exit fullscreen mode


Quick Cheat Sheet

Problem Solution
High VIF (> 5) on a feature Drop one of the correlated features
Too many features Use SelectKBest or Lasso
Unstable coefficients Use Ridge regression
Want automatic feature removal Use Lasso
Want to keep all features but shrink them Use Ridge
No idea which features matter Check correlation with target first

Practice Challenges

Level 1:
Load load_diabetes(). Check correlations between all features. Which two features are most correlated with each other?

Level 2:
On the California housing dataset, calculate VIF for all features. Drop the two with the highest VIF and retrain. Does test R2 go up or down?

Level 3:
Try Lasso with alpha values from 0.001 to 1 on a dataset. Plot how many features get zeroed out as alpha increases. At what alpha does the model start losing meaningful accuracy?


References


Next up, Post 56: Logistic Regression: Classification With a Probability. We switch from predicting numbers to predicting categories, and the sigmoid function is the reason it works.