Aii Cloud
Build a multi-file Vite-style React 18 + TypeScript app: "Neural Network…
Shared July 8, 2026 · Made with Aii · Read-only snapshot
User: Build a multi-file Vite-style React 18 + TypeScript app: "Neural Network Training & Verification Demo" — an interactive playground that trains a small binary classifier entirely in the browser with TensorFlow.js and verifies generalization on a held-out test set. No backend. Write every file complete — never truncate mid-file.
FILES (exactly these 17)
index.html (title "Neural Network Training & Verification Demo", 🧠 emoji favicon, #root, module script src/main.tsx)
package.json — deps: react ^18.3.1, react-dom ^18.3.1, @tensorflow/tfjs ^4.22.0, recharts ^2.15.0
src/main.tsx (createRoot + StrictMode), src/index.css, src/types.ts, src/App.tsx
src/utils/data.ts, src/utils/model.ts, src/utils/metrics.ts
src/components/Sidebar.tsx, DatasetPreview.tsx, NetworkArchitecture.tsx, TrainingCharts.tsx, DecisionBoundary.tsx, VerificationPanel.tsx, ManualPredictionPanel.tsx, ExplanationPanel.tsx
DESIGN SYSTEM (CSS variables, dark only)
bg #0a0c14, surface #11141f, surface-raised #171b2a, border #1e2436, text #e2e8f0, muted #94a3b8, accent blue #60a5fa, accent pink #f472b6, success #34d399, warning #fbbf24, danger #f87171, radius 8px. Font: Inter/system-ui. Class 0 = blue, Class 1 = pink everywhere. Numbers use tabular-nums.
LAYOUT
Centered header: h1 with blue→pink gradient text (background-clip), subtitle "Train a small neural network in your browser and verify whether it generalizes." Below: flex row = fixed 300px scrollable sidebar (left) + scrollable main column of stacked panels (cards: surface bg, 1px border, 8px radius, 1.5rem padding, each with h2 title + muted description line). Footer: "Built with React, TypeScript, TensorFlow.js, and Recharts. Runs entirely in the browser — no backend needed." Under 768px the sidebar stacks on top (max-height 45vh).
SIDEBAR — three card sections with uppercase mini-headings:
1. DATASET — Type select [Linear, Xor, Circle, Spiral] (default Linear); sliders with live value in label: Samples 100–2000 step 100 (default 500), Noise 0–1 shown as 0.1 steps (default 0.3), Train % 30–80 (default 60), Val % 5–40 (default 20, rest = test; keep ratios mutually consistent).
2. MODEL — sliders: Hidden Layers 1–5 (default 2), Neurons/Layer 2–64 step 2 (default 8); Activation select [relu, tanh, sigmoid] (default relu); Learning Rate 0.001–0.1 (default 0.01); Epochs 10–500 step 10 (default 100); Batch Size 4–256 step 4 (default 32).
3. TRAINING — four full-width buttons: "Generate Dataset" (blue), "Start Training" (green; label "Resume Training" when paused), "Pause Training" (amber; toggles to "Resume"), "Reset Model" (red). All config + Generate/Start/Reset disabled while training. Below: progress row "Progress N / M" + thin bar with blue→pink gradient fill; status badge "Training…" (green tint) / "Paused" (amber) / "Complete" (blue). Then a 2×2 live-metrics grid: Train Loss, Val Loss (4 decimals), Train Acc, Val Acc (0.1%). Then a 120px-tall mini recharts line chart of trainLoss (blue) vs valLoss (pink), no axes, with a tiny Train/Val legend.
MAIN PANELS, top to bottom:
1. Before any dataset exists, an empty-state card: big 🧠, "Ready to Train", copy telling the user to configure the sidebar then click Generate Dataset and Start Training, plus a hint recommending the default Linear dataset with 2 hidden layers of 8 neurons.
2. "Dataset Preview — <Type>" — square canvas scatter (dark #0f1117 bg, faint 10×10 grid, axis lines through origin). Points colored by class; split shown by size/opacity layering: train large+opaque (r6, 0.9), validation medium (r4.5, 0.55), test small+faint (r3, 0.25). In-canvas legends: top-left Train/Val/Test dot sizes, bottom-right "Class 0" blue / "Class 1" pink. Under the canvas a horizontal split bar with three labeled segments "Train X% / Val X% / Test X%" (blue / purple #a78bfa / gray tints).
3. "🔮 Network Architecture" — animated canvas (16:7, requestAnimationFrame): columns of glowing circular neurons = Input(2) labeled "Input (x,y)", each hidden layer labeled "Hidden n (count)", Output(1) labeled "Output (p)"; faint blue lines connect every neuron pair between adjacent layers; while training, small white pulse dots travel along connections and neuron glow pulses; "Epoch N" text top-right; layout recomputes when topology sliders change (ResizeObserver-safe). Legend chips below: Input / Hidden / Output / Signal pulse.
4. "Training Curves" (render once ≥2 epochs) — two side-by-side recharts cards: "Loss Curve" (trainLoss solid blue, valLoss dashed pink) and "Accuracy Curve" (trainAccuracy solid green, valAccuracy dashed amber, y domain 0–1 shown as %). Dark tooltips, legends, no dots. Below, when avg(valLoss − trainLoss) over the last 5 epochs > 0.1: amber warning banner "⚠ Validation loss is X.XXX higher than training loss — the model may be overfitting. Try reducing the number of epochs or hidden layers."
5. "Decision Boundary" (after training) — square canvas: 80×80 prediction-probability grid rendered as a semi-transparent heatmap interpolating blue (p≈0) → pink (p≈1); white dotted p=0.5 contour derived from the grid (marching-squares edge crossings drawn as small white dots); overlay validation points (solid, white ring) and training points (smaller, semi-transparent). Mind the y-flip: data y-up vs canvas y-down.
6. "Verification (Test Set)" — copy stressing the test set was never seen during training; "Verify on Test Set" button (disabled until a trained model exists and not while training). On click compute at threshold 0.5 and show metric cards: Test Accuracy (highlighted, large blue %), Test Loss (binary cross-entropy, 4 decimals), Precision, Recall, F1 (3 decimals); plus a 2×2 confusion-matrix table (Actual 0/1 × Predicted 0/1) with TN/TP green and FP/FN amber and a TN/FP/FN/TP legend.
7. "Manual Prediction" (after model exists) — X and Y number inputs + blue "Predict" button, and a crosshair-cursor scatter canvas of train+val points where clicking predicts that point: marker with colored glow + white ring at the location. Results as cards: Probability (4 decimals), Predicted Class (highlighted), Confidence % (= |p−0.5|×2). If |p−0.5| < 0.15 show amber "⚠ This point is near the decision boundary — the model is uncertain."
8. "How It Works" — accordion (one open at a time, ▸/▾ chevrons) with exactly these 8 items, each 3–6 sentences written for software engineers: "What is a Neural Network?", "What Does Training Mean?", "What is Loss?", "What Does Backpropagation Do?", "Why Use Validation Data?", "Why Must Test Data Be Held Out?", "What Does Overfitting Look Like?", "High Train Accuracy, Low Test Accuracy — Why Is That Bad?"
DATA GENERATORS (2D points, label 0|1, Fisher–Yates shuffled, then split train/val/test by the ratios)
linear: x,y uniform in ±4, label = y > x with noise-jittered boundary. xor: four Gaussian-ish clusters at (±1,±1), opposite corners share a class. circle: inner circle radius ~1.5 = class 1, outer ring radius ~4 = class 0. spiral: two interleaved spirals, ~1.5 turns, offset 180°. Normalize features by max-|coordinate| before feeding the model, and reuse the same normalization for grid/manual predictions.
MODEL & TRAINING (TensorFlow.js layers API)
Sequential: Dense(neuronsPerLayer, chosen activation, inputShape [2]) × hiddenLayers → Dense(1, sigmoid). Compile adam(learningRate), binaryCrossentropy, accuracy metric. Train epoch-by-epoch (model.fit with epochs:1, shuffle, validationData) in an async loop that yields to the UI each epoch and pushes {epoch, trainLoss, valLoss, trainAccuracy, valAccuracy} into state so every chart animates live; a pause flag polls without losing progress, reset stops and discards. Generate Dataset resets model + metrics. Dispose replaced models and all intermediate tensors.
If output budget runs short, drop in this order (everything above stays): sidebar mini loss chart → overfit banner → manual-prediction canvas (keep the X/Y form + result cards) → last 4 accordion items.
Aii:
User: Great first version. Now fix these defects and polish. Edit the existing files surgically — keep the layout, copy, design tokens, and accordion content exactly as they are. Write every edited file complete; never truncate.
A. FUNCTIONAL BUGS
1. src/App.tsx — Resume after Pause is broken: the training for-loop `return`s when pauseFlag is set, so clicking "Resume Training" only changes the badge — no loop is running and epochs never advance. Restructure to ONE persistent async loop: `for (epoch 1..epochs)` that on pause WAITS (`while (pauseRef.current && !stopRef.current) await sleep(100)`) instead of returning, then continues from the same epoch with the same model. Add a stopRef flag so Reset aborts the loop cleanly. Status flow: training → paused → training → complete.
2. src/components/DecisionBoundary.tsx — the heatmap renders once when the panel mounts (~epoch 1, near-random weights) and never again, because its useEffect deps ([model, dataset, maxAbs]) never change identity while the model trains in place. Pass currentEpoch as a prop and include it in the deps so the boundary redraws after every epoch and shows the final boundary when training completes.
3. Canvas cannot resolve CSS variables: `ctx.fillStyle = "var(--accent-blue)"` is silently ignored and the previous fillStyle is reused — input neurons are invisible when idle, the output neuron is gray, and the manual-prediction dot paints with a leftover gradient. Replace every `var(--…)` used inside canvas drawing with literal colors #60a5fa / #f472b6. Files: src/components/NetworkArchitecture.tsx, src/components/ManualPredictionPanel.tsx.
4. src/components/Sidebar.tsx — Reset Model is clickable during training; that disposes the model and tensors under the running loop and TensorFlow.js throws. Disable Reset while status === "training" (enabled when paused, complete, or idle with a model). Wire Reset to the stopRef from fix 1 so resetting from paused fully aborts the loop.
5. src/components/ManualPredictionPanel.tsx — the near-boundary warning checks `confidence < 0.15`, but confidence = |p−0.5|×2, so it only fires for p between 0.46 and 0.54. The rule is |probability − 0.5| < 0.15, i.e. `confidence < 0.30`. Fix the threshold.
B. VISUAL POLISH
6. src/components/NetworkArchitecture.tsx — neurons should be glowing blue spheres, not flat gray circles: radial-gradient body (light #94bcff center → #3b82f6 → #1e40af edge) with a soft blue radial glow behind every neuron at ALL times — subtle when idle, pulsing brighter during training. Hidden-layer neurons stay blue-family (remove the gray #94a3b8 fill). Hide the "Epoch N" text until epoch ≥ 1. Also stop setting canvas.width/height inside the requestAnimationFrame loop — size the canvas once and on resize only.
7. src/components/DecisionBoundary.tsx — raise the heatmap alpha from 0.35 to 0.55 so the blue→pink field reads clearly, and draw the white p=0.5 contour dots at interpolated EDGE crossings of each grid cell (t = (0.5 − v0)/(v1 − v0) along each sign-changing edge) instead of cell centers, so the dotted boundary is smooth instead of blocky.
8. src/components/Sidebar.tsx — show all four buttons stacked and always visible: Generate Dataset (blue), Start/Resume Training (green), Pause Training (amber, disabled unless training), Reset Model (red) — instead of swapping Start↔Pause in one slot. Move each slider's value into its label above a full-width slider ("Samples: 500", "Noise: 0.3", "Train: 60%", "Val: 20%", "Hidden Layers: 2", "Neurons / Layer: 8", "Learning Rate: 0.01", "Epochs: 100", "Batch Size: 32"), and display Learning Rate as 0.01, not 0.010.
9. src/components/TrainingCharts.tsx — the two-chart grid is hardcoded inline "1fr 1fr"; move it to a CSS class in src/index.css that collapses to one column under 768px.
10. src/components/DatasetPreview.tsx — restore the totals line in the description: "N total samples split into training, validation, and test sets. Blue = Class 0, Pink = Class 1. Larger dots are training data; smaller dots are test data."
11. src/utils/data.ts — XOR classes are inverted: the (1,1) and (−1,−1) clusters must be class 1, and (−1,1)/(1,−1) class 0.
ACCEPTANCE — confirm each in the code before finishing: Pause mid-run then Resume continues from the same epoch with the same weights; the decision boundary visibly sharpens as epochs advance and reflects the final model after completion; input/output neurons are visibly blue/pink while idle; Reset is disabled during training and aborts cleanly from paused; a manual prediction with p = 0.40 shows the near-boundary warning.
Aii:
User: issue: the button `Start Training` doesn't work right now.
Aii:
User: great! the `Start Training` button works! shall we further refine to compact the function space such as the panel `Dataset Preview`, `🔮 Network Architecture`, `Training Curves`, `Decision Boundary`, `Verification (Test Set)`, and `Manual Prediction`, etc. it sounds like those panel takes so big web page space. Let's improve the web page space efficiency.
Aii:
User: shall we further place two charts such as `Dataset Preview` and `🔮 Network Architecture` side by side on the same horizontal line?
Aii:
One AI in your browser, terminal, and editor — ask a follow-up below ↓ to continue this conversation free.
Shared from cloud.aiiware.com · Content is user-generated ·
Continues as your own copy — the shared files stay in your account, even if the original is unpublished · Free, 500 credits/day