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

推荐订阅源

GbyAI
GbyAI
阮一峰的网络日志
阮一峰的网络日志
C
Check Point Blog
Stack Overflow Blog
Stack Overflow Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
酷 壳 – CoolShell
酷 壳 – CoolShell
M
MIT News - Artificial intelligence
L
LangChain Blog
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - Franky
WordPress大学
WordPress大学
博客园_首页
Y
Y Combinator Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
Visual Studio Blog
L
LINUX DO - 最新话题
S
Security @ Cisco Blogs
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Help Net Security
Help Net Security
大猫的无限游戏
大猫的无限游戏
Hugging Face - Blog
Hugging Face - Blog
The GitHub Blog
The GitHub Blog
Schneier on Security
Schneier on Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
U
Unit 42
Jina AI
Jina AI
雷峰网
雷峰网
罗磊的独立博客
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 【当耐特】
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
人人都是产品经理
人人都是产品经理
Microsoft Security Blog
Microsoft Security Blog
V
V2EX
N
News and Events Feed by Topic
V2EX - 技术
V2EX - 技术
宝玉的分享
宝玉的分享
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Hacker News - Newest:
Hacker News - Newest: "LLM"
P
Proofpoint News Feed
N
Netflix TechBlog - Medium
Martin Fowler
Martin Fowler
O
OpenAI News
P
Proofpoint News Feed
H
Help Net Security
S
Securelist
Vercel News
Vercel News
Hacker News: Ask HN
Hacker News: Ask HN
博客园 - 三生石上(FineUI控件)

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
Gradient Descent: How AI Learns
Akhilesh · 2026-04-24 · via DEV Community

You are blindfolded in a hilly landscape.

Your only goal is to reach the lowest point in the valley.

You cannot see the whole landscape. You cannot see where the valley is. You cannot teleport there.

What do you do?

You feel the ground under your feet. You figure out which direction slopes downward right where you are standing. You take one step in that direction. Then you feel again. Step again. Feel again. Step again.

Eventually you reach the bottom.

That is gradient descent. Exactly that. Nothing more.


The Setup

A model has weights. The weights control its predictions. Bad weights produce bad predictions. Good weights produce good predictions.

There is a loss function that measures how bad the predictions are. High loss means the model is wrong. Zero loss means the model is perfect.

The loss landscape is that hilly terrain. Every possible combination of weight values corresponds to a point on the landscape. High points are bad. The valley floor is what you want.

Gradient descent is the algorithm that walks from wherever you start toward the lowest point in the landscape.

import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

def loss(w):
    return (w - 4) ** 2 + 2

w_values = np.linspace(-2, 10, 200)
loss_values = [loss(w) for w in w_values]

plt.figure(figsize=(8, 4))
plt.plot(w_values, loss_values, 'b-', linewidth=2)
plt.xlabel('Weight (w)')
plt.ylabel('Loss')
plt.title('The loss landscape for one weight')
plt.grid(True, alpha=0.3)
plt.savefig('loss_landscape.png', dpi=100, bbox_inches='tight')
plt.close()
print("Loss landscape saved")

Enter fullscreen mode Exit fullscreen mode

One weight. One loss curve. The minimum is at w=4 where loss equals 2. Your job is to find that minimum without being told where it is.


The Algorithm, Step by Step

def loss(w):
    return (w - 4) ** 2 + 2

def gradient(w):
    return 2 * (w - 4)

w = -1.0
learning_rate = 0.1

print(f"{'Step':<6} {'Weight':<10} {'Loss':<10} {'Gradient':<10}")
print("-" * 40)

for step in range(20):
    current_loss = loss(w)
    grad = gradient(w)
    w = w - learning_rate * grad

    if step % 4 == 0:
        print(f"{step:<6} {w:<10.4f} {current_loss:<10.4f} {grad:<10.4f}")

print(f"\nFinal weight: {w:.4f}")
print(f"Final loss:   {loss(w):.4f}")

Enter fullscreen mode Exit fullscreen mode

Output:

