▶ 展示 · 回索引
08-convergence-rates.html
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>收斂率:全梯度 vs SGD|Convergence Rates: Full Gradient vs SGD</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>
<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">收斂率:全梯度 vs SGD<small>Convergence Rates: Full Gradient vs SGD · IDL115 Ch.3 §4.2 · 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.02" max="0.5" step="0.02" value="0.15"><output id="etaV">0.15</output></label>
<button id="btnPlay" type="button">播放動畫</button>
<button id="btnReset" type="button" class="alt">重設</button>
</div>
<div class="hint" id="hint"><b>操作:</b>拖 η 看紅色帶子變厚、SGD 紅色鋸齒跟著變;按「播放動畫」看 t 從 0 長到 200;「重設」回到完整曲線。</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.15,tmax:200,playing:false};
let timer=null;
const PX0=140, PX1=1500, PY0=600, PY1=180, VMAX=1.2;
const X=t=>PX0+(t/200)*(PX1-PX0);
const Yv=v=>PY0-(v/VMAX)*(PY0-PY1);
const gdV=t=>1/(1+t/8);
function sgdV(t,eta){
const osc=0.55+0.38*Math.abs(Math.sin(0.7*t))+0.03*Math.sin(2.3*t);
return eta*(osc+(0.9/eta)*Math.exp(-t/12));
}
function drawPlot(){
const eta=state.eta, tmax=state.tmax;
/* --- O(η) 停滯帶 --- */
ctx.save();ctx.globalAlpha=0.45;ctx.fillStyle=C.redL;
ctx.fillRect(PX0,Yv(eta),PX1-PX0,PY0-Yv(eta));ctx.restore();
ctx.save();ctx.setLineDash([8,6]);ctx.strokeStyle=C.red;ctx.lineWidth=2;
ctx.beginPath();ctx.moveTo(PX0,Yv(eta));ctx.lineTo(PX1,Yv(eta));ctx.stroke();ctx.restore();
T('O(η) 停滯帶',PX1-8,Yv(eta)-10,{size:13,w:700,c:C.red,a:'right'});
/* --- 座標軸 --- */
ctx.save();ctx.setLineDash([8,6]);ctx.strokeStyle=C.grn;ctx.lineWidth=2;
ctx.beginPath();ctx.moveTo(PX0,PY0);ctx.lineTo(PX1,PY0);ctx.stroke();ctx.restore();
ctx.strokeStyle=C.ink;ctx.lineWidth=2;
ctx.beginPath();ctx.moveTo(PX0,PY0);ctx.lineTo(PX0,PY1);ctx.stroke();
ctx.fillStyle=C.ink;ctx.lineWidth=1.5;
for(let t=0;t<=200;t+=50){ctx.beginPath();ctx.moveTo(X(t),PY0-5);ctx.lineTo(X(t),PY0+5);ctx.stroke();
T(String(t),X(t),624,{size:12,c:C.mut,a:'center'});}
for(const v of [0,0.6,1.2]){T(v.toFixed(1),PX0-10,Yv(v)+4,{size:12,c:C.mut,a:'right'});}
T('iteration t',PX1,650,{size:14,w:700,a:'right'});
T('loss gap f(w) − f*',PX0,168,{size:13,c:C.mut});
T('精確最小 f*(綠色虛線)',PX0+12,PY0-10,{size:12,c:C.grn,w:700});
/* --- GD 藍色平滑曲線 O(1/t) --- */
ctx.strokeStyle=C.blu;ctx.lineWidth=3;ctx.beginPath();
for(let t=0;t<=tmax;t+=1){const x=X(t),y=Yv(gdV(t));if(t===0)ctx.moveTo(x,y);else ctx.lineTo(x,y);}
ctx.stroke();
/* --- SGD 紅色鋸齒曲線 --- */
ctx.strokeStyle=C.red;ctx.lineWidth=2.5;ctx.beginPath();
for(let t=0;t<=tmax;t+=1){const x=X(t),y=Yv(Math.max(0,sgdV(t,eta)));if(t===0)ctx.moveTo(x,y);else ctx.lineTo(x,y);}
ctx.stroke();
/* --- 轉折點標註:約 t=60 進入帶子 --- */
const tx=X(60);
ctx.save();ctx.setLineDash([4,4]);ctx.strokeStyle=C.mut;ctx.lineWidth=1.5;
ctx.beginPath();ctx.moveTo(tx,Yv(eta));ctx.lineTo(tx,PY0);ctx.stroke();ctx.restore();
dot(tx,Yv(sgdV(60,eta)),5,C.red,'#fff',2);
rr(tx-286,Yv(eta)-146,272,52,8);ctx.fillStyle='#fff';ctx.fill();
ctx.strokeStyle=C.red;ctx.lineWidth=1.5;ctx.stroke();
T('一進帶子就出不去',tx-272,Yv(eta)-124,{size:13,w:700,c:C.red});
T('殘差下限 = O(η)',tx-272,Yv(eta)-104,{size:13,w:700,c:C.red});
/* --- 圖例 --- */
const lx=1150;
ctx.strokeStyle=C.blu;ctx.lineWidth=3;ctx.beginPath();ctx.moveTo(lx,206);ctx.lineTo(lx+40,206);ctx.stroke();
T('GD:O(1/t) 貼近 0',lx+50,211,{size:13});
ctx.strokeStyle=C.red;ctx.lineWidth=2.5;ctx.beginPath();ctx.moveTo(lx,232);ctx.lineTo(lx+40,232);ctx.stroke();
T('SGD:進帶子後永遠震盪',lx+50,237,{size:13});
ctx.save();ctx.setLineDash([6,4]);ctx.strokeStyle=C.grn;ctx.lineWidth=2;
ctx.beginPath();ctx.moveTo(lx,258);ctx.lineTo(lx+40,258);ctx.stroke();ctx.restore();
T('精確最小 f*',lx+50,263,{size:13});
ctx.fillStyle=C.redL;ctx.fillRect(lx,270,40,14);ctx.strokeStyle=C.red;ctx.lineWidth=1;ctx.strokeRect(lx,270,40,14);
T('O(η) 停滯帶',lx+50,282,{size:13});
}
function drawFormulasRow(){
T('命題 2:全梯度',40,706,{size:13,w:700});
T('固定步長 η 的 SGD',560,706,{size:13,w:700,c:C.red});
T('遞減步長',1040,706,{size:13,w:700,c:C.teal});
T('把帶子壓扁,長期誤差 → 0',1040,794,{size:14,c:C.mut});
}
function draw(){
ctx.fillStyle=C.bg;ctx.fillRect(0,0,W,H);
header('收斂率:全梯度 vs SGD','Convergence Rates: Full Gradient vs SGD','IDL115','Ch.3 §4.2');
panel(40,110,1520,560,'固定步長 SGD 困在 O(η) 帶子裡','Fixed-step SGD trapped in the O(η) band');
drawPlot();
drawFormulasRow();
strip(40,828,1520,56,'反直覺:SGD 看起來一直在動,固定步長時卻永遠到不了最優;精度換速度,這就是深度學習用 SGD 的原因','SGD keeps moving yet never arrives (fixed η); trading accuracy for speed is why deep learning uses SGD');
}
function initFormulas(){
addFormula({id:'prop2',tex:String.raw`f(\boldsymbol{w}^{(t+1)})-f^{*}\leq \frac{2L\|\boldsymbol{w}^{(0)}-\boldsymbol{w}^{*}\|_2^2}{t+1}=\mathcal{O}(\frac{1}{t})`,x:40,y:712,w:500,fontSize:20});
addFormula({id:'sgdlim',tex:String.raw`\lim_{t\to\infty} f(\boldsymbol{w}^{(t+1)})-f^{*}=\mathcal{O}(\eta)`,x:560,y:712,w:440,fontSize:23});
addFormula({id:'decay',tex:String.raw`\eta^{(\tau)}=\frac{1}{\tau}\ \text{or}\ \frac{1}{\sqrt{\tau}}`,x:1040,y:712,w:480,fontSize:23});
}
document.addEventListener('DOMContentLoaded',()=>{
initFormulas();syncMathLayer();draw();
const eta=document.getElementById('eta'), etaV=document.getElementById('etaV');
eta.addEventListener('input',()=>{state.eta=parseFloat(eta.value);etaV.textContent=state.eta.toFixed(2);draw();});
document.getElementById('btnPlay').addEventListener('click',()=>{
if(state.playing)return;
state.playing=true;state.tmax=0;clearInterval(timer);
timer=setInterval(()=>{
state.tmax+=4;
if(state.tmax>=200){state.tmax=200;clearInterval(timer);state.playing=false;}
draw();
},40);
});
document.getElementById('btnReset').addEventListener('click',()=>{
clearInterval(timer);state.playing=false;state.tmax=200;draw();
});
});
</script>
</body>
</html>