▶ 展示 · 回索引
02-gradient-descent.html
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>梯度下降:學習率與更新規則|Gradient Descent: Learning Rate and the Update Rule</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@400;500;700;900&display=swap" rel="stylesheet">
<style>
:root{--bg:#e8edf0;--fg:#14232e;--mut:#5a6a75;--teal:#1b6f7f;--card:#ffffff;--line:#c5d2d9}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--fg);font-family:"Noto Sans TC","PingFang TC","Microsoft JhengHei","Heiti TC",sans-serif}
.wrap{max-width:1680px;margin:0 auto;padding:14px 16px 24px}
.bar{display:flex;flex-wrap:wrap;gap:8px;align-items:baseline;margin:2px 0 10px}
.bar.t{font-size:17px;font-weight:700}
.bar.t small{display:block;font-weight:400;color:var(--mut);font-size:12.5px}
.stage{position:relative;width:100%;aspect-ratio:16/9;background:#edf1f3;border-radius:6px;overflow:hidden;box-shadow:0 2px 14px rgba(0,0,0,.16)}
canvas{position:absolute;inset:0;width:100%;height:100%;display:block}
/* KaTeX 層:固定 1600x900 logical,與 canvas 同一座標系(SOP 18.5 問題A) */
#math-layer{position:absolute;left:0;top:0;width:1600px;height:900px;transform-origin:top left;pointer-events:none;overflow:hidden}
.formula{position:absolute;transform-origin:top left;line-height:1.25}
.formula .katex-display{margin:0;padding:0}
.controls{display:flex;flex-wrap:wrap;gap:10px 18px;align-items:center;margin-top:10px;background:var(--card);border:1px solid var(--line);border-radius:8px;padding:10px 16px}
.controls label{font-size:14px;font-weight:700;display:flex;align-items:center;gap:8px}
.controls output{font-size:14px;min-width:52px;color:var(--teal);font-weight:700}
button{font:inherit;font-size:14px;font-weight:700;border:0;border-radius:8px;padding:9px 18px;cursor:pointer;background:var(--teal);color:#fff}
button.alt{background:#fff;color:var(--fg);border:1.5px solid var(--mut)}
button.on{background:#e39b0b;color:#14232e}
input[type=range]{width:150px;accent-color:var(--teal)}
.hint{margin-top:8px;font-size:13px;color:var(--mut);line-height:1.7}
.hint b{color:var(--fg)}
</style>
</head>
<body>
<div class="wrap">
<div class="bar"><div class="t">梯度下降:學習率與更新規則<small>Gradient Descent: Learning Rate and the Update Rule · IDL115 第三章 · 16:9 互動式資訊圖表</small></div></div>
<div class="stage" id="stage">
<canvas id="c" width="3200" height="1800"></canvas>
<div id="math-layer"></div>
</div>
<div class="controls" id="controls">
<label>學習率 η <input type="range" id="eta" min="0.05" max="1.2" step="0.05" value="0.3"><output id="etav">0.30</output></label>
<label>起點 w₀ <input type="range" id="w0s" min="-6" max="6" step="0.5" value="4"><output id="w0v">4.0</output></label>
<button id="stepBtn" type="button">走一步</button>
<button id="resetBtn" type="button" class="alt">重設</button>
</div>
<div class="hint" id="hint"><b>操作:</b>拖動滑桿改變學習率與起點,按「走一步」看一次梯度更新;η ≥ 1 會在正負之間震盪甚至發散。</div>
</div>
<script>
/* ================= 共享繪圖系統(1600x900 logical,backing store 3200x1800) ================= */
const stage=document.getElementById('stage'), cv=document.getElementById('c'), ctx=cv.getContext('2d');
const S=2, W=1600, H=900;
ctx.setTransform(S,0,0,S,0,0);
const C={bg:'#EDF1F3',ink:'#14232E',mut:'#5A6A75',teal:'#1B6F7F',tealL:'#DCEBEF',tealM:'#A9CBD3',
amb:'#E39B0B',ambL:'#FBEBC8',red:'#D64545',redL:'#F6DDD6',grn:'#1E8A49',grnL:'#DDF3E4',
blu:'#2563EB',bluL:'#DBEAFE',org:'#EA580C',orgL:'#FDEBD7',pur:'#7C3AED',purL:'#EDE7FB',
pan:'#FFFFFF',line:'#C5D2D9'};
const FAM='"Noto Sans TC","PingFang TC","Microsoft JhengHei","Heiti TC","Segoe UI",sans-serif';
const F=(s,w)=>`${w||400} ${s}px ${FAM}`;
function T(s,x,y,o){o=o||{};ctx.font=F(o.size||15,o.w||400);ctx.fillStyle=o.c||C.ink;
ctx.textAlign=o.a||'left';ctx.textBaseline=o.b||'alphabetic';ctx.fillText(s,x,y);
return ctx.measureText(s).width;}
/* 換行:先把字面 \n 正規化(SOP 18.5),再做中英混合斷詞 */
function wrap(s,maxW,size,w){s=String(s).replace(/\\n/g,'\n');ctx.font=F(size,w);
const out=[];for(const para of s.split('\n')){
const toks=para.match(/[\x21-\x7E\u00A0-\u024F]+|\s+|[^\s]/gu)||[];let line='';
for(const t of toks){if(/^\s+$/.test(t)&&line==='')continue;
if(ctx.measureText(line+t).width>maxW&&line.trim()!==''){out.push(line.trimEnd());line=/^\s+$/.test(t)?'':t;}
else line+=t;}
if(line.trim()!=='')out.push(line.trimEnd());}
return out;}
function P(s,x,y,maxW,lh,size,w,c,a){const ls=wrap(s,maxW,size,w);
ls.forEach((l,i)=>T(l,x,y+i*lh,{size:size,w:w,c:c,a:a}));return ls.length;}
/* 置中段落專用:cx 必須是容器的真正中心 x(SOP 18.5 問題B/I:勿用 wrap(...,'center') 配左緣 x) */
function wrapCenter(s,cx,y,maxW,lh,size,w,c){const ls=wrap(s,maxW,size,w);
ls.forEach((l,i)=>T(l,cx,y+i*lh,{size:size,w:w,c:c,a:'center'}));return ls.length;}
function rr(x,y,w,h,r){ctx.beginPath();ctx.roundRect(x,y,w,h,r);}
function panel(x,y,w,h,zh,en){rr(x,y,w,h,10);ctx.fillStyle=C.pan;ctx.fill();
ctx.strokeStyle=C.line;ctx.lineWidth=1.5;ctx.stroke();
const tw=T(zh,x+18,y+30,{size:17,w:700});T(en,x+18+tw+10,y+30,{size:11.5,c:C.mut});}
function chip(x,y,w,h,txt,bg,fg,size){rr(x,y,w,h,h/2);ctx.fillStyle=bg;ctx.fill();
T(txt,x+w/2,y+h/2+(size||12)*0.35,{size:size||12,w:700,c:fg||'#fff',a:'center'});}
function arrow(x1,y1,x2,y2,col,lw,hs){hs=hs||8;ctx.strokeStyle=col;ctx.fillStyle=col;
ctx.lineWidth=lw||2.5;ctx.lineCap='round';const a=Math.atan2(y2-y1,x2-x1);
ctx.beginPath();ctx.moveTo(x1,y1);ctx.lineTo(x2-Math.cos(a)*hs*0.55,y2-Math.sin(a)*hs*0.55);ctx.stroke();
ctx.beginPath();ctx.moveTo(x2,y2);ctx.lineTo(x2-hs*Math.cos(a-0.42),y2-hs*Math.sin(a-0.42));
ctx.lineTo(x2-hs*Math.cos(a+0.42),y2-hs*Math.sin(a+0.42));ctx.closePath();ctx.fill();}
function dot(x,y,r,fill,stroke,lw){ctx.beginPath();ctx.arc(x,y,r,0,Math.PI*2);
ctx.fillStyle=fill;ctx.fill();if(stroke){ctx.strokeStyle=stroke;ctx.lineWidth=lw||2;ctx.stroke();}}
function strip(x,y,w,h,zh,en,bg,fg){rr(x,y,w,h,8);ctx.fillStyle=bg||C.tealL;ctx.fill();
wrapCenter(zh,x+w/2,y+26,w-40,24,15,700,fg||C.ink);
wrapCenter(en,x+w/2,y+52,w-40,20,12,400,C.mut);}
/* ================= KaTeX hybrid(SOP 4.3;LaTeX 一律用 String.raw 單反斜線,勿雙重跳脫) ================= */
const mathLayer=document.getElementById('math-layer');
function addFormula(o){let el=document.getElementById('fx-'+o.id);
if(!el){el=document.createElement('div');el.className='formula';el.id='fx-'+o.id;mathLayer.appendChild(el);}
el.style.left=o.x+'px';el.style.top=o.y+'px';el.style.width=(o.w||600)+'px';
el.style.textAlign=o.align||'center';el.style.fontSize=(o.fontSize||28)+'px';
el.style.color=o.color||C.ink;
try{katex.render(o.tex,el,{displayMode:true,throwOnError:false});}catch(e){el.textContent='[公式渲染失敗]';}
return el;}
function syncMathLayer(){const r=stage.getBoundingClientRect();
mathLayer.style.transform=`scale(${r.width/W},${r.height/H})`;}
new ResizeObserver(syncMathLayer).observe(stage);
window.addEventListener('resize',syncMathLayer);
window.addEventListener('load',syncMathLayer);
/* ================= 頁首 ================= */
function header(zh,en,tag,tagEn){
T(zh,40,60,{size:40,w:900});
T(en,40,90,{size:19,w:500,c:C.teal});
if(tag){const tw=ctx.measureText(tag).width;
rr(1560-tw-56,30,tw+56,52,26);ctx.fillStyle=C.teal;ctx.fill();
T(tag,1560-28,52,{size:15,w:700,c:'#fff',a:'center'});
if(tagEn)T(tagEn,1560-28,70,{size:10,c:'#CFE6EB',a:'center'});}
}
/* ================= 頁面內容 ================= */
const state={eta:0.3,w0:4,w:4};
function draw(){
ctx.fillStyle=C.bg;ctx.fillRect(0,0,W,H);
header('梯度下降:學習率與更新規則','Gradient Descent: Learning Rate and the Update Rule','IDL115','Ch.3 §2');
/* ---- 左上:更新規則 ---- */
panel(40,110,620,420,'更新規則','Update rules');
T('目標:找出讓損失最小的參數',62,172,{size:14,c:C.mut});
T('(1)',614,214,{size:14,c:C.mut});
T('L-smooth 假設下的理想步長 1/L',62,274,{size:14,c:C.mut});
T('(3)',614,314,{size:14,c:C.mut});
T('實務上 L 常未知,改用固定學習率 η',62,372,{size:14,c:C.mut});
T('(4)',614,412,{size:14,c:C.mut});
P('η 太大:來回震盪甚至發散;η 太小:收斂像烏龜。步長是第一個要調的超參數。',62,448,536,24,15);
/* ---- 右上:互動 ---- */
panel(680,110,880,420,'互動:二次損失上走一步','Interactive: one step on a quadratic loss');
const g=2*state.w, wn=state.w-state.eta*g;
T('w = '+state.w.toFixed(2)+',梯度 ∇f = 2w = '+g.toFixed(2)+',下一步 w_new = w − η·2w = '+wn.toFixed(2)+',f(w) = '+(state.w*state.w).toFixed(2),700,172,{size:14});
if(state.eta>=1)T('η 太大:在 ±w₀ 間震盪(η = 1)/發散(η > 1)',700,198,{size:14,w:700,c:C.red});
const qy=505,qtop=215;
const X=w=>1120+w*(760/12), Y=f=>qy-f*(290/36);
ctx.strokeStyle=C.mut;ctx.lineWidth=1.5;
ctx.beginPath();ctx.moveTo(740,qy);ctx.lineTo(1500,qy);ctx.stroke();
ctx.beginPath();ctx.moveTo(1120,qtop);ctx.lineTo(1120,qy);ctx.stroke();
T('-6',X(-6),qy+22,{size:12,c:C.mut,a:'center'});
T('0',1120,qy+22,{size:12,c:C.mut,a:'center'});
T('6',X(6),qy+22,{size:12,c:C.mut,a:'center'});
T('f(w) = w²',1470,302,{size:13,c:C.mut,a:'right'});
ctx.strokeStyle=C.teal;ctx.lineWidth=3;ctx.beginPath();
for(let i=0;i<=120;i++){const w=-6+i*0.1,x=X(w),y=Y(w*w);i?ctx.lineTo(x,y):ctx.moveTo(x,y);}
ctx.stroke();
if(Math.abs(wn)>7){
T('發散:|w_new| > 7,已超出繪圖範圍',1120,360,{size:16,w:700,c:C.red,a:'center'});
}else{
const x1=X(state.w),y1=Y(state.w*state.w),x2=X(wn),y2=Y(wn*wn);
arrow(x1,y1,x2,y2,C.grn,3,10);
dot(x1,y1,8,C.red,'#fff',2.5);
dot(x2,y2,8,C.grn,'#fff',2.5);
T('現在',x1,y1-18,{size:12.5,w:700,c:C.red,a:'center'});
T('下一步',x2,y2-18,{size:12.5,w:700,c:C.grn,a:'center'});
}
/* ---- 左下:凸目標 ---- */
panel(40,550,760,260,'凸目標','Convex objective');
P('凸函數上,梯度下降保證收斂到全域最低點,loss 單調遞減:每一步都不會比上一步差。',60,662,700,24,15);
ctx.strokeStyle=C.grn;ctx.lineWidth=3.5;ctx.beginPath();
for(let i=0;i<=60;i++){const x=100+i*(640/60),y=800-120*(1-Math.exp(-(x-100)/180));i?ctx.lineTo(x,y):ctx.moveTo(x,y);}
ctx.stroke();
T('loss 單調遞減',420,795,{size:12.5,c:C.mut,a:'center'});
/* ---- 右下:非凸目標 ---- */
panel(820,550,740,260,'非凸目標','Non-convex objective');
P('非凸地形只能保證走到「局部」最低,但整體趨勢仍是下降;深度學習的損失地形幾乎都是非凸的。',840,612,700,22,14);
const wy=x=>725+45*Math.sin((x-860)*0.0152+0.4)+15*Math.sin((x-860)*0.031);
ctx.strokeStyle=C.teal;ctx.lineWidth=3;ctx.beginPath();
for(let i=0;i<=132;i++){const x=860+i*5,y=wy(x);i?ctx.lineTo(x,y):ctx.moveTo(x,y);}
ctx.stroke();
let bx=1300,bv=1e9;
for(let x=1300;x<=1500;x+=2){const v=wy(x);if(v<bv){bv=v;bx=x;}}
const pxs=[900,990,1080,1170,1260,bx];
ctx.strokeStyle=C.red;ctx.lineWidth=2.5;ctx.beginPath();
pxs.forEach((x,i)=>{const y=wy(x);i?ctx.lineTo(x,y):ctx.moveTo(x,y);});
ctx.stroke();
pxs.forEach((x,i)=>dot(x,wy(x),i===pxs.length-1?8:5,i===pxs.length-1?C.grn:C.red,'#fff',2));
T('停在局部最低',bx,wy(bx)+26,{size:12.5,w:700,c:C.grn,a:'center'});
T('從高處出發',900,wy(900)-18,{size:12.5,c:C.mut,a:'center'});
strip(40,828,1520,56,'梯度下降 = 看坡度最陡往哪、反方向走一步;理想步長 1/L,實務用學習率 η','GD = step opposite the steepest slope; ideal step 1/L, in practice use η');
}
function initFormulas(){
addFormula({id:'f1',tex:String.raw`\underset{\boldsymbol{w}}{\operatorname{minimize}}\ f(\boldsymbol{w})`,x:60,y:182,w:545,align:'left',fontSize:28});
addFormula({id:'f3',tex:String.raw`\boldsymbol{w}^{(k+1)}:=\boldsymbol{w}^{(k)}-\frac{1}{L}\nabla f(\boldsymbol{w}^{(k)})`,x:60,y:284,w:545,align:'left',fontSize:24});
addFormula({id:'f4',tex:String.raw`\boldsymbol{w}^{(k+1)}:=\boldsymbol{w}^{(k)}-\eta\nabla f(\boldsymbol{w}^{(k)})`,x:60,y:382,w:545,align:'left',fontSize:24});
addFormula({id:'cvx',tex:String.raw`f(\boldsymbol{w}^{(0)})\geq f(\boldsymbol{w}^{(1)})\geq\cdots\geq f(\boldsymbol{w}^{*})`,x:60,y:572,w:720,fontSize:24});
}
document.addEventListener('DOMContentLoaded',()=>{
initFormulas();syncMathLayer();draw();
const eta=document.getElementById('eta'),etav=document.getElementById('etav');
const w0s=document.getElementById('w0s'),w0v=document.getElementById('w0v');
eta.addEventListener('input',()=>{state.eta=parseFloat(eta.value);etav.textContent=state.eta.toFixed(2);draw();});
w0s.addEventListener('input',()=>{state.w0=parseFloat(w0s.value);state.w=state.w0;w0v.textContent=state.w0.toFixed(1);draw();});
document.getElementById('stepBtn').addEventListener('click',()=>{state.w=+(state.w-state.eta*2*state.w).toFixed(4);draw();});
document.getElementById('resetBtn').addEventListener('click',()=>{state.w=state.w0;draw();});
});
</script>
</body>
</html>