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

推荐订阅源

量子位
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
F
Fortinet All Blogs
博客园 - 聂微东
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Hugging Face - Blog
Hugging Face - Blog
V
Visual Studio Blog
小众软件
小众软件
有赞技术团队
有赞技术团队
雷峰网
雷峰网
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
AWS News Blog
AWS News Blog
C
Cisco Blogs
美团技术团队
T
Threat Research - Cisco Blogs
C
CERT Recently Published Vulnerability Notes
人人都是产品经理
人人都是产品经理
宝玉的分享
宝玉的分享
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
酷 壳 – CoolShell
酷 壳 – CoolShell
Stack Overflow Blog
Stack Overflow Blog
W
WeLiveSecurity
D
DataBreaches.Net
博客园 - 司徒正美
Blog — PlanetScale
Blog — PlanetScale
IT之家
IT之家
云风的 BLOG
云风的 BLOG
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Simon Willison's Weblog
Simon Willison's Weblog
Google DeepMind News
Google DeepMind News
T
The Blog of Author Tim Ferriss
Know Your Adversary
Know Your Adversary
NISL@THU
NISL@THU
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Cloudflare Blog
Vercel News
Vercel News
月光博客
月光博客
T
Tailwind CSS Blog
H
Help Net Security
aimingoo的专栏
aimingoo的专栏
P
Proofpoint News Feed
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Spread Privacy
Spread Privacy
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
Microsoft Security Blog
Microsoft Security Blog
V
V2EX
WordPress大学
WordPress大学
Cyberwarzone
Cyberwarzone
Recent Announcements
Recent Announcements

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
A real-world walkthrough of regression using coffee, code, and actual data
Sujit Mali · 2026-05-21 · via DEV Community

I failed my first stats class in college.

Not because the math was hard. Because every example in the textbook was about iris flowers or Boston housing prices and I couldn't figure out why anyone in real life would care. So the formulas just slid off my brain.

Years later, I'm a backend dev in Mumbai with a serious filter coffee habit and an even more serious sleep deficit. One Sunday morning, somewhere between my second tumbler of decoction and a half-broken Saturday deploy, I asked myself a question I could actually feel in my body: does more coffee actually mean I write more code?

That question is what finally taught me linear regression. Not the textbook. Not the YouTube playlist. A Google Sheet, my git log, and 30 cups of filter coffee.

Here's the whole thing, including the math by hand, the part where I got it wrong, and the Python at the end.

The setup (and why I think most tutorials skip it)

Every linear regression tutorial I'd ever opened started with this line:

y = mx + b

And then immediately jumped into matrices. Cool. Useless.

The thing tutorials skip is what problem are you even trying to solve. Linear regression is, at its core, one question:

If I know X, can I make a reasonable guess at Y?

That's it. If I know the size of a flat in Malad, can I guess the rent? If I know how many standup minutes I sat through, can I guess how many I actually retained? If I know how much coffee I drank today, can I guess how many lines of code I'll commit?

I'm going to answer that last one.

The data I actually collected

For 30 weekdays I tracked two numbers:

  • X: cups of filter coffee I drank that day (one tumbler = one cup, no chai counted)
  • Y: lines of code I committed that day (net additions, from git log --shortstat)

Here are the first 10 rows. The full 30 are at the bottom of this post if you want to play with them yourself.

Day Coffees (X) Lines of code (Y)
1 2 142
2 4 287
3 1 95
4 3 210
5 5 305
6 2 160
7 0 40
8 4 250
9 3 195
10 6 360

scatter plot

Before doing any math, Before doing any math, I dropped the numbers into a scatter plot maker and just sat with it for a minute. You should always do this first. Eyeballs are a free regression model.
and just looked at it. You should always do this first. Eyeballs are a free regression model.

What I saw: a clear-ish upward smear. Not a perfect line — day 5 (5 coffees → 305 lines) and day 10 (6 coffees → 360 lines) sit a bit off the trend, and day 7 (zero coffee, 40 lines) was the day there was a 4-hour power cut and I worked off my laptop battery in a café. But overall, more coffee, more code.