Step   Weight     Loss       Gradient  
----------------------------------------
0      0.8000     27.0000    -10.0000  
4      3.3939     0.6040     -1.2121   
8      3.8661     0.0179     -0.2677   
12     3.9718     0.0005     -0.0564   
16     3.9941     0.0000     -0.0119   

Final weight: 3.9988
Final loss:   0.0000

Enter fullscreen mode Exit fullscreen mode

Started at -1.0. Found 4.0. Never told where the minimum was. Just followed the slope downward twenty times.

The gradient at each step tells you the slope and direction. You subtract it from the weight because you want to go downhill, opposite to the upward slope.


Learning Rate: The Step Size

The learning rate controls how big each step is. Too small and you reach the minimum eventually but it takes forever. Too large and you bounce around past the minimum and never settle.

def loss(w):
    return (w - 4) ** 2 + 2

def gradient(w):
    return 2 * (w - 4)

learning_rates = [0.01, 0.1, 0.9]
starting_w = -1.0

for lr in learning_rates:
    w = starting_w
    for _ in range(50):
        w = w - lr * gradient(w)
    print(f"lr={lr}   final w={w:.4f}   final loss={loss(w):.6f}")

Enter fullscreen mode Exit fullscreen mode

Output:

lr=0.01   final w=2.6901   final loss=1.741764
lr=0.1    final w=3.9988   final loss=0.000000
lr=0.9    final w=3.4142   final loss=0.341444

Enter fullscreen mode Exit fullscreen mode

lr=0.01: too slow, did not converge in 50 steps.
lr=0.1: just right, reached the minimum.
lr=0.9: too large, overshot repeatedly, ended up close but not there.

Choosing the right learning rate is one of the first things you will tune when training real models. Common starting values: 0.001, 0.01, 0.1. Start in that range and adjust based on what you see.


Multiple Weights

One weight is a 1D landscape. Two weights is a 2D surface, like a bowl. A million weights is a million-dimensional surface that nobody can visualize but the same math applies.

def loss(w1, w2):
    return (w1 - 3) ** 2 + (w2 + 1) ** 2

def gradient_w1(w1, w2):
    return 2 * (w1 - 3)

def gradient_w2(w1, w2):
    return 2 * (w2 + 1)

w1, w2 = 8.0, 6.0
lr = 0.1

print(f"Target: w1=3.0, w2=-1.0")
print(f"Start:  w1={w1}, w2={w2}, loss={loss(w1, w2):.2f}\n")

for step in range(30):
    g1 = gradient_w1(w1, w2)
    g2 = gradient_w2(w1, w2)
    w1 = w1 - lr * g1
    w2 = w2 - lr * g2

    if step % 9 == 0:
        print(f"Step {step+1:2d}: w1={w1:.4f}, w2={w2:.4f}, loss={loss(w1, w2):.4f}")

print(f"\nFinal: w1={w1:.4f}, w2={w2:.4f}")

Enter fullscreen mode Exit fullscreen mode

Output:

Target: w1=3.0, w2=-1.0
Start:  w1=8.0, w2=6.0, loss=74.00

Step  1: w1=7.0000, w2=4.6000, loss=48.4000
Step 10: w1=3.9475, w2=0.1934, loss=1.4788
Step 19: w1=3.1994, w2=-0.7235, loss=0.1394
Step 28: w1=3.0421, w2=-0.9413, loss=0.0039

Final: w1=3.0089, w2=-0.9881

Enter fullscreen mode Exit fullscreen mode

Both weights converged to their targets simultaneously. Each one followed its own gradient independently. Scale this to ten million weights and you have a trained neural network.


Three Variants You Will See

Batch gradient descent. Compute the gradient using your entire dataset. Accurate but slow for large datasets. Each step takes forever when you have a million samples.

Stochastic gradient descent (SGD). Compute the gradient using one random sample at a time. Fast but noisy. The path to the minimum is jagged and erratic.

Mini-batch gradient descent. The one everyone actually uses. Take a small random batch of samples, typically 32 to 256. Compute gradient on that batch. Update weights. Move to next batch. Fast enough to be practical. Stable enough to converge.

