Prompt specification
Build or customize the Three.js 3D scene "Model-fitting educational studio" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Model-fitting educational studio
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/model-fitting-educational-studio-x1883
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts gradient descent on a loss surface. Compose synthetic data points, a fitted line, and a two-parameter loss surface; connect parameter movement to residual reduction without claiming training success from visual smoothness alone. Voxel style.
Working Three.js Starter (model-fitting-educational-studio-x1883):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gradient Descent — Voxel Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #070a12;
--panel: rgba(10, 15, 27, 0.88);
--line: rgba(150, 190, 255, 0.2);
--text: #e9f1ff;
--muted: #8d9cb7;
--mint: #65fbd2;
--cyan: #78c8ff;
--amber: #ffbd5a;
--coral: #ff627d;
--violet: #9d7cff;
--gold: #ffd166;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
"Liberation Mono", monospace;
}
canvas {
display: block;
width: 100%;
height: 100%;
image-rendering: pixelated;
touch-action: none;
}
body::after {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
z-index: 20;
opacity: 0.12;
background:
repeating-linear-gradient(
to bottom,
transparent 0,
transparent 3px,
rgba(0, 0, 0, 0.32) 4px
);
}
#ui {
position: fixed;
inset: 0;
z-index: 10;
pointer-events: none;
}
.panel,
.controls {
pointer-events: auto;
background: var(--panel);
border: 1px solid var(--line);
box-shadow:
0 12px 36px rgba(0, 0, 0, 0.32),
inset 0 1px rgba(255, 255, 255, 0.035);
backdrop-filter: blur(12px);
}
header {
position: absolute;
top: 20px;
left: 22px;
max-width: 560px;
pointer-events: none;
}
.eyebrow {
color: var(--mint);
font-size: 10px;
letter-spacing: 0.2em;
text-transform: uppercase;
margin-bottom: 7px;
}
h1 {
margin: 0;
font-size: clamp(18px, 2.3vw, 30px);
line-height: 1.05;
letter-spacing: -0.045em;
}
header p {
margin: 8px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.live-badge {
display: inline-flex;
align-items: center;
gap: 7px;
margin-top: 12px;
padding: 6px 8px;
border: 1px solid rgba(101, 251, 210, 0.25);
color: var(--mint);
background: rgba(101, 251, 210, 0.06);
font-size: 9px;
letter-spacing: 0.1em;
}
.live-badge::before {
content: "";
width: 6px;
height: 6px;
background: var(--mint);
box-shadow: 0 0 10px var(--mint);
}
.metrics {
position: absolute;
top: 20px;
right: 20px;
width: 292px;
padding: 14px;
}
.panel-title {
display: flex;
justify-content: space-between;
align-items: center;
padding-bottom: 10px;
margin-bottom: 11px;
border-bottom: 1px solid var(--line);
color: #cfe0ff;
font-size: 10px;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.state {
color: var(--gold);
font-size: 9px;
letter-spacing: 0.04em;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-height: 60px;
padding: 9px;
background: rgba(255, 255, 255, 0.025);
border: 1px solid rgba(255, 255, 255, 0.055);
}
.metric-label {
color: var(--muted);
font-size: 8px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric-value {
margin-top: 7px;
color: var(--text);
font-size: 18px;
font-variant-numeric: tabular-nums;
}
.metric-value.train { color: var(--mint); }
.metric-value.holdout { color: var(--amber); }
.metric-value.param { color: var(--cyan); }
.equation {
margin-top: 11px;
padding: 10px;
background: rgba(120, 200, 255, 0.045);
border-left: 2px solid var(--cyan);
color: #b7c9e4;
font-size: 9px;
line-height: 1.65;
}
.loss-track {
height: 7px;
margin-top: 12px;
background: rgba(255, 255, 255, 0.055);
overflow: hidden;
}
#lossFill {
width: 0;
height: 100%;
background: linear-gradient(90deg, var(--coral), var(--gold), var(--mint));
transition: width 80ms linear;
}
.track-caption {
display: flex;
justify-content: space-between;
margin-top: 6px;
color: var(--muted);
font-size: 8px;
}
.legend {
position: absolute;
left: 22px;
bottom: 104px;
display: grid;
gap: 7px;
padding: 11px 13px;
pointer-events: none;
background: rgba(7, 10, 18, 0.72);
border-left: 2px solid rgba(120, 200, 255, 0.4);
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
color: #aab9d0;
font-size: 9px;
}
.swatch {
width: 9px;
height: 9px;
box-shadow: 0 0 9px currentColor;
background: currentColor;
}
.swatch.train { color: var(--mint); }
.swatch.holdout { color: var(--amber); }
.swatch.fit { color: var(--cyan); }
.swatch.residual { color: var(--coral); }
.swatch.loss { color: var(--violet); }
.controls {
position: absolute;
left: 50%;
bottom: 20px;
transform: translateX(-50%);
width: min(760px, calc(100vw - 40px));
padding: 12px 14px;
display: grid;
grid-template-columns: auto 1fr 1fr auto;
align-items: center;
gap: 13px;
}
.button-row {
display: flex;
gap: 6px;
}
button {
height: 32px;
min-width: 66px;
padding: 0 10px;
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: 0;
color: var(--text);
background: rgba(255, 255, 255, 0.055);
font: 700 9px ui-monospace, monospace;
letter-spacing: 0.07em;
cursor: pointer;
}
button:hover {
border-color: var(--mint);
color: var(--mint);
background: rgba(101, 251, 210, 0.07);
}
button.primary {
color: #06110f;
background: var(--mint);
border-color: var(--mint);
}
button.primary:hover {
color: #06110f;
background: #a2ffe4;
}
.slider-control label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 8px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.slider-control output {
color: var(--cyan);
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
appearance: none;
background: rgba(255, 255, 255, 0.11);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 12px;
height: 12px;
appearance: none;
border: 2px solid #081018;
background: var(--cyan);
box-shadow: 0 0 9px rgba(120, 200, 255, 0.5);
}
input[type="range"]::-moz-range-thumb {
width: 10px;
height: 10px;
border: 2px solid #081018;
background: var(--cyan);
}
.check {
display: flex;
align-items: center;
gap: 6px;
color: var(--muted);
font-size: 8px;
white-space: nowrap;
}
.check input {
accent-color: var(--coral);
}
.guardrail {
position: absolute;
right: 20px;
bottom: 104px;
width: 292px;
padding: 12px 13px;
border-left: 2px solid var(--amber);
}
.guardrail strong {
display: block;
margin-bottom: 6px;
color: var(--amber);
font-size: 9px;
letter-spacing: 0.11em;
}
.guardrail p {
margin: 0;
color: #a9b7cd;
font-size: 9px;
line-height: 1.6;
}
.hint {
position: absolute;
left: 22px;
bottom: 22px;
color: rgba(174, 193, 220, 0.52);
font-size: 8px;
letter-spacing: 0.05em;
pointer-events: none;
}
@media (max-width: 850px) {
header {
top: 14px;
left: 14px;
max-width: calc(100vw - 28px);
}
header p,
.live-badge {
display: none;
}
.metrics {
top: 72px;
right: 12px;
width: 232px;
padding: 10px;
}
.metric {
min-height: 51px;
padding: 7px;
}
.metric-value { font-size: 15px; }
.equation { display: none; }
.legend {
left: 14px;
bottom: 90px;
}
.guardrail {
right: 12px;
bottom: 90px;
width: 252px;
}
.controls {
bottom: 12px;
width: calc(100vw - 24px);
grid-template-columns: auto 1fr;
}
.speed-control { display: none; }
.hint { display: none; }
}
@media (max-width: 600px) {
.metrics {
width: 206px;
}
.metric-grid {
grid-template-columns: 1fr 1fr;
gap: 5px;
}
.legend {
display: none;
}
.guardrail {
left: 12px;
right: 12px;
bottom: 86px;
width: auto;
}
.controls {
gap: 9px;
}
.button-row {
gap: 4px;
}
button {
min-width: 56px;
padding: 0 7px;
}
.check { display: none; }
}
</style>
</head>
<body>
<div id="ui">
<header>
<div class="eyebrow">Interactive optimization diagram / 01</div>
<h1>GRADIENT DESCENT<br>VOXEL LAB</h1>
<p>
One parameter pair drives both views: the regression line and the
two-parameter MSE surface.
</p>
<div class="live-badge">LIVE PARAMETER TRACE</div>
</header>
<aside class="panel metrics">
<div class="panel-title">
<span>Parameter State</span>
<span class="state" id="stateText">DESCENDING −∇MSE</span>
</div>
<div class="metric-grid">
<div class="metric">
<div class="metric-label">Weight w</div>
<div class="metric-value param" id="wValue">0.000</div>
</div>
<div class="metric">
<div class="metric-label">Bias b</div>
<div class="metric-value param" id="bValue">0.000</div>
</div>
<div class="metric">
<div class="metric-label">Train MSE</div>
<div class="metric-value train" id="trainValue">0.000</div>
</div>
<div class="metric">
<div class="metric-label">Holdout MSE</div>
<div class="metric-value holdout" id="holdoutValue">0.000</div>
</div>
<div class="metric">
<div class="metric-label">Mean |residual|</div>
<div class="metric-value" id="residualValue">0.000</div>
</div>
<div class="metric">
<div class="metric-label">Gradient norm</div>
<div class="metric-value" id="gradientValue">0.000</div>
</div>
</div>
<div class="equation">
ŷ = wx + b<br>
MSE = mean(ŷ − y)²<br>
update: (w, b) ← (w, b) − η∇MSE
</div>
<div class="loss-track"><div id="lossFill"></div></div>
<div class="track-caption">
<span id="lossDelta">MSE CHANGE VS START</span>
<span id="stepValue">STEP 0</span>
</div>
</aside>
<div class="legend">
<div class="legend-row">
<span class="swatch train"></span>
SYNTHETIC TRAIN POINT
</div>
<div class="legend-row">
<span class="swatch holdout"></span>
HELD-OUT POINT
</div>
<div class="legend-row">
<span class="swatch fit"></span>
FITTED LINE Ŷ = WX + B
</div>
<div class="legend-row">
<span class="swatch residual"></span>
TRAIN RESIDUAL
</div>
<div class="legend-row">
<span class="swatch loss"></span>
MSE LOSS SURFACE
</div>
</div>
<aside class="panel guardrail">
<strong>READ THE TRACE, NOT THE LOOK</strong>
<p>
A smooth path or shrinking residuals does not by itself prove successful
training. Check convergence, learning-rate stability, and held-out loss.
</p>
</aside>
<section class="panel controls">
<div class="button-row">
<button id="playButton" class="primary" type="button">PAUSE</button>
<button id="replayButton" type="button">REPLAY</button>
<button id="cameraButton" type="button">VIEW</button>
</div>
<div class="slider-control">
<label>
<span>Learning rate η</span>
<output id="lrOutput">0.045</output>
</label>
<input id="lrSlider" type="range" min="0.010" max="0.090"
step="0.005" value="0.045">
</div>
<div class="slider-control speed-control">
<label>
<span>Trace speed</span>
<output id="speedOutput">7 steps/s</output>
</label>
<input id="speedSlider" type="range" min="2" max="18"
step="1" value="7">
</div>
<label class="check">
<input id="residualToggle" type="checkbox" checked>
RESIDUALS
</label>
</section>
<div class="hint">DRAG TO ORBIT · WHEEL TO ZOOM · DOUBLE-CLICK TO RESET VIEW</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Synthetic data
// ---------------------------------------------------------------------
const train = [
{ x: -2.4, y: -3.25 },
{ x: -1.6, y: -2.18 },
{ x: -0.9, y: -1.12 },
{ x: -0.2, y: -0.48 },
{ x: 0.45, y: 0.24 },
{ x: 1.1, y: 0.98 },
{ x: 1.8, y: 1.78 },
{ x: 2.5, y: 2.62 }
];
const holdout = [
{ x: -2.05, y: -2.72 },
{ x: -0.55, y: -0.82 },
{ x: 0.76, y: 0.72 },
{ x: 2.14, y: 2.31 }
];
const initial = { w: 0.05, b: 1.15 };
const W_MIN = -2;
const W_MAX = 3;
const B_MIN = -3;
const B_MAX = 3;
const DATA_X0 = -7.6;
const DATA_X1 = -2.4;
const DATA_Z0 = -3.8;
const DATA_Z1 = 3.8;
const SURFACE_X0 = 4.6;
const SURFACE_X1 = 9.2;
const SURFACE_Z0 = -2.8;
const SURFACE_Z1 = 2.8;
const clamp = (x, a, b) => Math.max(a, Math.min(b, x));
const map = (x, a, b, c, d) => c + ((x - a) / (b - a)) * (d - c);
function mseFor(w, b, points = train) {
let sum = 0;
for (const p of points) {
const e = w * p.x + b - p.y;
sum += e * e;
}
return sum / points.length;
}
function gradientFor(w, b) {
let gw = 0;
let gb = 0;
for (const p of train) {
const e = w * p.x + b - p.y;
gw += 2 * p.x * e / train.length;
gb += 2 * e / train.length;
}
return { w: gw, b: gb };
}
function lossHeight(loss) {
// Compresses high-loss corners while preserving a readable basin.
return 0.18 + 3.15 * (1 - Math.exp(-Math.max(0, loss) / 7));
}
// ---------------------------------------------------------------------
// Renderer and scene
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x070a12);
scene.fog = new THREE.Fog(0x070a12, 24, 44);
const renderer = new THREE.WebGLRenderer({
antialias: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.6));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.16;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.prepend(renderer.domElement);
const camera = new THREE.OrthographicCamera(-10, 10, 6, -6, 0.1, 100);
const cameraTarget = new THREE.Vector3(0.55, 0.7, 0);
const cameraState = {
theta: 0.72,
phi: 0.94,
radius: 20
};
const hemisphere = new THREE.HemisphereLight(0xc9e4ff, 0x24112d, 2.2);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(-5, 12, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -13;
keyLight.shadow.camera.right = 13;
keyLight.shadow.camera.top = 11;
keyLight.shadow.camera.bottom = -11;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xa579ff, 1.1);
fillLight.position.set(10, 6, -7);
scene.add(fillLight);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0.04,
flatShading: true,
...options
});
}
function box(parent, sx, sy, sz, mat, x = 0, y = 0, z = 0) {
const mesh = new THREE.Mesh(unitBox, mat);
mesh.scale.set(sx, sy, sz);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function textSprite(text, color = "#dce9ff", scale = 2.3) {
const canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(7, 12, 23, 0.72)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = "rgba(150, 190, 255, 0.26)";
ctx.strokeRect(3, 3, canvas.width - 6, canvas.height - 6);
ctx.font = "700 44px monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = color;
ctx.fillText(text, canvas.width / 2, canvas.height / 2 + 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.magFilter = THREE.NearestFilter;
texture.minFilter = THREE.LinearMipmapLinearFilter;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
fog: false
}));
sprite.scale.set(scale, scale * 0.2, 1);
sprite.renderOrder = 20;
return sprite;
}
// ---------------------------------------------------------------------
// Data plane
// ---------------------------------------------------------------------
const floorMat = material(0x0c1220);
const gridMat = material(0x26354d);
const axisMat = material(0x526783);
const trainMat = material(0x65fbd2, {
emissive: 0x123f36,
emissiveIntensity: 0.75
});
const holdoutMat = material(0xffbd5a, {
emissive: 0x4a2a05,
emissiveIntensity: 0.6
});
const fitMat = material(0x78c8ff, {
emissive: 0x123a5e,
emissiveIntensity: 0.9
});
const residualMat = material(0xff627d, {
emissive: 0x4a111e,
emissiveIntensity: 0.85
});
const dataFloor = new THREE.Group();
scene.add(dataFloor);
box(
dataFloor,
DATA_X1 - DATA_X0 + 0.25,
0.12,
DATA_Z1 - DATA_Z0 + 0.25,
floorMat,
(DATA_X0 + DATA_X1) / 2,
-0.09,
0
);
for (let x = -3; x <= 3; x++) {
const px = map(x, -3, 3, DATA_X0, DATA_X1);
box(dataFloor, 0.018, 0.018, DATA_Z1 - DATA_Z0, gridMat, px, 0.012, 0);
}
for (let z = -4; z <= 4; z++) {
const pz = map(z, -4, 4, DATA_Z0, DATA_Z1);
box(dataFloor, DATA_X1 - DATA_X0, 0.018, 0.018, gridMat,
(DATA_X0 + DATA_X1) / 2, 0.012, pz);
}
box(dataFloor, DATA_X1 - DATA_X0, 0.045, 0.045, axisMat,
(DATA_X0 + DATA_X1) / 2, 0.04, DATA_Z0);
box(dataFloor, 0.045, 0.045, DATA_Z1 - DATA_Z0, axisMat,
DATA_X0, 0.04, 0);
const dataTitle = textSprite("DATA + REGRESSION", "#78c8ff", 3.0);
dataTitle.position.set(-5.0, 4.25, -3.0);
scene.add(dataTitle);
const xLabel = textSprite("INPUT X", "#91a5c4", 1.25);
xLabel.position.set(-2.35, 0.25, -4.05);
scene.add(xLabel);
const yLabel = textSprite("OUTPUT Ŷ", "#91a5c4", 1.55);
yLabel.position.set(-7.95, 0.25, 3.75);
scene.add(yLabel);
function createTrainPoint(x, y) {
const group = new THREE.Group();
group.position.set(map(x, -3, 3, DATA_X0, DATA_X1), 0.35, y);
box(group, 0.25, 0.25, 0.25, material(0x071018), 0, 0, 0);
box(group, 0.17, 0.17, 0.17, trainMat, 0, 0.015, 0);
box(group, 0.08, 0.08, 0.08, material(0xd8fff4), 0, 0.115, 0);
scene.add(group);
}
function createHoldoutPoint(x, y) {
const group = new THREE.Group();
group.position.set(map(x, -3, 3, DATA_X0, DATA_X1), 0.35, y);
// Four amber voxels form a hollow marker.
box(group, 0.22, 0.09, 0.06, holdoutMat, 0, 0, -0.08);
box(group, 0.22, 0.09, 0.06, holdoutMat, 0, 0, 0.08);
box(group, 0.06, 0.09, 0.22, holdoutMat, -0.08, 0, 0);
box(group, 0.06, 0.09, 0.22, holdoutMat, 0.08, 0, 0);
scene.add(group);
}
train.forEach(p => createTrainPoint(p.x, p.y));
holdout.forEach(p => createHoldoutPoint(p.x, p.y));
const fitBlocks = [];
const FIT_SAMPLES = 64;
const fitStart = -2.86;
const fitEnd = 2.86;
for (let i = 0; i < FIT_SAMPLES; i++) {
fitBlocks.push(box(scene, 0.1, 0.075, 0.075, fitMat));
}
const residualGroup = new THREE.Group();
scene.add(residualGroup);
const residualBlocks = [];
for (let i = 0; i < train.length; i++) {
for (let j = 0; j < 5; j++) {
residualBlocks.push(box(residualGroup, 0.04, 0.04, 0.04, residualMat));
}
}
// ---------------------------------------------------------------------
// Loss surface made from voxel columns
// ---------------------------------------------------------------------
const surfaceFloor = new THREE.Group();
scene.add(surfaceFloor);
box(
surfaceFloor,
SURFACE_X1 - SURFACE_X0 + 0.32,
0.12,
SURFACE_Z1 - SURFACE_Z0 + 0.32,
floorMat,
(SURFACE_X0 + SURFACE_X1) / 2,
-0.09,
0
);
box(
surfaceFloor,
SURFACE_X1 - SURFACE_X0,
0.045,
0.045,
axisMat,
(SURFACE_X0 + SURFACE_X1) / 2,
0.04,
SURFACE_Z0
);
box(
surfaceFloor,
0.045,
0.045,
SURFACE_Z1 - SURFACE_Z0,
axisMat,
SURFACE_X1,
0.04,
0
);
const GRID_W = 19;
const GRID_H = 15;
const surfaceMaterial = material(0xffffff, {
vertexColors: true,
roughness: 0.9
});
const surfaceMesh = new THREE.InstancedMesh(
unitBox,
surfaceMaterial,
GRID_W * GRID_H
);
surfaceMesh.castShadow = true;
surfaceMesh.receiveShadow = true;
surfaceMesh.frustumCulled = false;
scene.add(surfaceMesh);
const dummy = new THREE.Object3D();
const lowColor = new THREE.Color(0x18d7a0);
const midColor = new THREE.Color(0x796cff);
const highColor = new THREE.Color(0xff3d7d);
function surfaceColor(loss) {
const t = Math.log1p(Math.min(loss, 30)) / Math.log1p(30);
const color = new THREE.Color();
if (t < 0.5) {
color.copy(lowColor).lerp(midColor, t * 2);
} else {
color.copy(midColor).lerp(highColor, (t - 0.5) * 2);
}
return color;
}
let instanceIndex = 0;
for (let iz = 0; iz < GRID_H; iz++) {
const b = map(iz, 0, GRID_H - 1, B_MIN, B_MAX);
for (let ix = 0; ix < GRID_W; ix++) {
const w = map(ix, 0, GRID_W - 1, W_MIN, W_MAX);
const loss = mseFor(w, b);
const height = lossHeight(loss);
const x = map(w, W_MIN, W_MAX, SURFACE_X0, SURFACE_X1);
const z = map(b, B_MIN, B_MAX, SURFACE_Z0, SURFACE_Z1);
dummy.position.set(x, height / 2, z);
dummy.scale.set(
(SURFACE_X1 - SURFACE_X0) / (GRID_W - 1) * 0.77,
height,
(SURFACE_Z1 - SURFACE_Z0) / (GRID_H - 1) * 0.70
);
dummy.updateMatrix();
surfaceMesh.setMatrixAt(instanceIndex, dummy.matrix);
surfaceMesh.setColorAt(instanceIndex, surfaceColor(loss));
instanceIndex++;
}
}
surfaceMesh.instanceMatrix.needsUpdate = true;
surfaceMesh.instanceColor.needsUpdate = true;
const surfaceTitle = textSprite("MSE LOSS SURFACE", "#b79cff", 3.0);
surfaceTitle.position.set(6.9, 4.35, -2.25);
scene.add(surfaceTitle);
const wLabel = textSprite("WEIGHT W", "#91a5c4", 1.7);
wLabel.position.set(9.45, 0.25, 0);
scene.add(wLabel);
const bLabel = textSprite("BIAS B", "#91a5c4", 1.7);
bLabel.position.set(4.18, 0.25, 2.95);
scene.add(bLabel);
// Visual bridge emphasizing that both views use the same parameter pair.
for (let x = -2.15; x <= 4.15; x += 0.42) {
box(scene, 0.13, 0.045, 0.045, material(0x36526f), x, 3.05, 0);
}
const bridgeLabel = textSprite("SAME (W, B)", "#91a5c4", 1.85);
bridgeLabel.position.set(1.0, 3.42, 0);
scene.add(bridgeLabel);
// ---------------------------------------------------------------------
// Optimization path, current marker, and blocky gradient arrow
// ---------------------------------------------------------------------
const MAX_PATH = 160;
const pathMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
vertexColors: true
});
const pathMesh = new THREE.InstancedMesh(
unitBox,
pathMaterial,
MAX_PATH
);
pathMesh.count = 0;
pathMesh.frustumCulled = false;
scene.add(pathMesh);
const marker = new THREE.Group();
const markerStemMat = material(0xffd166, {
transparent: true,
opacity: 0.3,
depthWrite: false
});
const markerMat = material(0xffd166, {
emissive: 0x704d00,
emissiveIntensity: 1.1
});
const markerStem = box(marker, 0.045, 1, 0.045, markerStemMat);
box(marker, 0.28, 0.28, 0.28, markerMat, 0, 0.14, 0);
box(marker, 0.15, 0.15, 0.15, material(0xfff4bf), 0, 0.34, 0);
scene.add(marker);
const gradientArrow = new THREE.Group();
const arrowMat = material(0xff9f43, {
emissive: 0x5b2600,
emissiveIntensity: 0.8
});
for (let i = 0; i < 6; i++) {
box(gradientArrow, 0.13, 0.085, 0.085, arrowMat, -0.48 + i * 0.14, 0, 0);
}
box(gradientArrow, 0.14, 0.11, 0.11, arrowMat, 0.41, 0, 0);
box(gradientArrow, 0.13, 0.10, 0.10, arrowMat, 0.34, 0, 0.12);
box(gradientArrow, 0.13, 0.10, 0.10, arrowMat, 0.34, 0, -0.12);
scene.add(gradientArrow);
const gradientLabel = textSprite("−∇MSE", "#ffad55", 1.25);
scene.add(gradientLabel);
let path = [];
let progress = 0;
let playing = true;
let learningRate = Number(document.querySelector("#lrSlider").value);
let stepsPerSecond = Number(document.querySelector("#speedSlider").value);
function rebuildPath() {
path = [];
let w = initial.w;
let b = initial.b;
for (let i = 0; i < MAX_PATH; i++) {
const loss = mseFor(w, b);
path.push({ w, b, loss });
const g = gradientFor(w, b);
const norm = Math.hypot(g.w, g.b);
if (norm < 0.002) break;
w = clamp(w - learningRate * g.w, W_MIN, W_MAX);
b = clamp(b - learningRate * g.b, B_MIN, B_MAX);
}
pathMesh.count = path.length;
for (let i = 0; i < path.length; i++) {
const p = path[i];
const x = map(p.w, W_MIN, W_MAX, SURFACE_X0, SURFACE_X1);
const z = map(p.b, B_MIN, B_MAX, SURFACE_Z0, SURFACE_Z1);
const y = lossHeight(p.loss) + 0.09;
dummy.position.set(x, y, z);
dummy.scale.set(0.11, 0.11, 0.11);
dummy.updateMatrix();
pathMesh.setMatrixAt(i, dummy.matrix);
}
pathMesh.instanceMatrix.needsUpdate = true;
progress = 0;
}
const traversedColor = new THREE.Color(0xffd166);
const futureColor = new THREE.Color(0x41536c);
function updatePathColors() {
const reached = Math.floor(progress);
for (let i = 0; i < path.length; i++) {
pathMesh.setColorAt(i, i <= reached ? traversedColor : futureColor);
}
if (pathMesh.instanceColor) pathMesh.instanceColor.needsUpdate = true;
}
// ---------------------------------------------------------------------
// UI and dynamic visualization
// ---------------------------------------------------------------------
const wValue = document.querySelector("#wValue");
const bValue = document.querySelector("#bValue");
const trainValue = document.querySelector("#trainValue");
const holdoutValue = document.querySelector("#holdoutValue");
const residualValue = document.querySelector("#residualValue");
const gradientValue = document.querySelector("#gradientValue");
const lossFill = document.querySelector("#lossFill");
const lossDelta = document.querySelector("#lossDelta");
const stepValue = document.querySelector("#stepValue");
const stateText = document.querySelector("#stateText");
const playButton = document.querySelector("#playButton");
const replayButton = document.querySelector("#replayButton");
const cameraButton = document.querySelector("#cameraButton");
const lrSlider = document.querySelector("#lrSlider");
const lrOutput = document.querySelector("#lrOutput");
const speedSlider = document.querySelector("#speedSlider");
const speedOutput = document.querySelector("#speedOutput");
const residualToggle = document.querySelector("#residualToggle");
function setPlaying(value) {
playing = value;
playButton.textContent = playing ? "PAUSE" : "PLAY";
}
function updateVisuals() {
if (!path.length) return;
const index = Math.min(Math.floor(progress), path.length - 1);
const nextIndex = Math.min(index + 1, path.length - 1);
const t = progress - index;
const p0 = path[index];
const p1 = path[nextIndex];
const w = THREE.MathUtils.lerp(p0.w, p1.w, t);
const b = THREE.MathUtils.lerp(p0.b, p1.b, t);
const trainLoss = mseFor(w, b);
const holdoutLoss = mseFor(w, b, holdout);
const gradient = gradientFor(w, b);
const gradientNorm = Math.hypot(gradient.w, gradient.b);
let meanAbs = 0;
for (const p of train) {
meanAbs += Math.abs(w * p.x + b - p.y);
}
meanAbs /= train.length;
// Update the regression line from the same (w, b) used by the surface.
const spacing = (fitEnd - fitStart) / (FIT_SAMPLES - 1);
for (let i = 0; i < FIT_SAMPLES; i++) {
const x = fitStart + i * spacing;
const predicted = w * x + b;
fitBlocks[i].position.set(
map(x, -3, 3, DATA_X0, DATA_X1),
0.48,
predicted
);
fitBlocks[i].scale.x = spacing * 1.28;
}
// Update each block residual connector.
for (let i = 0; i < train.length; i++) {
const p = train[i];
const predicted = w * p.x + b;
const actual = p.y;
const delta = predicted - actual;
const fullLength = Math.abs(delta);
const min = Math.min(predicted, actual);
const segmentLength = fullLength / 5;
for (let j = 0; j < 5; j++) {
const block = residualBlocks[i * 5 + j];
block.visible = fullLength > 0.035;
block.position.set(
map(p.x, -3, 3, DATA_X0, DATA_X1),
0.69,
min + segmentLength * (j + 0.5)
);
block.scale.z = Math.max(0.012, segmentLength * 0.58);
}
}
// Current point on the loss surface.
const surfaceX = map(w, W_MIN, W_MAX, SURFACE_X0, SURFACE_X1);
const surfaceZ = map(b, B_MIN, B_MAX, SURFACE_Z0, SURFACE_Z1);
const height = lossHeight(trainLoss);
marker.position.set(surfaceX, height, surfaceZ);
markerStem.scale.y = Math.max(0.01, height);
markerStem.position.y = -height / 2;
// Blocky arrow showing the current parameter-space descent direction.
const dirXRaw = -gradient.w;
const dirZRaw = -gradient.b;
const dirLength = Math.hypot(dirXRaw, dirZRaw) || 1;
const dirX = dirXRaw / dirLength;
const dirZ = dirZRaw / dirLength;
gradientArrow.position.set(surfaceX, height + 0.28, surfaceZ);
gradientArrow.rotation.y = -Math.atan2(dirZ, dirX);
gradientArrow.visible = gradientNorm > 0.001;
gradientLabel.position.set(
surfaceX + dirX * 1.05,
height + 0.55,
surfaceZ + dirZ * 1.05
);
gradientLabel.visible = gradientArrow.visible;
// Readouts.
wValue.textContent = w.toFixed(3);
bValue.textContent = b.toFixed(3);
trainValue.textContent = trainLoss.toFixed(3);
holdoutValue.textContent = holdoutLoss.toFixed(3);
residualValue.textContent = meanAbs.toFixed(3);
gradientValue.textContent = gradientNorm.toFixed(3);
stepValue.textContent = `STEP ${Math.round(progress)}`;
const initialLoss = path[0].loss;
const reduction = clamp((1 - trainLoss / initialLoss) * 100, 0, 100);
const signedDelta = trainLoss - initialLoss;
lossFill.style.width = `${reduction}%`;
lossDelta.textContent = `MSE Δ ${signedDelta >= 0 ? "+" : ""}${signedDelta.toFixed(3)}`;
if (progress >= path.length - 1) {
stateText.textContent = "TRACE ENDED · INSPECT METRICS";
} else if (playing) {
stateText.textContent = "DESCENDING −∇MSE";
} else {
stateText.textContent = "TRACE PAUSED";
}
updatePathColors();
}
playButton.addEventListener("click", () => {
if (progress >= path.length - 1) {
progress = 0;
setPlaying(true);
} else {
setPlaying(!playing);
}
});
replayButton.addEventListener("click", () => {
progress = 0;
setPlaying(true);
});
lrSlider.addEventListener("input", () => {
learningRate = Number(lrSlider.value);
lrOutput.textContent = learningRate.toFixed(3);
rebuildPath();
setPlaying(true);
});
speedSlider.addEventListener("input", () => {
stepsPerSecond = Number(speedSlider.value);
speedOutput.textContent = `${stepsPerSecond} steps/s`;
});
residualToggle.addEventListener("change", () => {
residualGroup.visible = residualToggle.checked;
});
// ---------------------------------------------------------------------
// Camera controls, implemented without Three.js addons
// ---------------------------------------------------------------------
function updateCamera() {
const { theta, phi, radius } = cameraState;
const sinPhi = Math.sin(phi);
camera.position.set(
cameraTarget.x + radius * sinPhi * Math.cos(theta),
cameraTarget.y + radius * Math.cos(phi),
cameraTarget.z + radius * sinPhi * Math.sin(theta)
);
camera.lookAt(cameraTarget);
camera.zoom = 20 / radius;
camera.updateProjectionMatrix();
}
function resetCamera() {
cameraState.theta = 0.72;
cameraState.phi = 0.94;
cameraState.radius = 20;
cameraTarget.set(0.55, 0.7, 0);
updateCamera();
}
cameraButton.addEventListener("click", resetCamera);
renderer.domElement.addEventListener("dblclick", resetCamera);
let dragging = false;
let lastX = 0;
let lastY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
lastX = event.clientX;
lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
document.body.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
cameraState.theta -= dx * 0.006;
cameraState.phi = clamp(cameraState.phi - dy * 0.005, 0.48, 1.34);
lastX = event.clientX;
lastY = event.clientY;
updateCamera();
});
function endDrag(event) {
dragging = false;
document.body.style.cursor = "default";
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = clamp(cameraState.radius + event.deltaY * 0.012, 12, 30);
updateCamera();
}, { passive: false });
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
// Preserve a readable minimum horizontal span on narrow displays.
const viewHeight = Math.max(11.8, 18.5 / aspect);
camera.left = -viewHeight * aspect / 2;
camera.right = viewHeight * aspect / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.6));
}
window.addEventListener("resize", resize);
// ---------------------------------------------------------------------
// Animation loop
// ---------------------------------------------------------------------
rebuildPath();
resize();
resetCamera();
updateVisuals();
let previousTime = performance.now();
function animate(now) {
const dt = Math.max(0, Math.min((now - previousTime) / 1000, 0.05));
previousTime = now;
if (playing && path.length > 1) {
progress += dt * stepsPerSecond;
if (progress >= path.length - 1) {
progress = path.length - 1;
setPlaying(false);
}
}
updateVisuals();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```