That smear is what linear regression turns into a number.

What we're actually trying to find

We want to draw the single straight line that fits this cloud of points as well as possible.

A line has two parts:

  • Slope (m): how many lines of code does one extra cup of coffee buy me?
  • Intercept (b): how many lines of code do I write on a day with zero coffee?

If I find good values for m and b, then for any future day, I can plug in my coffee count and get a prediction.

But "fits as well as possible" — what does that mean? This is the bit that took me embarrassingly long to internalize.

The "least squares" idea, explained without the squares

Imagine I draw a random line through the cloud. For each real data point, there's a gap between where the point actually is and where my line thinks it should be. That gap is called the residual — basically, how wrong the line was for that day.

If I add up all those gaps, I get a "total wrongness" score. The best line is the one with the smallest score.

One catch: some gaps are positive (line predicted too low), some are negative (predicted too high). If you just add them, they cancel each other out and you get a line that looks correct on paper but is actually terrible.

The fix is to square each gap before adding them. Negatives become positives, big mistakes get punished more than small ones, and now you have a real "wrongness" number worth minimizing.

That's why it's called least squares regression. We're picking the line that makes the sum of squared gaps as small as possible.

That's the whole intuition. The formulas below are just the calculus result of "find the m and b that minimize that sum."

Doing it by hand on 5 data points

Let me use just 5 points so the numbers stay sane:

X Y
2 142
4 287
1 95
3 210
5 305

Step 1: averages.

  • Mean of X: (2+4+1+3+5)/5 = 3
  • Mean of Y: (142+287+95+210+305)/5 = 207.8

Step 2: deviations and products.

For each row I compute (X - meanX), (Y - meanY), their product, and (X - meanX)².

X Y X − 3 Y − 207.8 product (X−3)²
2 142 −1 −65.8 65.8 1
4 287 1 79.2 79.2 1
1 95 −2 −112.8 225.6 4
3 210 0 2.2 0 0
5 305 2 97.2 194.4 4

Sums: products = 565.0, squared deviations = 10.

Step 3: slope.

m = sum of products / sum of squared deviations
m = 565 / 10
m = 56.5

Enter fullscreen mode Exit fullscreen mode

Step 4: intercept.

b = meanY - m * meanX
b = 207.8 - 56.5 * 3
b = 207.8 - 169.5
b = 38.3

Enter fullscreen mode Exit fullscreen mode

So my fitted line is:

lines_of_code ≈ 56.5 * coffees + 38.3

Enter fullscreen mode Exit fullscreen mode

Read in English: every extra cup of coffee buys me ~56 more lines of code, and on a zero-coffee day I'd still grind out about 38 lines. That intercept matches my power-cut day pretty well (40 lines).

