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

推荐订阅源

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
雷峰网
雷峰网
博客园 - 叶小钗
C
Check Point Blog
F
Fortinet All Blogs
A
About on SuperTechFans
Y
Y Combinator Blog
Vercel News
Vercel News
IT之家
IT之家
V
V2EX
T
Tailwind CSS Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The GitHub Blog
The GitHub Blog
Jina AI
Jina AI
Blog — PlanetScale
Blog — PlanetScale
罗磊的独立博客
云风的 BLOG
云风的 BLOG
U
Unit 42
博客园_首页
量子位
M
MIT News - Artificial intelligence
G
Google Developers Blog
小众软件
小众软件
N
Netflix TechBlog - Medium
P
Palo Alto Networks Blog
S
Schneier on Security
T
Tor Project blog
F
Full Disclosure
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tenable Blog
T
The Blog of Author Tim Ferriss
Spread Privacy
Spread Privacy
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
Microsoft Azure Blog
Microsoft Azure Blog
Google DeepMind News
Google DeepMind News
T
Threat Research - Cisco Blogs
Know Your Adversary
Know Your Adversary
P
Proofpoint News Feed
Security Latest
Security Latest
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园 - 司徒正美
AWS News Blog
AWS News Blog
Simon Willison's Weblog
Simon Willison's Weblog
Recorded Future
Recorded Future
L
Lohrmann on Cybersecurity
I
Intezer
L
LangChain Blog
L
LINUX DO - 热门话题

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
54. Linear Regression: Predicting Numbers From Patterns
Akhilesh · 2026-05-05 · via DEV Community

You want to predict something. A number. How much a house will sell for. How many units you'll sell next month. What temperature it'll be tomorrow.

That's a regression problem. And linear regression is the first tool you reach for.

It's the simplest ML model that actually does something useful. Every more complex model builds on the ideas here. You can't skip this one.


What You'll Learn Here

  • What linear regression actually does
  • The equation y = mx + b and what each part means in ML
  • What a cost function is and why we need one
  • How least squares fitting works
  • Building linear regression from scratch and with scikit-learn
  • How to evaluate regression models (not accuracy, different metrics)
  • Multiple features and what changes

The Simplest Idea in ML

You have two things that seem related. Hours studied and exam score. House size and house price. Temperature and ice cream sales.

Plot them on a graph. You get a scatter of dots. Linear regression draws the best possible straight line through those dots.

Once you have that line, you can plug in a new value on the X axis and read off a prediction on the Y axis.

That's it. That's linear regression.


The Equation: y = mx + b

You've seen this since school. In ML we write it slightly differently but it's the same thing.

y = mx + b

y  = the thing you're predicting (output)
x  = the input feature you know
m  = slope (how much y changes when x increases by 1)
b  = intercept (what y is when x is 0)

Enter fullscreen mode Exit fullscreen mode

In ML notation:

y_hat = w * x + b

y_hat = predicted value
w     = weight (same as slope m)
x     = input feature
b     = bias (same as intercept)

Enter fullscreen mode Exit fullscreen mode

The model's job is to find the right values of w and b that make the line fit the data as well as possible.


What "Best Fit" Means: The Cost Function

For any line you draw, some predictions will be too high and some too low. The difference between your prediction and the real answer is called the residual or error.

error = actual - predicted

Enter fullscreen mode Exit fullscreen mode

You want to minimize the total error across all your training examples. But you can't just add up raw errors because positive and negative errors cancel out.

So instead, you square each error and add them all up. This is called the Mean Squared Error (MSE).

MSE = (1/n) * sum((actual - predicted)^2)

Enter fullscreen mode Exit fullscreen mode

Squaring does two things: makes all errors positive, and punishes big errors more than small ones. A prediction that's off by 10 is penalized 4x more than one off by 5.

The line that gives you the lowest MSE is your best fit line. That's what scikit-learn finds when you call .fit().


Building It From Scratch First

Before using scikit-learn, let's implement linear regression manually so you see what's actually happening.

import numpy as np
import matplotlib.pyplot as plt

# Simple dataset: study hours vs exam score
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=float)
scores = np.array([52, 55, 60, 65, 68, 72, 75, 81, 85, 90], dtype=float)

# Calculate slope (w) and intercept (b) using the least squares formula
n = len(hours)
mean_x = np.mean(hours)
mean_y = np.mean(scores)

