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

推荐订阅源

V2EX - 技术
V2EX - 技术
T
Troy Hunt's Blog
The Last Watchdog
The Last Watchdog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
S
Secure Thoughts
Hacker News - Newest:
Hacker News - Newest: "LLM"
WordPress大学
WordPress大学
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 司徒正美
TaoSecurity Blog
TaoSecurity Blog
博客园 - Franky
有赞技术团队
有赞技术团队
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
L
LINUX DO - 最新话题
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
NISL@THU
NISL@THU
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Recent Commits to openclaw:main
Recent Commits to openclaw:main
K
Kaspersky official blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
W
WeLiveSecurity
SecWiki News
SecWiki News
Google DeepMind News
Google DeepMind News
O
OpenAI News
V
V2EX
AI
AI
博客园_首页
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
美团技术团队
C
Cyber Attacks, Cyber Crime and Cyber Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Security Archives - TechRepublic
Security Archives - TechRepublic
博客园 - 三生石上(FineUI控件)
G
GRAHAM CLULEY
月光博客
月光博客
T
Threatpost
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Vulnerabilities – Threatpost
Last Week in AI
Last Week in AI
爱范儿
爱范儿
C
CXSECURITY Database RSS Feed - CXSecurity.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Cloudbric
Cloudbric
酷 壳 – CoolShell
酷 壳 – CoolShell
The Hacker News
The Hacker News
N
News | PayPal Newsroom
Know Your Adversary
Know Your Adversary

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
Word Embeddings Explained: The Math Behind AI, LLMs, and Chatbots
Malcolm Low · 2026-05-16 · via DEV Community

Malcolm Low

Originally published on malcolmlow.net

When a search engine retrieves a document about automobiles in response to a query about cars, it is not matching text character by character. Somewhere beneath the interface, the system understands that these two words are semantically related. The mechanism behind that understanding is the word embedding — and once you see the geometry, you cannot unsee it.

This article walks through the key mathematical operations that make embeddings work: distance, similarity, arithmetic, scaling, and the dot product. Each concept is illustrated with concrete numerical vectors so the math is visible, not just described. Real embeddings typically use hundreds of dimensions; the 3- and 4-dimensional examples here preserve all the structure while staying readable on a page.


1 · What is a Word Embedding?

A word embedding is a representation of a word as a vector — an ordered list of numbers — in a high-dimensional space. A typical embedding model might use 300 dimensions, so the word cat becomes a point with 300 coordinates. The key insight: the position of that point encodes meaning.

This is what researchers call a semantic space. Words with related meanings end up positioned close to each other. King and Queen live near each other. Paris and London live near each other. Bicycle and democracy live far apart.

Example: 4-dimensional vectors (simplified from real 300-dim embeddings)

vec("King")  = [ 0.9,  0.7,  0.4, +0.6 ]
vec("Queen") = [ 0.9,  0.7,  0.4, -0.6 ]
vec("Man")   = [ 0.5,  0.3,  0.1, +0.8 ]
vec("Woman") = [ 0.5,  0.3,  0.1, -0.8 ]

Enter fullscreen mode Exit fullscreen mode

The first three dimensions encode royalty, authority, and age. The fourth dimension encodes gender: positive = masculine, negative = feminine.


2 · The Geometry of Meaning: Distance and Similarity

Once words are points in space, we need a way to measure how close they are. Two approaches dominate: Euclidean distance and cosine similarity.

Temperature vectors (3 dimensions)

vec("Hot")  = [ 1.0,  0.8,  0.6 ]
vec("Warm") = [ 0.8,  0.6,  0.4 ]
vec("Cold") = [-0.6,  0.4, -0.8 ]

Enter fullscreen mode Exit fullscreen mode

2.1 Euclidean Distance

The straight-line gap between the tips of two vectors:

d(a, b) = √ Σᵢ (aᵢ − bᵢ)²

Enter fullscreen mode Exit fullscreen mode

Worked example:

d(Hot, Warm) = √[(1.0-0.8)² + (0.8-0.6)² + (0.6-0.4)²]
             = √[0.04 + 0.04 + 0.04] = √0.12 ≈ 0.346  ← small: close together

d(Hot, Cold) = √[(1.0-(-0.6))² + (0.8-0.4)² + (0.6-(-0.8))²]
             = √[2.56 + 0.16 + 1.96] = √4.68 ≈ 2.163  ← large: far apart

Enter fullscreen mode Exit fullscreen mode

2.2 Cosine Similarity — The Industry Standard

In practice, NLP systems almost universally prefer cosine similarity. It ignores vector length entirely and focuses only on the angle between them — two vectors pointing the same direction score 1.0 regardless of magnitude.

cos(θ) = (a · b) / (‖a‖ × ‖b‖)

Range: −1 (opposite) → 0 (orthogonal) → +1 (identical direction)

Enter fullscreen mode Exit fullscreen mode

Worked example:

‖Hot‖  = √(1.0² + 0.8² + 0.6²) = √2.00 ≈ 1.414
‖Warm‖ = √(0.8² + 0.6² + 0.4²) = √1.16 ≈ 1.077
‖Cold‖ = √(0.6² + 0.4² + 0.8²) = √1.16 ≈ 1.077

dot(Hot, Warm) = (1.0)(0.8) + (0.8)(0.6) + (0.6)(0.4) = 1.52
cos(Hot, Warm) = 1.52 / (1.414 × 1.077) ≈ +0.998   ← nearly identical direction

dot(Hot, Cold) = (1.0)(-0.6) + (0.8)(0.4) + (0.6)(-0.8) = -0.76
cos(Hot, Cold) = -0.76 / (1.414 × 1.077) ≈ -0.499  ← opposite directions

