1. Analyze the Request:
* Goal: Develop a data imbalance remediation toolkit.
* Core Features: Ensure the artifact includes augmentation (text data, usually), reweighting, and synthetic resampling.
* Design Persona: Natural UI/UX artist, inspired by Biophilic Design and Wabi-Sabi.
* Design Principles: Organic shapes, earthy colors, texture/noise, serif fonts, fluid/soft motion, dappled light/slow media.
* Technical Stack: Tailwind CSS, Framer Motion (or GSAP), Three.js/Shaders, SVG Morphing.
* Constraint: "Code is executable for demonstration."
-
Conceptualization:
- A "toolkit" implies an interactive application, not just a library of functions. It needs a UI to select algorithms and visualize the results.
- Biophilic/Wabi-Sabi theme: This needs to feel organic, calm, and natural. Instead of a standard dashboard with sharp charts, use flowing blobs, paper textures, soft transitions, and a palette of terracotta, sage, cream, slate.
- Imbalance Problem: Usually involves a dataset (numerical/text) with uneven class distribution. I need to simulate a dataset within the browser for demonstration purposes. A simple scatter plot or bar chart showing class counts.
- Remediation Methods:
- Augmentation: Adding slight noise/transformations to existing minority class data points.
- Reweighting: Adjusting the learning weights (visualized by changing point opacity or size based on class weight).
- Synthetic Resampling (SMOTE): Generating synthetic points interpolating between neighbors.
-
Technical Architecture (Single HTML/JS file for executability):
- Styling: Tailwind CSS (via CDN) for layout and typography, but custom CSS for organic shapes, noise overlays, and specific textures.
- Graphics: HTML5 Canvas for the data visualization (performance for many points). Three.js is possible but maybe overkill for a 2D scatter plot; Canvas is sufficient and simpler for a single file, but I can use Canvas to simulate organic morphing or use Three.js for the background to satisfy the "Three.js/Shaders" requirement. Let's use Three.js for a background fluid effect (slow-moving smoke/water) to set the mood, and Canvas for the data scatter plot.
- Animation: GSAP (GreenSock) is excellent for UI transitions (slow, smooth) and might be easier for DOM manipulation than Framer Motion in a single React-less file, though Framer Motion is React typically. I'll use GSAP for UI transitions and perhaps custom requestAnimationFrame for the fluid background if not using Three.js shaders. Actually, the prompt specifically mentions Three.js/Shaders. I will include a Three.js background that simulates a slowly moving, ethereal fluid or smoke effect (vertex displacement or fragment shader) to fulfill the tech requirement and the aesthetic.
- Noise/Texture: CSS
::before element with a base64 noise image or a CSS gradient pattern for the "paper grain" effect.
- Fonts: A Google Font like 'Playfair Display' or 'Lora' for that serif elegance.
-
Detailed Implementation Steps:
-
Step 1: HTML Structure
- Container for the Three.js background (fixed, behind).
- Main content wrapper with paper texture (overlay).
- Header (title).
- Control Panel: Buttons/Inputs for "Dataset Size", "Imbalance Ratio", and Remediation buttons (Augment, Reweight, Synthetic).
- Visualization Container: A canvas for the 2D scatter plot.
- Stats Panel: Class distribution counts. Markers for algorithm descriptions.
-
Step 2: Design System (CSS)
- Colors:
bg-stone-100 (cream), text-stone-800 (dark grey).
- Buttons: Organic shapes using
rounded-[100px] or rounded-3xl. Background colors: sage-200, terracotta-200. Soft borders.
- Texture: Use an SVG filter or a base64 noise URL to add grain.
- Shadows: Large, soft diffuse shadows (
shadow-2xl, shadow-stone-200/50).
-
Step 3: Three.js Background (Shader Art)
- Create a plane.
- Use a fragment shader that generates a slow-moving, organic gradient/noise pattern (like oil in water) in muted earthy tones.
- Code: Vertex shader (simple), Fragment shader (GLSL noise, sin/cos time).
-
Step 4: Data Simulation Logic (JavaScript)
- Generate two classes centered around different points in the 2D space.
- Allow imbalance (e.g., 90% class 0, 10% class 1).
- Visualize points: Class 0 = Sage color, Class 1 = Terracotta color.
- Smooth rendering, not just pixels (maybe circular points with soft edges). Canvas
arc with shadows.
-
Step 5: Remediation Algorithms
- Augmentation: For minority class points, add small random Gaussian noise to position (simulate varied data). Animate newly added points appearing or expanding from original points.
- Reweighting: This is usually a model parameter, but we can visualize it. Reweight could change the size or opacity of points based on weight (minority points become larger). Or we could rebuild dataset weights but that's invisible. I'll make it change the point opacity or add a "halo" to minority points to show importance.
- Synthetic Resampling (SMOTE-ish): Pick two minority class neighbors, create new points along the line between them. Animate them sliding out.
-
Refining the Design (Wabi-Sabi/Tech constraints):
- Earthy Colors: Deep Clay (#C4815B), Sage (#A3B18A), Sand (#E5E5E5), Charcoal (#333333).
- Fonts:
font-serif.
- Motion: All transitions > 0.8s.
ease-out-expo or power2.out.
-
Drafting the Code (Mental or Scratchpad):
-
Libraries: Tailwind (CDN), Three.js (CDN), GSAP (CDN).
-
Noise Texture: I'll generate a simple noise texture using Canvas and use it as a background image pattern to keep it self-contained without external assets (except CDNs).
-
Three.js Shader:
varying vec2 vUv;
uniform float u_time;
void main() {
vec2 p = vUv;
float t = u_time * 0.1;
vec3 color = mix(vec3(0.78, 0.7, 0.65), vec3(0.6, 0.65, 0.55), sin(p.x*10.0 + t) * cos(p.y*10.0 + t));
gl_FragColor = vec4(color, 0.3);
}
Actually, let's make it more "smoke-like" with fbm or simple noise sums.
-
Canvas Interaction:
- Draw loop (requestAnimationFrame).
- Store points in array:
{x, y, class, isSynthetic, weight}.
- Update logic for amplification/sythetic.
-
Addressing the "Toolkit" Aspect:
- It's a demo of techniques. I'll frame it as a "Biophilic Data Balancer".
- User inputs: slider for imbalance.
- Buttons: "Sample New Data", "Apply Augmentation", "Synthetic Resampling (SMOTE)", "Class Reweighting".
- Since we can't run actual training, we visualize the effect on the data distribution.
-
Final Polish:
- Ensure all overlay textures align.
- Check contrast (suffusion of light).
- Ensure code is within a single HTML block.
- Add comments explaining the design decisions.
-
Self-Correction/Review:
- Constraint Check: Did I include Three.js? Yes, for background. Is it slow media? Yes, default durations long. Are colors earthy? Yes. Is noise/texture present? Yes (paper grain).
- Functionality: Does augmentation work? Yes, adds noise to existing points. Reweighting: visual emphasis. Synthetic: adds new points. Reset function to start over.
-
Writing the Output: (Proceeding to generate the HTML file).
- Note: Since I need to simulate "reweighting" visually, I will add a "Gravity" effect or simply make minority points larger/brighter to represent higher weight.
- SMOTE Implementation: Find k-nearest neighbors (k=1 or random) among minority class, pick one, generate a point at
p + factor*(neighbor_p - p). Ensure points stay within bounds.
-
Final Code Structure:
<html>
<head>: Tailwind CDN, Google Fonts (Lora), Styles (custom classes for shapes, noise).
<body>:
<canvas id="noise"> (for grain).
<div id=" Three-container"> (bg).
<main> (UI): Header, Controls, Canvas Overlay, Stats.
<script>: Three.js setup, Canvas logic, GSAP animations, Interaction logic.
Let's build it.
Here is a complete, self-contained HTML file implementing a Biophilic Data Imbalance Remediation Toolkit.
This tool combines a serene, organic UI with a functional demonstration of augmentation, reweighting, and synthetic resampling (SMOTE-like). It uses Three.js for a calming fluid background, GSAP for smooth motion, Tailwind CSS for layout, and HTML5 Canvas for the interactive data visualization.
How to use:
- Save the code below as an
.html file (e.g., biobalance.html).
- Open it in any modern web browser.
- Interact:
- Adjust the Imbalance Ratio to skew the dataset.
- Click Generate Data to create a new scatter plot.
- Use Augment, Reweight, and Synthesize to apply remediation techniques and watch the visualization evolve with earthy, slow animations.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Biophilic Data Balancer</title>
<!-- Google Fonts: Lora (Serif) for natural elegance -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lora:ital,wght@0,400;0,600;1,400&display=swap" rel="stylesheet">
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- GSAP for animations -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<!-- Three.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<!-- Configuration for Tailwind colors to match earthy palette -->
<script>
tailwind.config = {
theme: {
extend: {
colors: {
sage: {
DEFAULT: '#8DA399', // Muted green-grey
dark: '#6B8274',
light: '#B8C2BC'
},
terracotta: {
DEFAULT: '#C7815E',
dark: '#A6654A',
light: '#E6A68A'
},
cream: {
DEFAULT: '#F5F2EB',
dark: '#E8E5DD'
},
charcoal: {
DEFAULT: '#4A4A4A',
light: '#6B6B6B'
},
paper: '#FDFBF7' // Warm white
},
fontFamily: {
serif: ['"Lora"', 'serif'],
},
boxShadow: {
'soft': '0 10px 40px -10px rgba(0,0,0,0.1)',
'glow': '0 0 20px rgba(141, 163, 153, 0.3)'
}
}
}
}
</script>
<style>
/* General Body Styling */
body {
background-color: #FDFBF7;
color: #4A4A4A;
font-family: 'Lora', serif;
overflow-x: hidden;
margin: 0;
position: relative;
}
/* --- Textures --- */
/* Paper Grain Overlay using SVG filter */
.noise-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 50;
opacity: 0.4;
filter: url(#noiseFilter);
}
/* Soft vignette */
.vignette {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: radial-gradient(circle at center, transparent 0%, rgba(253, 251, 247, 0.2) 100%);
pointer-events: none;
z-index: 40;
}
/* Three.js Background Container */
#canvas-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 0;
opacity: 0.6; /* Let the background be subtle */
}
/* --- UI Components --- */
/* Organic Button Shape */
.btn-organic {
border-radius: 100px 40px 100px 40px / 40px 100px 40px 100px;
transition: all 0.6s cubic-bezier(0.25, 1, 0.5, 1);
border: 1px solid rgba(74, 74, 74, 0.1);
}
.btn-organic:hover {
border-radius: 40px 100px 40px 100px / 100px 40px 100px 40px;
box-shadow: 0 10px 25px rgba(141, 163, 153, 0.25);
transform: translateY(-2px);
}
.btn-organic:active {
transform: translateY(1px);
}
/* Glass/Panel effect */
.panel {
background: rgba(253, 251, 247, 0.75);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border: 1px solid rgba(255, 255, 255, 0.6);
box-shadow: 0 20px 60px -15px rgba(0,0,0,0.1);
}
/* Slider Styling */
input[type=range] {
-webkit-appearance: none;
width: 100%;
background: transparent;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
height: 24px;
width: 24px;
border-radius: 50%;
background: #C7815E;
cursor: pointer;
margin-top: -10px;
box-shadow: 0 2px 10px rgba(199, 129, 94, 0.4);
transition: transform 0.3s;
}
input[type=range]::-webkit-slider-thumb:hover {
transform: scale(1.1);
}
input[type=range]::-webkit-slider-runnable-track {
width: 100%;
height: 4px;
cursor: pointer;
background: #E8E5DD;
border-radius: 2px;
}
/* Canvas container */
#viz-container {
position: relative;
width: 100%;
height: 600px;
border-radius: 2rem;
overflow: hidden;
background: rgba(255,255,255,0.3);
box-shadow: inset 0 0 40px rgba(255,255,255,0.5);
}
/* Type styling */
h1, h2, h3 {
font-weight: 600;
letter-spacing: -0.02em;
}
.stats-badge {
font-variant-numeric: tabular-nums;
}
</style>
</head>
<body>
<!-- SVG Noise Filter (Hidden) -->
<svg style="display: none;">
<filter id='noiseFilter'>
<feTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='4' stitchTiles='stitch' result='noise' />
<feColorMatrix type='matrix' values='0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.4 0' in='noise' result='coloredNoise' />
<feBlend in='SourceGraphic' in2='coloredNoise' mode='multiply' />
</filter>
</svg>
<!-- Three.js Background -->
<div id="canvas-container"></div>
<!-- Noise Overlay -->
<div class="noise-overlay"></div>
<div class="vignette"></div>
<!-- Main Interface -->
<main class="relative z-10 container mx-auto px-6 py-12 max-w-6xl">
<!-- Header -->
<header class="text-center mb-16 animate-fade-in-up">
<h1 class="text-5xl md:text-6xl text-charcoal-DEFAULT mb-4">Biophilic Data Balancer</h1>
<p class="text-xl text-charcoal-light max-w-2xl mx-auto leading-relaxed">
A gentle toolkit for class imbalance remediation.
<br>
<span class="italic text-sage-dark">Augment</span>,
<span class="italic text-terracotta-dark">Reweight</span>, or
<span class="italic text-sage-dark">Synthesize</span> data with organic rhythm.
</p>
</header>
<!-- Dashboard Grid -->
<div class="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
<!-- Control Panel (Left) -->
<div class="lg:col-span-4 flex flex-col gap-8">
<!-- Configuration Card -->
<div class="panel p-8 rounded-[2.5rem] transform transition-transform duration-700 hover:scale-[1.01]">
<h2 class="text-2xl mb-6 text-charcoal-DEFAULT flex items-center gap-3">
<svg class="w-6 h-6 text-sage" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4"></path></svg>
Configuration
</h2>
<div class="mb-6">
<label class="block text-sm uppercase tracking-wider text-charcoal-light mb-3">Majority vs Minority Ratio</label>
<div class="flex justify-between text-sm mb-1 text-charcoal-light">
<span>Balanced (50/50)</span>
<span class="stats-badge">Extreme (95/5)</span>
</div>
<input type="range" id="imbalance-slider" min="50" max="95" value="90" step="5">
<div class="text-center mt-2 text-2xl font-serif text-terracotta-DEFAULT" id="imbalance-display">90% Majority</div>
</div>
<button id="btn-generate" class="btn-organic w-full py-4 bg-sage-light text-sage-dark font-bold text-lg shadow-soft block mb-4">
Generate Data
</button>
<p class="text-xs text-charcoal-light italic text-center">
Data consists of two clusters in 2D feature space.
</p>
</div>
<!-- Remediation Card -->
<div class="panel p-8 rounded-[2.5rem]">
<h2 class="text-2xl mb-6 text-charcoal-DEFAULT flex items-center gap-3">
<svg class="w-6 h-6 text-terracotta" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"></path></svg>
Remediation
</h2>
<div class="flex flex-col gap-3">
<button id="btn-augment" class="btn-organic py-3 px-6 bg-cream-dark text-charcoal-DEFAULT flex items-center justify-center gap-2 group">
<span>✨ Augment</span>
<span class="text-xs opacity-50 group-hover:opacity-100 transition-opacity">(Add noise)</span>
</button>
<button id="btn-reweight" class="btn-organic py-3 px-6 bg-cream-dark text-charcoal-DEFAULT flex items-center justify-center gap-2 group">
<span>⚖️ Reweight</span>
<span class="text-xs opacity-50 group-hover:opacity-100 transition-opacity">(Adjust importance)</span>
</button>
<button id="btn-synthesize" class="btn-organic py-3 px-6 bg-cream-dark text-charcoal-DEFAULT flex items-center justify-center gap-2 group">
<span>🌱 Synthesize</span>
<span class="text-xs opacity-50 group-hover:opacity-100 transition-opacity">(SMOTE-like)</span>
</button>
</div>
<div class="mt-6 pt-6 border-t border-charcoal-light/20">
<div class="grid grid-cols-2 gap-4 text-center">
<div class="bg-sage-light/30 p-3 rounded-2xl">
<div class="text-xs uppercase text-sage-dark">Class 0</div>
<div class="text-xl font-serif" id="count-0">0</div>
</div>
<div class="bg-terracotta-light/30 p-3 rounded-2xl">
<div class="text-xs uppercase text-terracotta-dark">Class 1</div>
<div class="text-xl font-serif" id="count-1">0</div>
</div>
</div>
</div>
</div>
</div>
<!-- Visualization Area (Right) -->
<div class="lg:col-span-8 flex flex-col gap-6">
<div class="panel p-2 md:p-6 rounded-[2.5rem] flex-grow flex flex-col">
<div class="flex justify-between items-center mb-4 px-2">
<h3 class="text-lg text-charcoal-light">Feature Space Visualization</h3>
<div id="status-msg" class="text-xs font-bold bg-sage-light text-sage-dark px-3 py-1 rounded-full opacity-0 transition-opacity duration-1000">
Synthetic Points Generated
</div>
</div>
<div id="viz-container" class="flex-grow relative">
<canvas id="data-canvas" class="absolute top-0 left-0 w-full h-full rounded-[2rem]"></canvas>
</div>
</div>
<!-- Educational description cards -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div class="p-4 bg-white/50 rounded-[2rem] border border-white/50 shadow-soft">
<h4 class="font-bold text-sage-dark mb-1">Augmentation</h4>
<p class="text-xs text-charcoal-light leading-relaxed">
Applying small, random perturbations to minority samples to increase dataset variance without collecting new data.
</p>
</div>
<div class="p-4 bg-white/50 rounded-[2rem] border border-white/50 shadow-soft">
<h4 class="font-bold text-terracotta-dark mb-1">Reweighting</h4>
<p class="text-xs text-charcoal-light leading-relaxed">
Inflating the loss contribution of the minority class, forcing the model to pay more attention during training.
</p>
</div>
<div class="p-4 bg-white/50 rounded-[2rem] border border-white/50 shadow-soft">
<h4 class="font-bold text-sage-dark mb-1">Synthetic Sampling</h4>
<p class="text-xs text-charcoal-light leading-relaxed">
Creating new synthetic data points by interpolating between existing minority class neighbors (SMOTE).
</p>
</div>
</div>
</div>
</div>
<footer class="mt-20 text-center text-charcoal-light text-sm pb-8">
<p>Designed with Biophilic Principles. Slow living code.</p>
</footer>
</main>
<script>
/**
* ------------------------------------------------------------------
* PART 1: Three.js Background (Ethereal Fluid Shader)
* ------------------------------------------------------------------
*/
const initThreeBackground = () => {
const container = document.getElementById('canvas-container');
const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
const renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
// Uniforms
const uniforms = {
u_time: { value: 0.0 },
u_resolution: { value: new THREE.Vector2(window.innerWidth, window.innerHeight) }
};
// Vertex Shader (Simple full-screen quad)
const vertexShader = `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4(position, 1.0);
}
`;
// Fragment Shader (Slow, organic noise)
const fragmentShader = `
uniform float u_time;
uniform vec2 u_resolution;
varying vec2 vUv;
// Simple 2D noise function
float random (in vec2 st) {
return fract(sin(dot(st.xy, vec2(12.9898,78.233)))*43758.5453123);
}
float noise (in vec2 st) {
vec2 i = floor(st);
vec2 f = fract(st);
float a = random(i);
float b = random(i + vec2(1.0, 0.0));
float c = random(i + vec2(0.0, 1.0));
float d = random(i + vec2(1.0, 1.0));
vec2 u = f*f*(3.0-2.0*f);
return mix(a, b, u.x) + (c - a)* u.y * (1.0 - u.x) + (d - b) * u.x * u.y;
}
void main() {
vec2 st = vUv * u_resolution.xy / u_resolution.y;
// Slowly moving coordinates
vec2 pos = st * 3.0;
pos.x += u_time * 0.1;
pos.y += u_time * 0.05;
// Layered noise (FBM)
float n = 0.0;
n += 0.5 * noise(pos);
pos *= 2.0;
n += 0.25 * noise(pos);
// Earthy colors mixing: Creamy beige to sage green
vec3 color1 = vec3(0.91, 0.90, 0.86); // Cream
vec3 color2 = vec3(0.55, 0.64, 0.60); // Sage
// Mix based on noise
vec3 finalColor = mix(color1, color2, n * 0.5 + 0.3);
// Add a very slow shift in tone
finalColor.r += 0.05 * sin(u_time * 0.1);
gl_FragColor = vec4(finalColor, 0.6); // 0.6 opacity for blending
}
`;
const geometry = new THREE.PlaneGeometry(2, 2);
const material = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: vertexShader,
fragmentShader: fragmentShader
});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
const animate = (time) => {
requestAnimationFrame(animate);
uniforms.u_time.value = time * 0.001;
renderer.render(scene, camera);
};
animate();
// Resize handling
window.addEventListener('resize', () => {
renderer.setSize(window.innerWidth, window.innerHeight);
uniforms.u_resolution.value.set(window.innerWidth, window.innerHeight);
});
};
/**
* ------------------------------------------------------------------
* PART 2: Data Simulation & Visualization Core
* ------------------------------------------------------------------
*/
class DataBalancer {
constructor(canvasId) {
this.canvas = document.getElementById(canvasId);
this.ctx = this.canvas.getContext('2d');
this.points = [];
this.majorityClass = 0;
this.minorityClass = 1;
// Visual settings
this.colors = {
0: '#8DA399', // Sage
0Highlight: '#A3B18A',
1: '#C7815E', // Terracotta
1Highlight: '#E6A68A',
synthetic: '#F2C9A0' // Lighter sand/cream for synthetic
};
this.animationProxies = []; // For GSAP
this.resize();
window.addEventListener('resize', () => this.resize());
}
resize() {
// Handle high DPI displays
const dpr = window.devicePixelRatio || 1;
const rect = this.canvas.parentElement.getBoundingClientRect();
this.canvas.width = rect.width * dpr;
this.canvas.height = rect.height * dpr;
this.ctx.scale(dpr, dpr);
this.width = rect.width;
this.height = rect.height;
this.render(); // Re-render immediately
}
// Generate Gaussian clusters (~ Normal distribution)
gaussianRandom(mean = 0, stdev = 1) {
const u = 1 - Math.random();
const v = Math.random();
const z = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.pi * v);
return z * stdev + mean;
}
generateData(ratio) {
// ratio: percentage of majority class (e.g., 90)
const totalPoints = 300; // Keep performant
const majorityCount = Math.floor((ratio / 100) * totalPoints);
const minorityCount = totalPoints - majorityCount;
this.points = [];
// Class 0 (Majority) center: Left, Sage
const cx0 = this.width * 0.3;
const cy0 = this.height * 0.5;
// Class 1 (Minority) center: Right, Terracotta
const cx1 = this.width * 0.7;
const cy1 = this.height * 0.5;
// Create Majority
for (let i = 0; i < majorityCount; i++) {
this.points.push({
x: cx0 + this.gaussianRandom(0, this.width * 0.12),
y: cy0 + this.gaussianRandom(0, this.height * 0.12),
class: 0,
originalClass: 0,
isSynthetic: false,
radius: this.randomRadius(),
weight: 1.0
});
}
// Create Minority
for (let i = 0; i < minorityCount; i++) {
this.points.push({
x: cx1 + this.gaussianRandom(0, this.width * 0.12),
y: cy1 + this.gaussianRandom(0, this.height * 0.12),
class: 1,
originalClass: 1,
isSynthetic: false,
radius: this.randomRadius(),
weight: 1.0
});
}
this.updateStats();
this.animateEnter();
}
randomRadius() {
return 4 + Math.random() * 4;
}
// --- Remediation Logic ---
augment() {
// For minority class (or all), add small noise to position
// Let's augment minority class only for visual impact
const minorityPoints = this.points.filter(p => p.originalClass === 1 && !p.isSynthetic);
if (minorityPoints.length === 0) return;
const newPoints = [];
minorityPoints.forEach(p => {
// Create an augmented copy
const aug = {
x: p.x + this.gaussianRandom(0, 10),
y: p.y + this.gaussianRandom(0, 10),
class: p.class,
originalClass: p.originalClass,
isSynthetic: true, // Mark visually different maybe? Or just rattle
radius: p.radius,
weight: 1.0,
alpha: 0
};
newPoints.push(aug);
});
this.addPoints(newPoints, 'augment');
}
reweight() {
// Visual effect: Minority original points become larger and more opaque
const minorityOriginals = this.points.filter(p => p.originalClass === 1 && !p.isSynthetic);
// GSAP animate properties
minorityOriginals.forEach(p => {
// "Weight" increases -> larger radius, brighter color
gsap.to(p, {
radius: 12,
duration: 1.5,
ease: "power2.out"
});
});
// Other class remains smaller
const others = this.points.filter(p => p.originalClass !== 1 || p.isSynthetic);
others.forEach(p => {
gsap.to(p, {
radius: 4,
duration: 1.5,
ease: "power2.out"
});
});
}
synthesizeSMOTE(k = 3) {
// Find minority class originals
const minorityPoints = this.points.filter(p => p.originalClass === 1 && !p.isSynthetic);
if (minorityPoints.length < 2) return;
const newPoints = [];
// Generate ~ 20% of minority count as synthetic
const numToGen = Math.floor(minorityPoints.length * 0.4);
for (let i = 0; i < numToGen; i++) {
// Pick random point a
const a = minorityPoints[Math.floor(Math.random() * minorityPoints.length)];
// Find nearest neighbor (simple random neighbor approximation for performance)
// In a real app, use KD-tree. Here random neighbor is "fast enough" for demo vibes.
const b = minorityPoints[Math.floor(Math.random() * minorityPoints.length)];
if (a === b) { i--; continue; }
// Interpolate: a + factor * (b - a)
const factor = 0.2 + Math.random() * 0.3; // Somewhere between 20% and 50% of the line
const sx = a.x + factor * (b.x - a.x);
const sy = a.y + factor * (b.y - a.y);
// Keep within bounds loosely
const clamp = (val, min, max) => Math.max(min, Math.min(max, val));
newPoints.push({
x: clamp(sx, 20, this.width - 20),
y: clamp(sy, 20, this.height - 20),
class: 1,
originalClass: 1,
isSynthetic: true,
radius: 0, // Start small for animation
weight: 0.8
});
}
this.addPoints(newPoints, 'synthesize');
}
addPoints(newPoints, type) {
this.points = [...this.points, ...newPoints];
this.updateStats();
if (type === 'synthesize') {
// Pop-in animation
newPoints.forEach(p => {
p.radius = 0;
gsap.to(p, {
radius: 4,
duration: 1.2,
ease: "elastic.out(1, 0.5)",
delay: Math.random() * 0.5
});
});
this.showStatus("Synthetic resampling applied");
} else if (type === 'augment') {
// Fade in / small expansion
newPoints.forEach(p => {
p.alpha = 0;
gsap.to(p, {
alpha: 0.6,
duration: 1.0,
onUpdate: () => this.render()
});
});
this.showStatus("Data augmentation applied");
}
}
animateEnter() {
// When new dataset generated, points start at random location and "settle" could do,
// but simpler: radius pulse
this.points.forEach(p => p.radius = 0);
const sorted = [...this.points]; // Copy reference
// Animate in batches by class for organic feel
setTimeout(() => {
sorted.forEach((p, i) => {
gsap.to(p, {
radius: this.randomRadius(),
delay: i * 0.002, // slight staggered wave
duration: 0.8,
ease: "back.out(1.7)"
});
});
}, 100);
}
updateStats() {
const c0 = this.points.filter(p => p.originalClass === 0).length;
const c1 = this.points.filter(p => p.originalClass === 1).length;
gsap.to(document.getElementById('count-0'), {
innerText: c0,
duration: 1,
snap: { innerText: 1 }
});
gsap.to(document.getElementById('count-1'), {
innerText: c1,
duration: 1,
snap: { innerText: 1 }
});
}
showStatus(text) {
const el = document.getElementById('status-msg');
el.innerText = text;
el.style.opacity = 1;
clearTimeout(this.statusTimer);
this.statusTimer = setTimeout(() => {
el.style.opacity = 0;
}, 2000);
}
// --- Main Render Loop ---
render() {
// Clear with a slight fade effect? No, clear completely.
this.ctx.clearRect(0, 0, this.width, this.height);
// Draw points
this.points.forEach(p => {
this.ctx.beginPath();
this.ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2);
// Determine color based on class and synthetic status
let color;
if (p.isSynthetic) {
color = this.colors.synthetic;
} else if (p.class === 0) {
// Check if reweighted (larger radius) to highlight subtly
color = p.radius > 6 ? this.colors.0Highlight : this.colors[0];
} else {
color = p.radius > 6 ? this.colors.1Highlight : this.colors[1];
}
this.ctx.fillStyle = color;
// Apply opacity if alpha property exists
if (p.alpha !== undefined) {
this.ctx.globalAlpha = p.alpha;
} else {
this.ctx.globalAlpha = 0.8;
}
this.ctx.fill();
// Soft glow for synthetic points
if (p.isSynthetic) {
this.ctx.beginPath();
this.ctx.arc(p.x, p.y, p.radius * 0.5, 0, Math.PI * 2);
this.ctx.fillStyle = 'rgba(255,255,255,0.3)';
this.ctx.globalAlpha = 0.6;
this.ctx.fill();
}
this.ctx.globalAlpha = 1.0;
});
}
}
/**
* ------------------------------------------------------------------
* PART 3: UI Integration & Event Listeners
* ------------------------------------------------------------------
*/
document.addEventListener('DOMContentLoaded', () => {
// 1. Init Three.js
initThreeBackground();
// 2. Init Data Visualizer
const balancer = new DataBalancer('data-canvas');
// Initial Data
balancer.generateData(90); // Default 90% majority
// 3. UI Elements
const slider = document.getElementById('imbalance-slider');
const display = document.getElementById('imbalance-display');
const btnGenerate = document.getElementById('btn-generate');
const btnAugment = document.getElementById('btn-augment');
const btnReweight = document.getElementById('btn-reweight');
const btnSynthesize = document.getElementById('btn-synthesize');
// 4. Event Handlers
// Slider Update
slider.addEventListener('input', (e) => {
const val = e.target.value;
display.innerText = `${val}% Majority`;
});
// Generate Button
btnGenerate.addEventListener('click', () => {
const ratio = parseInt(slider.value);
// Add a fading effect out/in
gsap.to(balancer.canvas, {
opacity: 0,
duration: 0.4,
onComplete: () => {
balancer.generateData(ratio);
gsap.to(balancer.canvas, { opacity: 1, duration: 0.8 });
}
});
});
// Augment
btnAugment.addEventListener('click', () => {
balancer.augment();
});
// Reweight
btnReweight.addEventListener('click', () => {
balancer.reweight();
});
// Synthesize
btnSynthesize.addEventListener('click', () => {
balancer.synthesizeSMOTE();
});
// 5. Continuous render loop (driven by GSAP ticker or requestAnimationFrame)
// Since we use GSAP for animations and modify point properties, we need to redraw canvas constantly
gsap.ticker.add(() => {
balancer.render();
});
});
</script>
</body>
</html>