# Slope formula: w = sum((x - mean_x) * (y - mean_y)) / sum((x - mean_x)^2)
numerator   = np.sum((hours - mean_x) * (scores - mean_y))
denominator = np.sum((hours - mean_x) ** 2)
w = numerator / denominator

# Intercept formula: b = mean_y - w * mean_x
b = mean_y - w * mean_x

print(f"Slope (w):     {w:.2f}")
print(f"Intercept (b): {b:.2f}")
print(f"Equation: score = {w:.2f} * hours + {b:.2f}")

# Make predictions
predictions = w * hours + b

# Plot
plt.figure(figsize=(8, 5))
plt.scatter(hours, scores, color='blue', label='Actual scores', zorder=5)
plt.plot(hours, predictions, color='red', linewidth=2, label=f'y = {w:.1f}x + {b:.1f}')
plt.xlabel('Hours Studied')
plt.ylabel('Exam Score')
plt.title('Linear Regression From Scratch')
plt.legend()
plt.grid(True, alpha=0.3)
plt.savefig('linear_regression_scratch.png', dpi=100)
plt.show()

Enter fullscreen mode Exit fullscreen mode

Output:

Slope (w):     4.24
Intercept (b): 47.27
Equation: score = 4.24 * hours + 47.27

Enter fullscreen mode Exit fullscreen mode

This tells you: for every extra hour of study, the score goes up by about 4.24 points. If someone studies 0 hours, the model predicts 47.27.

Now predict for a new student who studied 7.5 hours:

new_hours = 7.5
predicted_score = w * new_hours + b
print(f"Predicted score for {new_hours} hours: {predicted_score:.1f}")
# Output: Predicted score for 7.5 hours: 79.1

Enter fullscreen mode Exit fullscreen mode


Now With Scikit-learn

You'll always use scikit-learn in practice. Let's do the same thing but properly.

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
import numpy as np

# Same data, shaped for sklearn (needs 2D input)
hours  = np.array([1,2,3,4,5,6,7,8,9,10]).reshape(-1, 1)
scores = np.array([52,55,60,65,68,72,75,81,85,90])

# Split
X_train, X_test, y_train, y_test = train_test_split(
    hours, scores, test_size=0.2, random_state=42
)

# Train
model = LinearRegression()
model.fit(X_train, y_train)

print(f"Slope (w):     {model.coef_[0]:.2f}")
print(f"Intercept (b): {model.intercept_:.2f}")

# Predict
y_pred = model.predict(X_test)

# Evaluate
mse  = mean_squared_error(y_test, y_pred)
mae  = mean_absolute_error(y_test, y_pred)
r2   = r2_score(y_test, y_pred)

print(f"\nMSE:  {mse:.2f}")
print(f"RMSE: {np.sqrt(mse):.2f}")
print(f"MAE:  {mae:.2f}")
print(f"R2:   {r2:.3f}")

Enter fullscreen mode Exit fullscreen mode


Evaluating Regression: Different Metrics Than Classification

For classification you use accuracy. For regression, accuracy doesn't make sense. You use these instead.

MAE (Mean Absolute Error)
Average of absolute differences between predictions and actual values. Easy to understand. If MAE = 5.2, your predictions are off by 5.2 on average.

MAE = mean(|actual - predicted|)

Enter fullscreen mode Exit fullscreen mode

MSE (Mean Squared Error)
Squares the errors before averaging. Punishes big mistakes more. Harder to interpret because the units are squared.

MSE = mean((actual - predicted)^2)

Enter fullscreen mode Exit fullscreen mode

RMSE (Root Mean Squared Error)
Square root of MSE. Same units as your target variable. Most commonly used.

RMSE = sqrt(MSE)

Enter fullscreen mode Exit fullscreen mode

R2 Score (R-squared)
Tells you how much of the variance in your target variable is explained by your model. Ranges from 0 to 1. Closer to 1 is better.

  • R2 = 1.0: perfect predictions
  • R2 = 0.8: model explains 80% of the variation in the data
  • R2 = 0.0: model is no better than just predicting the mean every time
  • R2 < 0: model is worse than predicting the mean (something is very wrong)
# Quick comparison of all metrics
print("Metric comparison:")
print(f"  MAE:  {mae:.2f}   <- average error in original units")
print(f"  RMSE: {np.sqrt(mse):.2f}  <- also in original units, penalizes big errors")
print(f"  R2:   {r2:.3f}  <- 0 to 1, higher is better")

Enter fullscreen mode Exit fullscreen mode


Real Example: California Housing Dataset