Enter fullscreen mode Exit fullscreen mode

Word Pair Euclidean d cos(θ) Interpretation
Hot vs Warm 0.346 +0.998 Nearly identical direction — closely related
Hot vs Cold 2.163 −0.499 Opposite directions — antonyms

3 · Vector Arithmetic: Meaning You Can Add and Subtract

Because words are vectors, you can perform arithmetic on them — and the results are semantically meaningful. The most famous example:

vec("King") − vec("Man") + vec("Woman") ≈ vec("Queen")

Enter fullscreen mode Exit fullscreen mode

Worked example:

King  = [ 0.9,  0.7,  0.4, +0.6 ]
Man   = [ 0.5,  0.3,  0.1, +0.8 ]
Woman = [ 0.5,  0.3,  0.1, -0.8 ]

King − Man = [ 0.4,  0.4,  0.3, -0.2 ]
+ Woman    = [ 0.9,  0.7,  0.4, -1.0 ]

d(result, Queen)  ≈ 0.400  ← nearest
d(result, Woman)  ≈ 0.671
d(result, King)   = 1.600
cos(result, Queen) ≈ 0.974  ← highest cosine similarity

Enter fullscreen mode Exit fullscreen mode

What happened geometrically? Subtracting Man stripped out the gender dimension, leaving the royalty structure intact. Adding Woman injected the feminine gender value. The result sits 0.4 units from Queen — the nearest word in this vocabulary.


4 · Scalar Multiplication and Division: Changing Intensity

Multiplying or dividing a vector by a scalar changes its magnitude without changing its direction. This maps onto the idea of degree in language — Tiny, Large, and Gigantic all point in roughly the same semantic direction, at different intensities.

Size vectors (3 dimensions)

vec("Tiny")     = [ 0.10,  0.20,  0.10 ]
vec("Large")    = [ 0.50,  0.70,  0.40 ]
vec("Gigantic") = [ 1.10,  1.50,  0.90 ]

Enter fullscreen mode Exit fullscreen mode

Worked example:

Large × 2   = [ 1.00, 1.40, 0.80 ]
vec("Gigantic") = [ 1.10, 1.50, 0.90 ]
d(Large × 2, Gigantic) ≈ 0.173  ← very close

Large × 0.2 = [ 0.10, 0.14, 0.08 ]
vec("Tiny")     = [ 0.10, 0.20, 0.10 ]
d(Large × 0.2, Tiny) ≈ 0.063   ← very close

Loud ÷ 2 lands near "Soft" — direction unchanged, intensity halved.

Enter fullscreen mode Exit fullscreen mode

Key intuition: Scalar operations change how much of something a vector represents, without changing what kind of thing it represents.


5 · The Dot Product: Agreement and Magnitude Together

a · b = Σᵢ (aᵢ × bᵢ) = a₁b₁ + a₂b₂ + … + aₙbₙ

Enter fullscreen mode Exit fullscreen mode

The dot product captures two things simultaneously: the direction of agreement and the combined magnitude. Cosine similarity captures only the first.

Worked example — Very Loud vs A Little Loud:

vec("A Little Loud") = [ 0.30, 0.40, 0.20 ]  |magnitude| = 0.539
vec("Very Loud")     = [ 0.90, 1.20, 0.60 ]  |magnitude| = 1.616

dot(AL, VL) = (0.3)(0.9) + (0.4)(1.2) + (0.2)(0.6) = 0.87
cos(AL, VL) = 0.87 / (0.539 × 1.616) ≈ 1.000  ← perfect alignment

AL · AL = 0.09 + 0.16 + 0.04 = 0.29
VL · VL = 0.81 + 1.44 + 0.36 = 2.61

Enter fullscreen mode Exit fullscreen mode

Comparison Magnitude cos(θ) v · v
A Little Loud 0.539 1.000 0.29
Very Loud 1.616 1.000 2.61

Both are perfectly collinear — cosine similarity is 1.0 in both cases. But the dot products are 0.29 vs 2.61, a 9× difference. This is why recommendation systems and attention mechanisms in transformer models often prefer raw dot products: when you want to know not just whether a document is relevant but also how prominently it discusses a topic, the dot product gives you both dimensions at once.


6 · Practical Applications

Search engines convert your query into a vector and retrieve documents whose vectors are nearest to it — using cosine similarity to rank by relevance regardless of exact word match. When you search for car insurance and get results about vehicle coverage, that's nearest-neighbour lookup in embedding space.

Recommendation systems represent your interests as a vector computed from your history, then find products whose vectors are closest. The dot product is particularly useful here: a highly-relevant item with a large magnitude will score higher than a mildly-relevant item even if they point in the same direction.

Large language models use the scaled dot product directly inside the attention mechanism. For every token, a query vector and a set of key vectors are compared via dot product to determine which parts of the context deserve attention — a direct descendant of the arithmetic in Section 5.


Quick Reference: Embedding Operations

Operation Formula Result
Euclidean Distance √(Σ(aᵢ−bᵢ)²) d(Hot,Warm)=0.346 / d(Hot,Cold)=2.163
Cosine Similarity (a·b)/(‖a‖×‖b‖) cos(Hot,Warm)=+0.998 / cos(Hot,Cold)=-0.499
Vector Arithmetic a ± b King−Man+Woman → nearest Queen (d=0.400)
Scalar Multiplication λ · a Large×2 → near Gigantic / Loud÷2 → near Soft
Dot Product a·b = Σaᵢbᵢ cos=1.00 for both; dot 0.29 (soft) vs 2.61 (loud)