I checked this against an online linear regression calculator and got the same numbers, which was nice — I'd been low-key worried I'd dropped a sign somewhere. (When you're learning this, do the by-hand version and then verify with a tool. Two methods agreeing is how you know you actually understand it, not just memorized it.)

The mistake I made the first time

When I ran this on all 30 days, I got a slope of about 53 and an intercept of about 42. Close enough.

But then I made a prediction:

"If I drink 15 cups of coffee, I'll write 53 × 15 + 42 = 837 lines of code."

This is wrong, and it's wrong in a way that's worth understanding. My data only ranged from 0 to 6 cups of coffee. Predicting for 15 cups is called extrapolation, and a linear model has no idea that at 15 cups I would actually be in the ER, not in VS Code.

The relationship is probably linear-ish in the range I measured. Outside that range, all bets are off. Most real-world relationships curve, plateau, or break at some point. Linear regression is a local approximation, not a universal law.

This is the most common mistake I see beginners make, and honestly it's the most common mistake I see in production dashboards too. "Our user growth was linear for six months, so we'll hit ten lakh users by Q4." No you won't.

How good is my line, actually?

A line that's "best" can still be terrible. Imagine if my data were a random cloud — there'd still be a best line, but it would predict nothing useful.

The standard score for this is (pronounced "R squared"). It's a number between 0 and 1:

  • R² = 1: the line passes through every point. Perfect.
  • R² = 0: the line is no better than just guessing the average.
  • R² = 0.7: the line explains about 70% of the variation in Y.

For my 30-day coffee experiment, R² came out to about 0.89. That's strong — coffee really does seem to track my coding output. But correlation isn't causation, and here's where I have to be honest: on high-coffee days I was probably also more rested, more motivated, and not stuck in a 90-minute Outer Ring Road jam. The coffee might be a side effect of a productive day, not the cause of one.

Linear regression will happily fit a line. It will not tell you what causes what. That's your job.

The Python version (5 lines)

Once you understand what's happening, the code is almost a letdown:

import numpy as np

x = np.array([2, 4, 1, 3, 5, 2, 0, 4, 3, 6])
y = np.array([142, 287, 95, 210, 305, 160, 40, 250, 195, 360])

slope, intercept = np.polyfit(x, y, 1)
print(f"y = {slope:.1f}x + {intercept:.1f}")

Enter fullscreen mode Exit fullscreen mode

If you want R² and the rest of the diagnostics, scipy.stats.linregress is the friendlier version:

from scipy.stats import linregress

result = linregress(x, y)
print(f"slope: {result.slope:.2f}")
print(f"intercept: {result.intercept:.2f}")
print(f"r-squared: {result.rvalue**2:.3f}")
print(f"p-value: {result.pvalue:.4f}")

Enter fullscreen mode Exit fullscreen mode

The p-value is asking: "what's the chance this slope is just noise?" Anything under 0.05 is the traditional cutoff for "probably real." Mine came in at 1e-14, which means: almost certainly not a coincidence. (Doesn't mean coffee causes code. Just means the relationship is real, whatever it is.)

When to reach for linear regression in real life

Honestly, more often than you'd think. Some boring-but-genuinely-useful examples from my own work:

  • Estimating ticket resolution time from ticket length. Helps with sprint planning.
  • Predicting cloud bill from monthly active users. Helps when pricing a new tier — and trust me, the finance team will ask.
  • Figuring out at what page-load speed users start churning on a landing page. The slope tells you how many sign-ups each extra 100ms costs.
  • Calibrating a sensor. If your IoT temperature reading drifts linearly off a reference thermometer, regression gives you the correction formula in two lines of Python.

The pattern is always the same: you have an X you can measure cheaply, and a Y you actually care about, and you want a quick "if I move the dial on X by this much, what happens to Y?"

It is not magic. It is a ruler. But it's a ruler that knows about uncertainty, which is more than most rulers can claim.

What to try this week

If you want this to actually stick, don't just read it. Pick something annoying in your life that has two numbers attached to it, and track it for two weeks.

Some ideas to steal:

  • Hours of sleep vs. time-to-first-coffee (or chai) the next morning
  • Number of standup attendees vs. how long it actually ran
  • PRs opened that day vs. PRs you reviewed
  • Daily commute minutes vs. how cranky you felt at the 6 PM standup

Plug it into any regression tool (I obviously used this one), look at the slope, and ask: does this number match my gut? If yes, you've quantified your intuition. If no, you've found something interesting.

That's the whole point of stats, when you strip away the textbook flavor. It's a tool for arguing with your own assumptions.

The full dataset

If you want to reproduce what I got, here's all 30 days:

coffees = [2,4,1,3,5,2,0,4,3,6,2,3,4,1,5,3,2,4,5,1,3,4,2,6,3,4,2,5,3,4]
lines   = [142,287,95,210,305,160,40,250,195,360,170,225,260,80,330,
           205,150,265,310,90,200,255,165,355,200,270,155,315,210,275]

Enter fullscreen mode Exit fullscreen mode

Drop those into the snippet above. You should get a slope around 53, intercept around 42, R² around 0.89.

And then go track something of your own. That's when it actually clicks.


If you spot a math mistake, please yell at me in the comments. I'd rather be embarrassed than wrong.