Let's use a real dataset with actual features.

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 mean_squared_error, r2_score
import numpy as np
import pandas as pd

# Load data
housing = fetch_california_housing()
X = pd.DataFrame(housing.data, columns=housing.feature_names)
y = housing.target  # median house value in $100,000s

print(X.head())
print(f"\nTarget range: ${y.min()*100:.0f}k to ${y.max()*100:.0f}k")

Enter fullscreen mode Exit fullscreen mode

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

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled  = scaler.transform(X_test)

# Train
model = LinearRegression()
model.fit(X_train_scaled, y_train)

# Evaluate
y_pred = model.predict(X_test_scaled)
rmse   = np.sqrt(mean_squared_error(y_test, y_pred))
r2     = r2_score(y_test, y_pred)

print(f"RMSE: ${rmse*100:.0f}k")
print(f"R2:   {r2:.3f}")

Enter fullscreen mode Exit fullscreen mode

Output:

RMSE: $74k
R2:   0.576

Enter fullscreen mode Exit fullscreen mode

The model is off by about $74k on average. R2 of 0.576 means it explains about 58% of the variation in house prices. Not bad for a simple linear model with no tuning.


Looking at Feature Weights

One great thing about linear regression: you can see exactly how much each feature matters.

# Feature importance from coefficients
coefficients = pd.Series(model.coef_, index=housing.feature_names)
coefficients_sorted = coefficients.sort_values()

print("Feature weights (bigger absolute value = more influence):")
print(coefficients_sorted)

Enter fullscreen mode Exit fullscreen mode

Output:

Feature weights:
AveOccup    -0.391
Latitude    -0.900
Longitude   -0.870
HouseAge     0.123
AveRooms     0.323
Population  -0.003
AveBedrms   -0.049
MedInc       0.827

Enter fullscreen mode Exit fullscreen mode

MedInc (median income) has the biggest positive weight. Higher income neighborhoods have higher house prices. Makes sense.

Latitude has a big negative weight. Moving north in California (higher latitude) generally means lower prices. Also makes sense geographically.

This interpretability is one of the biggest advantages of linear regression. You can explain every prediction.


The Things Everyone Gets Wrong

Mistake 1: Not scaling features

Linear regression works with raw numbers. If one feature ranges from 0 to 1,000,000 and another from 0 to 1, the big-range feature dominates the coefficients. Always scale when features have very different ranges.

# Always do this before linear regression
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled  = scaler.transform(X_test)

Enter fullscreen mode Exit fullscreen mode

Mistake 2: Using it for non-linear relationships

Linear regression assumes the relationship is, well, linear. If the real pattern curves, a straight line won't fit it. Check a scatter plot first.

Mistake 3: Reporting R2 without checking residuals

R2 can look decent even when your model is completely wrong in systematic ways. Always plot actual vs predicted and residuals vs predicted.

import matplotlib.pyplot as plt

# Residual plot
residuals = y_test - y_pred

plt.figure(figsize=(8, 4))
plt.scatter(y_pred, residuals, alpha=0.3, color='blue')
plt.axhline(y=0, color='red', linewidth=1)
plt.xlabel('Predicted Values')
plt.ylabel('Residuals')
plt.title('Residual Plot - should look like random scatter around 0')
plt.savefig('residual_plot.png', dpi=100)
plt.show()

Enter fullscreen mode Exit fullscreen mode

If residuals show a pattern (a curve, a funnel shape), your linear model is missing something.


Quick Cheat Sheet

Thing Code
Train model model = LinearRegression(); model.fit(X_train, y_train)
Get slope model.coef_
Get intercept model.intercept_
Predict model.predict(X_test)
MAE mean_absolute_error(y_test, y_pred)
RMSE np.sqrt(mean_squared_error(y_test, y_pred))
R2 r2_score(y_test, y_pred)
Scale features StandardScaler().fit_transform(X_train)

Practice Challenges

Level 1:
Load load_diabetes() from sklearn. Train a linear regression model. Print the RMSE and R2. Which feature has the highest positive weight?

Level 2:
On the California housing dataset, remove the scaling step. Compare R2 with and without scaling. What changes? What does that tell you?

Level 3:
Plot actual vs predicted values as a scatter plot for the California housing data. Draw a diagonal line where predicted = actual. Points closer to that line are better predictions. Where does the model struggle the most?


References


Next up, Post 55: Multiple Regression: More Features, More Power. What changes when you go from 1 input to 10 inputs, how multicollinearity breaks your model, and how to pick the right features.