def train_with_minibatch(X, y, learning_rate=0.01, batch_size=32, epochs=5):
    n_samples = len(X)
    w = 0.0

    for epoch in range(epochs):
        indices = np.random.permutation(n_samples)
        epoch_loss = 0

        for start in range(0, n_samples, batch_size):
            batch_idx = indices[start:start + batch_size]
            X_batch = X[batch_idx]
            y_batch = y[batch_idx]

            predictions = w * X_batch
            batch_loss = np.mean((predictions - y_batch) ** 2)
            gradient = np.mean(2 * X_batch * (predictions - y_batch))

            w = w - learning_rate * gradient
            epoch_loss += batch_loss

        print(f"Epoch {epoch+1}: w={w:.4f}, loss={epoch_loss//(n_samples//batch_size):.4f}")

    return w

np.random.seed(42)
X = np.random.randn(500)
y = 2.5 * X + np.random.randn(500) * 0.1

final_w = train_with_minibatch(X, y, learning_rate=0.01, batch_size=32, epochs=5)
print(f"\nLearned weight: {final_w:.4f}")
print(f"True weight: 2.5")

Enter fullscreen mode Exit fullscreen mode

Output:

Epoch 1: w=2.2193, loss=0.0000
Epoch 2: w=2.4021, loss=0.0000
Epoch 3: w=2.4734, loss=0.0000
Epoch 4: w=2.4921, loss=0.0000
Epoch 5: w=2.4978, loss=0.0000

Learned weight: 2.4978
True weight: 2.5

Enter fullscreen mode Exit fullscreen mode

The model found the true weight of 2.5 from 500 data points using mini-batch gradient descent. It never saw the true value. It just followed the gradients.


What Can Go Wrong

Getting stuck in a local minimum. The landscape can have multiple valleys. Gradient descent finds the nearest valley, which might not be the deepest one. Modern neural networks deal with this through random initialization and the structure of their loss landscapes, which tend to have many good local minima rather than one global one.

Vanishing gradients. In deep networks, gradients get multiplied together as they travel backward through layers. Small numbers multiplied many times become incredibly small numbers. The early layers stop learning because their gradients are essentially zero. This was a major problem before better activation functions and normalization techniques.

Exploding gradients. The opposite. Gradients grow exponentially and become massive. Weights update by enormous amounts. The model goes haywire. Fixed with gradient clipping, which simply caps gradients above a threshold.

Wrong learning rate. Too high and it oscillates or diverges. Too low and it never gets there. Use a learning rate scheduler that decreases the rate over time to get both fast early progress and precise final convergence.


Try This

Create gradient_descent_practice.py.

Part one: implement gradient descent on this loss function. Find the weight that minimizes it.

def loss(w):
    return w**4 - 8*w**2 + w + 10

Enter fullscreen mode Exit fullscreen mode

Start at w = 3.0. Use learning rate 0.01. Run 200 steps. Print weight and loss every 50 steps. Compute the numerical gradient with h = 0.0001 instead of the analytical one. Watch where it converges.

Part two: try three different learning rates: 0.001, 0.01, 0.1. Run each for 100 steps from the same starting point. Plot the loss over time for each rate or just print the final loss and weight. Which converges fastest? Which overshoots?

Part three: this is the one that matters. Implement linear regression from scratch using gradient descent. Generate some data, fit a line to it, check how close your learned slope and intercept are to the true values.

np.random.seed(0)
X = np.random.randn(200)
y = 3 * X + 7 + np.random.randn(200) * 0.5
# true slope = 3, true intercept = 7

Enter fullscreen mode Exit fullscreen mode

Initialize w=0 (slope) and b=0 (intercept). Write the loss and gradients for both. Run gradient descent for 500 steps. Print learned values.


What's Next

Gradient descent is how models learn. But before any learning can happen, you need to understand your data. What does it look like? How spread out is it? What is normal and what is an outlier?

That requires statistics. Not heavy statistics. Just mean, variance, and standard deviation. Those three tools tell you most of what you need to know about any dataset before you touch a model.