diff --git a/ml-complete-all-topics/app.js b/ml-complete-all-topics/app.js new file mode 100644 index 0000000000000000000000000000000000000000..cb3c51ac454c796f7ab765f6c126e66724b76592 --- /dev/null +++ b/ml-complete-all-topics/app.js @@ -0,0 +1,2381 @@ +// Data +const data = { + linearRegression: [ + { experience: 1, salary: 39.764 }, + { experience: 2, salary: 48.900 }, + { experience: 3, salary: 56.978 }, + { experience: 4, salary: 68.290 }, + { experience: 5, salary: 77.867 }, + { experience: 6, salary: 85.022 } + ], + logistic: [ + { height: 150, label: 0, prob: 0.2 }, + { height: 160, label: 0, prob: 0.35 }, + { height: 170, label: 0, prob: 0.5 }, + { height: 180, label: 1, prob: 0.65 }, + { height: 190, label: 1, prob: 0.8 }, + { height: 200, label: 1, prob: 0.9 } + ], + svm: [ + { label: 'A', x1: 2, x2: 7, class: 1 }, + { label: 'B', x1: 3, x2: 8, class: 1 }, + { label: 'C', x1: 4, x2: 7, class: 1 }, + { label: 'D', x1: 6, x2: 2, class: -1 }, + { label: 'E', x1: 7, x2: 3, class: -1 }, + { label: 'F', x1: 8, x2: 2, class: -1 } + ], + knn: [ + { x: 1, y: 2, class: 'orange' }, + { x: 0.9, y: 1.7, class: 'orange' }, + { x: 1.5, y: 2.5, class: 'orange' }, + { x: 4, y: 5, class: 'yellow' }, + { x: 4.2, y: 4.8, class: 'yellow' }, + { x: 3.8, y: 5.2, class: 'yellow' } + ], + roc: [ + { id: 'A', true_label: 1, score: 0.95 }, + { id: 'B', true_label: 0, score: 0.70 }, + { id: 'C', true_label: 1, score: 0.60 }, + { id: 'D', true_label: 0, score: 0.40 }, + { id: 'E', true_label: 1, score: 0.20 } + ] +}; + +// State +let state = { + slope: 7.5, + intercept: 32, + learningRate: 0.1, + gdIterations: [], + testPoint: { x: 2, y: 1 }, + svm: { + w1: 1, + w2: 1, + b: -10, + C: 1, + kernel: 'linear', + kernelParam: 1, + training: { + w: [0, 0], + b: 0, + step: 0, + learningRate: 0.01, + isTraining: false + } + } +}; + +// Initialize collapsible sections +function initSections() { + const sections = document.querySelectorAll('.section'); + + sections.forEach(section => { + const header = section.querySelector('.section-header'); + const toggle = section.querySelector('.section-toggle'); + const body = section.querySelector('.section-body'); + + // Start with first section expanded + if (section.id === 'intro') { + body.classList.add('expanded'); + toggle.classList.remove('collapsed'); + } else { + toggle.classList.add('collapsed'); + } + + header.addEventListener('click', () => { + const isExpanded = body.classList.contains('expanded'); + + if (isExpanded) { + body.classList.remove('expanded'); + toggle.classList.add('collapsed'); + } else { + body.classList.add('expanded'); + toggle.classList.remove('collapsed'); + + // Initialize visualizations when section opens + if (section.id === 'linear-regression') initLinearRegression(); + if (section.id === 'gradient-descent') initGradientDescent(); + if (section.id === 'logistic-regression') initLogistic(); + if (section.id === 'svm') initSVM(); + if (section.id === 'knn') initKNN(); + if (section.id === 'model-evaluation') initModelEvaluation(); + if (section.id === 'regularization') initRegularization(); + if (section.id === 'bias-variance') initBiasVariance(); + if (section.id === 'cross-validation') initCrossValidation(); + if (section.id === 'preprocessing') initPreprocessing(); + if (section.id === 'loss-functions') initLossFunctions(); + } + }); + }); +} + +// Smooth scroll for TOC links +function initTOCLinks() { + const links = document.querySelectorAll('.toc-link'); + + links.forEach(link => { + link.addEventListener('click', (e) => { + e.preventDefault(); + const targetId = link.getAttribute('href').substring(1); + const target = document.getElementById(targetId); + + if (target) { + // Remove active from all links + links.forEach(l => l.classList.remove('active')); + link.classList.add('active'); + + // Scroll to target + target.scrollIntoView({ behavior: 'smooth', block: 'start' }); + + // Expand the section + const toggle = target.querySelector('.section-toggle'); + const body = target.querySelector('.section-body'); + body.classList.add('expanded'); + toggle.classList.remove('collapsed'); + } + }); + }); + + // Update active link on scroll + let ticking = false; + window.addEventListener('scroll', () => { + if (!ticking) { + window.requestAnimationFrame(() => { + updateActiveLink(); + ticking = false; + }); + ticking = true; + } + }); +} + +function updateActiveLink() { + const sections = document.querySelectorAll('.section'); + const scrollPos = window.scrollY + 100; + + sections.forEach(section => { + const top = section.offsetTop; + const height = section.offsetHeight; + const id = section.getAttribute('id'); + + if (scrollPos >= top && scrollPos < top + height) { + document.querySelectorAll('.toc-link').forEach(link => { + link.classList.remove('active'); + if (link.getAttribute('href') === '#' + id) { + link.classList.add('active'); + } + }); + } + }); +} + +// Linear Regression Visualization +function initLinearRegression() { + const canvas = document.getElementById('lr-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + + const slopeSlider = document.getElementById('slope-slider'); + const interceptSlider = document.getElementById('intercept-slider'); + const slopeVal = document.getElementById('slope-val'); + const interceptVal = document.getElementById('intercept-val'); + + if (slopeSlider) { + slopeSlider.addEventListener('input', (e) => { + state.slope = parseFloat(e.target.value); + slopeVal.textContent = state.slope.toFixed(1); + drawLinearRegression(); + }); + } + + if (interceptSlider) { + interceptSlider.addEventListener('input', (e) => { + state.intercept = parseFloat(e.target.value); + interceptVal.textContent = state.intercept.toFixed(1); + drawLinearRegression(); + }); + } + + drawLinearRegression(); +} + +function drawLinearRegression() { + const canvas = document.getElementById('lr-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 400; + + ctx.clearRect(0, 0, width, height); + + const padding = 60; + const chartWidth = width - 2 * padding; + const chartHeight = height - 2 * padding; + + const xMin = 0, xMax = 7; + const yMin = 0, yMax = 100; + + // Draw axes + ctx.strokeStyle = '#2a3544'; + ctx.lineWidth = 2; + ctx.beginPath(); + ctx.moveTo(padding, padding); + ctx.lineTo(padding, height - padding); + ctx.lineTo(width - padding, height - padding); + ctx.stroke(); + + // Grid + ctx.strokeStyle = 'rgba(42, 53, 68, 0.3)'; + ctx.lineWidth = 1; + for (let i = 0; i <= 5; i++) { + const x = padding + (chartWidth / 5) * i; + ctx.beginPath(); + ctx.moveTo(x, padding); + ctx.lineTo(x, height - padding); + ctx.stroke(); + + const y = height - padding - (chartHeight / 5) * i; + ctx.beginPath(); + ctx.moveTo(padding, y); + ctx.lineTo(width - padding, y); + ctx.stroke(); + } + + const scaleX = (x) => padding + ((x - xMin) / (xMax - xMin)) * chartWidth; + const scaleY = (y) => height - padding - ((y - yMin) / (yMax - yMin)) * chartHeight; + + // Draw data points + ctx.fillStyle = '#6aa9ff'; + data.linearRegression.forEach(point => { + const x = scaleX(point.experience); + const y = scaleY(point.salary); + ctx.beginPath(); + ctx.arc(x, y, 6, 0, 2 * Math.PI); + ctx.fill(); + }); + + // Draw regression line + ctx.strokeStyle = '#ff8c6a'; + ctx.lineWidth = 3; + ctx.beginPath(); + const y1 = state.slope * xMin + state.intercept; + const y2 = state.slope * xMax + state.intercept; + ctx.moveTo(scaleX(xMin), scaleY(y1)); + ctx.lineTo(scaleX(xMax), scaleY(y2)); + ctx.stroke(); + + // Labels + ctx.fillStyle = '#a9b4c2'; + ctx.font = '12px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText('Experience (years)', width / 2, height - 20); + ctx.save(); + ctx.translate(20, height / 2); + ctx.rotate(-Math.PI / 2); + ctx.fillText('Salary ($k)', 0, 0); + ctx.restore(); + + // Calculate MSE + let mse = 0; + data.linearRegression.forEach(point => { + const predicted = state.slope * point.experience + state.intercept; + const error = point.salary - predicted; + mse += error * error; + }); + mse /= data.linearRegression.length; + + // Display MSE + ctx.fillStyle = '#7ef0d4'; + ctx.font = '14px sans-serif'; + ctx.textAlign = 'right'; + ctx.fillText(`MSE: ${mse.toFixed(2)}`, width - padding, padding + 20); +} + +// Gradient Descent Visualization +function initGradientDescent() { + const canvas = document.getElementById('gd-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + + const runBtn = document.getElementById('run-gd'); + const resetBtn = document.getElementById('reset-gd'); + const lrSlider = document.getElementById('lr-slider'); + const lrVal = document.getElementById('lr-val'); + + if (lrSlider) { + lrSlider.addEventListener('input', (e) => { + state.learningRate = parseFloat(e.target.value); + lrVal.textContent = state.learningRate.toFixed(2); + }); + } + + if (runBtn) { + runBtn.addEventListener('click', runGradientDescent); + } + + if (resetBtn) { + resetBtn.addEventListener('click', () => { + state.gdIterations = []; + drawGradientDescent(); + }); + } + + drawGradientDescent(); +} + +function runGradientDescent() { + state.gdIterations = []; + let m = 0, c = 20; // Start with poor values + const alpha = state.learningRate; + const iterations = 50; + + for (let i = 0; i < iterations; i++) { + let dm = 0, dc = 0; + const n = data.linearRegression.length; + + // Calculate gradients + data.linearRegression.forEach(point => { + const predicted = m * point.experience + c; + const error = predicted - point.salary; + dm += (2 / n) * error * point.experience; + dc += (2 / n) * error; + }); + + // Update parameters + m -= alpha * dm; + c -= alpha * dc; + + // Calculate loss + let loss = 0; + data.linearRegression.forEach(point => { + const predicted = m * point.experience + c; + const error = point.salary - predicted; + loss += error * error; + }); + loss /= n; + + state.gdIterations.push({ m, c, loss }); + } + + animateGradientDescent(); +} + +function animateGradientDescent() { + let step = 0; + const interval = setInterval(() => { + if (step >= state.gdIterations.length) { + clearInterval(interval); + return; + } + + const iteration = state.gdIterations[step]; + state.slope = iteration.m; + state.intercept = iteration.c; + + // Update linear regression chart + drawLinearRegression(); + drawGradientDescent(step); + + step++; + }, 50); +} + +function drawGradientDescent(currentStep = -1) { + const canvas = document.getElementById('gd-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 400; + + ctx.clearRect(0, 0, width, height); + + if (state.gdIterations.length === 0) { + ctx.fillStyle = '#a9b4c2'; + ctx.font = '16px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText('Click "Run Gradient Descent" to see the algorithm in action', width / 2, height / 2); + return; + } + + const padding = 60; + const chartWidth = width - 2 * padding; + const chartHeight = height - 2 * padding; + + const maxLoss = Math.max(...state.gdIterations.map(i => i.loss)); + const minLoss = Math.min(...state.gdIterations.map(i => i.loss)); + + // Draw axes + ctx.strokeStyle = '#2a3544'; + ctx.lineWidth = 2; + ctx.beginPath(); + ctx.moveTo(padding, padding); + ctx.lineTo(padding, height - padding); + ctx.lineTo(width - padding, height - padding); + ctx.stroke(); + + const scaleX = (i) => padding + (i / (state.gdIterations.length - 1)) * chartWidth; + const scaleY = (loss) => height - padding - ((loss - minLoss) / (maxLoss - minLoss)) * chartHeight; + + // Draw loss curve + ctx.strokeStyle = '#7ef0d4'; + ctx.lineWidth = 2; + ctx.beginPath(); + state.gdIterations.forEach((iter, i) => { + const x = scaleX(i); + const y = scaleY(iter.loss); + if (i === 0) { + ctx.moveTo(x, y); + } else { + ctx.lineTo(x, y); + } + }); + ctx.stroke(); + + // Highlight current step + if (currentStep >= 0 && currentStep < state.gdIterations.length) { + const iter = state.gdIterations[currentStep]; + const x = scaleX(currentStep); + const y = scaleY(iter.loss); + + ctx.fillStyle = '#ff8c6a'; + ctx.beginPath(); + ctx.arc(x, y, 6, 0, 2 * Math.PI); + ctx.fill(); + + // Display current values + ctx.fillStyle = '#e8eef6'; + ctx.font = '12px sans-serif'; + ctx.textAlign = 'left'; + ctx.fillText(`Step: ${currentStep + 1}`, padding + 10, padding + 20); + ctx.fillText(`Loss: ${iter.loss.toFixed(2)}`, padding + 10, padding + 40); + } + + // Labels + ctx.fillStyle = '#a9b4c2'; + ctx.font = '12px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText('Iterations', width / 2, height - 20); + ctx.save(); + ctx.translate(20, height / 2); + ctx.rotate(-Math.PI / 2); + ctx.fillText('Loss (MSE)', 0, 0); + ctx.restore(); +} + +// Initialize everything when DOM is ready +function init() { + initSections(); + initTOCLinks(); + + // Initialize first section visualizations + setTimeout(() => { + initLinearRegression(); + }, 100); +} + +if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', init); +} else { + init(); +} + +// SVM Visualizations +function initSVM() { + initSVMBasic(); + initSVMMargin(); + initSVMCParameter(); + initSVMTraining(); + initSVMKernel(); +} + +function initSVMBasic() { + const canvas = document.getElementById('svm-basic-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + + const w1Slider = document.getElementById('svm-w1-slider'); + const w2Slider = document.getElementById('svm-w2-slider'); + const bSlider = document.getElementById('svm-b-slider'); + + if (w1Slider) { + w1Slider.addEventListener('input', (e) => { + state.svm.w1 = parseFloat(e.target.value); + document.getElementById('svm-w1-val').textContent = state.svm.w1.toFixed(1); + drawSVMBasic(); + }); + } + + if (w2Slider) { + w2Slider.addEventListener('input', (e) => { + state.svm.w2 = parseFloat(e.target.value); + document.getElementById('svm-w2-val').textContent = state.svm.w2.toFixed(1); + drawSVMBasic(); + }); + } + + if (bSlider) { + bSlider.addEventListener('input', (e) => { + state.svm.b = parseFloat(e.target.value); + document.getElementById('svm-b-val').textContent = state.svm.b.toFixed(1); + drawSVMBasic(); + }); + } + + drawSVMBasic(); +} + +function drawSVMBasic() { + const canvas = document.getElementById('svm-basic-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 450; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const padding = 60; + const chartWidth = width - 2 * padding; + const chartHeight = height - 2 * padding; + + const xMin = 0, xMax = 10; + const yMin = 0, yMax = 10; + + const scaleX = (x) => padding + ((x - xMin) / (xMax - xMin)) * chartWidth; + const scaleY = (y) => height - padding - ((y - yMin) / (yMax - yMin)) * chartHeight; + + // Draw grid + ctx.strokeStyle = 'rgba(42, 53, 68, 0.5)'; + ctx.lineWidth = 1; + for (let i = 0; i <= 10; i++) { + const x = scaleX(i); + const y = scaleY(i); + + ctx.beginPath(); + ctx.moveTo(x, padding); + ctx.lineTo(x, height - padding); + ctx.stroke(); + + ctx.beginPath(); + ctx.moveTo(padding, y); + ctx.lineTo(width - padding, y); + ctx.stroke(); + } + + // Draw axes + ctx.strokeStyle = '#2a3544'; + ctx.lineWidth = 2; + ctx.beginPath(); + ctx.moveTo(padding, padding); + ctx.lineTo(padding, height - padding); + ctx.lineTo(width - padding, height - padding); + ctx.stroke(); + + // Draw decision boundary + const w1 = state.svm.w1; + const w2 = state.svm.w2; + const b = state.svm.b; + + if (Math.abs(w2) > 0.01) { + ctx.strokeStyle = '#6aa9ff'; + ctx.lineWidth = 3; + ctx.beginPath(); + + const x1 = xMin; + const y1 = -(w1 * x1 + b) / w2; + const x2 = xMax; + const y2 = -(w1 * x2 + b) / w2; + + ctx.moveTo(scaleX(x1), scaleY(y1)); + ctx.lineTo(scaleX(x2), scaleY(y2)); + ctx.stroke(); + } + + // Draw data points + data.svm.forEach(point => { + const x = scaleX(point.x1); + const y = scaleY(point.x2); + const score = w1 * point.x1 + w2 * point.x2 + b; + + ctx.fillStyle = point.class === 1 ? '#7ef0d4' : '#ff8c6a'; + ctx.beginPath(); + ctx.arc(x, y, 8, 0, 2 * Math.PI); + ctx.fill(); + + ctx.strokeStyle = '#1a2332'; + ctx.lineWidth = 2; + ctx.stroke(); + + // Label + ctx.fillStyle = '#e8eef6'; + ctx.font = 'bold 12px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText(point.label, x, y - 15); + + // Score + ctx.font = '11px monospace'; + ctx.fillStyle = '#a9b4c2'; + ctx.fillText(score.toFixed(2), x, y + 20); + }); + + // Labels + ctx.fillStyle = '#a9b4c2'; + ctx.font = '13px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText('X₁', width / 2, height - 20); + ctx.save(); + ctx.translate(20, height / 2); + ctx.rotate(-Math.PI / 2); + ctx.fillText('X₂', 0, 0); + ctx.restore(); + + // Equation + ctx.fillStyle = '#7ef0d4'; + ctx.font = '14px monospace'; + ctx.textAlign = 'left'; + ctx.fillText(`w·x + b = ${w1.toFixed(1)}x₁ + ${w2.toFixed(1)}x₂ + ${b.toFixed(1)}`, padding + 10, padding + 25); +} + +function initSVMMargin() { + const canvas = document.getElementById('svm-margin-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + drawSVMMargin(); +} + +function drawSVMMargin() { + const canvas = document.getElementById('svm-margin-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 450; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const padding = 60; + const chartWidth = width - 2 * padding; + const chartHeight = height - 2 * padding; + + const xMin = 0, xMax = 10; + const yMin = 0, yMax = 10; + + const scaleX = (x) => padding + ((x - xMin) / (xMax - xMin)) * chartWidth; + const scaleY = (y) => height - padding - ((y - yMin) / (yMax - yMin)) * chartHeight; + + // Use good values for visualization + const w1 = 0.5, w2 = -1, b = 5.5; + + // Draw margin lines + if (Math.abs(w2) > 0.01) { + // Positive margin line + ctx.strokeStyle = '#ff8c6a'; + ctx.lineWidth = 2; + ctx.setLineDash([5, 5]); + ctx.beginPath(); + let x1 = xMin, y1 = -(w1 * x1 + b - 1) / w2; + let x2 = xMax, y2 = -(w1 * x2 + b - 1) / w2; + ctx.moveTo(scaleX(x1), scaleY(y1)); + ctx.lineTo(scaleX(x2), scaleY(y2)); + ctx.stroke(); + + // Negative margin line + ctx.beginPath(); + y1 = -(w1 * x1 + b + 1) / w2; + y2 = -(w1 * x2 + b + 1) / w2; + ctx.moveTo(scaleX(x1), scaleY(y1)); + ctx.lineTo(scaleX(x2), scaleY(y2)); + ctx.stroke(); + + // Decision boundary + ctx.setLineDash([]); + ctx.strokeStyle = '#6aa9ff'; + ctx.lineWidth = 3; + ctx.beginPath(); + y1 = -(w1 * x1 + b) / w2; + y2 = -(w1 * x2 + b) / w2; + ctx.moveTo(scaleX(x1), scaleY(y1)); + ctx.lineTo(scaleX(x2), scaleY(y2)); + ctx.stroke(); + } + + // Draw data points + data.svm.forEach(point => { + const x = scaleX(point.x1); + const y = scaleY(point.x2); + const score = w1 * point.x1 + w2 * point.x2 + b; + const isSupport = Math.abs(Math.abs(score) - 1) < 0.5; + + ctx.fillStyle = point.class === 1 ? '#7ef0d4' : '#ff8c6a'; + ctx.beginPath(); + ctx.arc(x, y, 8, 0, 2 * Math.PI); + ctx.fill(); + + // Highlight support vectors + if (isSupport) { + ctx.strokeStyle = '#7ef0d4'; + ctx.lineWidth = 3; + ctx.beginPath(); + ctx.arc(x, y, 14, 0, 2 * Math.PI); + ctx.stroke(); + } + + ctx.fillStyle = '#e8eef6'; + ctx.font = 'bold 12px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText(point.label, x, y - 20); + }); + + // Show margin width + const wNorm = Math.sqrt(w1 * w1 + w2 * w2); + const marginWidth = 2 / wNorm; + + ctx.fillStyle = '#7ef0d4'; + ctx.font = '16px sans-serif'; + ctx.textAlign = 'left'; + ctx.fillText(`Margin Width: ${marginWidth.toFixed(2)}`, padding + 10, padding + 25); + ctx.fillText('Support vectors highlighted with cyan ring', padding + 10, padding + 50); +} + +function initSVMCParameter() { + const canvas = document.getElementById('svm-c-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + + const cSlider = document.getElementById('svm-c-slider'); + if (cSlider) { + cSlider.addEventListener('input', (e) => { + const val = parseFloat(e.target.value); + state.svm.C = Math.pow(10, val); + document.getElementById('svm-c-val').textContent = state.svm.C.toFixed(state.svm.C < 10 ? 1 : 0); + drawSVMCParameter(); + }); + } + + drawSVMCParameter(); +} + +function drawSVMCParameter() { + const canvas = document.getElementById('svm-c-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 450; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const padding = 60; + const chartWidth = width - 2 * padding; + const chartHeight = height - 2 * padding; + + const xMin = 0, xMax = 10; + const yMin = 0, yMax = 10; + + const scaleX = (x) => padding + ((x - xMin) / (xMax - xMin)) * chartWidth; + const scaleY = (y) => height - padding - ((y - yMin) / (yMax - yMin)) * chartHeight; + + // Adjust margin based on C + const C = state.svm.C; + const marginFactor = Math.min(1, 10 / C); + const w1 = 0.5 * marginFactor, w2 = -1 * marginFactor, b = 5.5; + + // Calculate violations + let violations = 0; + data.svm.forEach(point => { + const score = w1 * point.x1 + w2 * point.x2 + b; + if (point.class * score < 1) violations++; + }); + + // Draw margin lines + if (Math.abs(w2) > 0.01) { + ctx.strokeStyle = '#ff8c6a'; + ctx.lineWidth = 2; + ctx.setLineDash([5, 5]); + ctx.beginPath(); + let x1 = xMin, y1 = -(w1 * x1 + b - 1) / w2; + let x2 = xMax, y2 = -(w1 * x2 + b - 1) / w2; + ctx.moveTo(scaleX(x1), scaleY(y1)); + ctx.lineTo(scaleX(x2), scaleY(y2)); + ctx.stroke(); + + ctx.beginPath(); + y1 = -(w1 * x1 + b + 1) / w2; + y2 = -(w1 * x2 + b + 1) / w2; + ctx.moveTo(scaleX(x1), scaleY(y1)); + ctx.lineTo(scaleX(x2), scaleY(y2)); + ctx.stroke(); + + ctx.setLineDash([]); + ctx.strokeStyle = '#6aa9ff'; + ctx.lineWidth = 3; + ctx.beginPath(); + y1 = -(w1 * x1 + b) / w2; + y2 = -(w1 * x2 + b) / w2; + ctx.moveTo(scaleX(x1), scaleY(y1)); + ctx.lineTo(scaleX(x2), scaleY(y2)); + ctx.stroke(); + } + + // Draw points + data.svm.forEach(point => { + const x = scaleX(point.x1); + const y = scaleY(point.x2); + const score = w1 * point.x1 + w2 * point.x2 + b; + const violates = point.class * score < 1; + + ctx.fillStyle = point.class === 1 ? '#7ef0d4' : '#ff8c6a'; + ctx.beginPath(); + ctx.arc(x, y, 8, 0, 2 * Math.PI); + ctx.fill(); + + if (violates) { + ctx.strokeStyle = '#ff4444'; + ctx.lineWidth = 3; + ctx.stroke(); + } + }); + + // Update info + const wNorm = Math.sqrt(w1 * w1 + w2 * w2); + const marginWidth = 2 / wNorm; + document.getElementById('margin-width').textContent = marginWidth.toFixed(2); + document.getElementById('violations-count').textContent = violations; +} + +function initSVMTraining() { + const canvas = document.getElementById('svm-train-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + + const trainBtn = document.getElementById('svm-train-btn'); + const stepBtn = document.getElementById('svm-step-btn'); + const resetBtn = document.getElementById('svm-reset-btn'); + + if (trainBtn) { + trainBtn.addEventListener('click', () => { + state.svm.training.step = 0; + state.svm.training.w = [0, 0]; + state.svm.training.b = 0; + state.svm.training.isTraining = true; + autoTrain(); + }); + } + + if (stepBtn) { + stepBtn.addEventListener('click', () => { + if (state.svm.training.step < data.svm.length) { + trainStep(); + } + }); + } + + if (resetBtn) { + resetBtn.addEventListener('click', () => { + state.svm.training.step = 0; + state.svm.training.w = [0, 0]; + state.svm.training.b = 0; + state.svm.training.isTraining = false; + updateTrainingInfo(); + drawSVMTraining(); + }); + } + + drawSVMTraining(); +} + +function trainStep() { + if (state.svm.training.step >= data.svm.length) return; + + const point = data.svm[state.svm.training.step]; + const w = state.svm.training.w; + const b = state.svm.training.b; + const lr = state.svm.training.learningRate; + const C = 1; + + const score = w[0] * point.x1 + w[1] * point.x2 + b; + const violation = point.class * score < 1; + + if (violation) { + w[0] = w[0] - lr * (w[0] - C * point.class * point.x1); + w[1] = w[1] - lr * (w[1] - C * point.class * point.x2); + state.svm.training.b = b + lr * C * point.class; + } else { + w[0] = w[0] - lr * w[0]; + w[1] = w[1] - lr * w[1]; + } + + state.svm.training.step++; + updateTrainingInfo(point, violation); + drawSVMTraining(); +} + +function autoTrain() { + if (!state.svm.training.isTraining) return; + + if (state.svm.training.step < data.svm.length) { + trainStep(); + setTimeout(autoTrain, 800); + } else { + state.svm.training.isTraining = false; + } +} + +function updateTrainingInfo(point = null, violation = null) { + document.getElementById('train-step').textContent = state.svm.training.step; + document.getElementById('train-point').textContent = point ? `${point.label} (${point.x1}, ${point.x2})` : '-'; + document.getElementById('train-w').textContent = `${state.svm.training.w[0].toFixed(2)}, ${state.svm.training.w[1].toFixed(2)}`; + document.getElementById('train-b').textContent = state.svm.training.b.toFixed(2); + document.getElementById('train-violation').textContent = violation === null ? '-' : (violation ? 'YES ❌' : 'NO ✓'); +} + +function drawSVMTraining() { + const canvas = document.getElementById('svm-train-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 450; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const padding = 60; + const chartWidth = width - 2 * padding; + const chartHeight = height - 2 * padding; + + const xMin = 0, xMax = 10; + const yMin = 0, yMax = 10; + + const scaleX = (x) => padding + ((x - xMin) / (xMax - xMin)) * chartWidth; + const scaleY = (y) => height - padding - ((y - yMin) / (yMax - yMin)) * chartHeight; + + const w = state.svm.training.w; + const b = state.svm.training.b; + + // Draw boundary if weights are non-zero + if (Math.abs(w[1]) > 0.01) { + ctx.strokeStyle = '#6aa9ff'; + ctx.lineWidth = 3; + ctx.beginPath(); + const x1 = xMin, y1 = -(w[0] * x1 + b) / w[1]; + const x2 = xMax, y2 = -(w[0] * x2 + b) / w[1]; + ctx.moveTo(scaleX(x1), scaleY(y1)); + ctx.lineTo(scaleX(x2), scaleY(y2)); + ctx.stroke(); + } + + // Draw points + data.svm.forEach((point, i) => { + const x = scaleX(point.x1); + const y = scaleY(point.x2); + const processed = i < state.svm.training.step; + const current = i === state.svm.training.step - 1; + + ctx.fillStyle = point.class === 1 ? '#7ef0d4' : '#ff8c6a'; + ctx.globalAlpha = processed ? 1 : 0.3; + ctx.beginPath(); + ctx.arc(x, y, 8, 0, 2 * Math.PI); + ctx.fill(); + + if (current) { + ctx.globalAlpha = 1; + ctx.strokeStyle = '#ffff00'; + ctx.lineWidth = 3; + ctx.beginPath(); + ctx.arc(x, y, 14, 0, 2 * Math.PI); + ctx.stroke(); + } + + ctx.globalAlpha = 1; + ctx.fillStyle = '#e8eef6'; + ctx.font = 'bold 12px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText(point.label, x, y - 15); + }); +} + +function initSVMKernel() { + const canvas = document.getElementById('svm-kernel-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + + const kernelRadios = document.querySelectorAll('input[name="kernel"]'); + kernelRadios.forEach(radio => { + radio.addEventListener('change', (e) => { + state.svm.kernel = e.target.value; + const paramGroup = document.getElementById('kernel-param-group'); + if (paramGroup) { + paramGroup.style.display = state.svm.kernel === 'linear' ? 'none' : 'block'; + } + drawSVMKernel(); + }); + }); + + const paramSlider = document.getElementById('kernel-param-slider'); + if (paramSlider) { + paramSlider.addEventListener('input', (e) => { + state.svm.kernelParam = parseFloat(e.target.value); + document.getElementById('kernel-param-val').textContent = state.svm.kernelParam.toFixed(1); + drawSVMKernel(); + }); + } + + drawSVMKernel(); +} + +function drawSVMKernel() { + const canvas = document.getElementById('svm-kernel-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 500; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const padding = 60; + const chartWidth = width - 2 * padding; + const chartHeight = height - 2 * padding; + + // Generate circular data + const innerPoints = []; + const outerPoints = []; + + for (let i = 0; i < 15; i++) { + const angle = (i / 15) * 2 * Math.PI; + innerPoints.push({ x: 5 + 1.5 * Math.cos(angle), y: 5 + 1.5 * Math.sin(angle), class: 1 }); + } + + for (let i = 0; i < 20; i++) { + const angle = (i / 20) * 2 * Math.PI; + const r = 3.5 + Math.random() * 0.5; + outerPoints.push({ x: 5 + r * Math.cos(angle), y: 5 + r * Math.sin(angle), class: -1 }); + } + + const allPoints = [...innerPoints, ...outerPoints]; + + const xMin = 0, xMax = 10; + const yMin = 0, yMax = 10; + + const scaleX = (x) => padding + ((x - xMin) / (xMax - xMin)) * chartWidth; + const scaleY = (y) => height - padding - ((y - yMin) / (yMax - yMin)) * chartHeight; + + // Draw decision boundary based on kernel + if (state.svm.kernel === 'linear') { + // Linear can't separate circular data well + ctx.strokeStyle = 'rgba(106, 169, 255, 0.5)'; + ctx.lineWidth = 2; + ctx.beginPath(); + ctx.moveTo(scaleX(2), scaleY(2)); + ctx.lineTo(scaleX(8), scaleY(8)); + ctx.stroke(); + } else if (state.svm.kernel === 'polynomial' || state.svm.kernel === 'rbf') { + // Draw circular boundary + ctx.strokeStyle = '#6aa9ff'; + ctx.lineWidth = 3; + ctx.beginPath(); + const radius = state.svm.kernel === 'polynomial' ? 2.5 : 2.3 + state.svm.kernelParam * 0.1; + ctx.arc(scaleX(5), scaleY(5), radius * (chartWidth / 10), 0, 2 * Math.PI); + ctx.stroke(); + } + + // Draw points + allPoints.forEach(point => { + const x = scaleX(point.x); + const y = scaleY(point.y); + + ctx.fillStyle = point.class === 1 ? '#7ef0d4' : '#ff8c6a'; + ctx.beginPath(); + ctx.arc(x, y, 5, 0, 2 * Math.PI); + ctx.fill(); + }); + + // Draw kernel info + ctx.fillStyle = '#7ef0d4'; + ctx.font = '16px sans-serif'; + ctx.textAlign = 'left'; + const kernelName = state.svm.kernel === 'linear' ? 'Linear Kernel' : + state.svm.kernel === 'polynomial' ? 'Polynomial Kernel' : 'RBF Kernel'; + ctx.fillText(kernelName, padding + 10, padding + 25); + + if (state.svm.kernel === 'linear') { + ctx.font = '13px sans-serif'; + ctx.fillStyle = '#ff8c6a'; + ctx.fillText('❌ Linear kernel cannot separate circular data!', padding + 10, padding + 50); + } else { + ctx.font = '13px sans-serif'; + ctx.fillStyle = '#7ef0d4'; + ctx.fillText('✓ Non-linear kernel successfully separates the data', padding + 10, padding + 50); + } +} + +// Logistic Regression Visualizations +function initLogistic() { + initSigmoid(); + initLogisticClassification(); +} + +function initSigmoid() { + const canvas = document.getElementById('sigmoid-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + drawSigmoid(); +} + +function drawSigmoid() { + const canvas = document.getElementById('sigmoid-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 350; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const padding = 60; + const chartWidth = width - 2 * padding; + const chartHeight = height - 2 * padding; + + const zMin = -10, zMax = 10; + const scaleX = (z) => padding + ((z - zMin) / (zMax - zMin)) * chartWidth; + const scaleY = (sig) => height - padding - sig * chartHeight; + + // Draw grid + ctx.strokeStyle = 'rgba(42, 53, 68, 0.5)'; + ctx.lineWidth = 1; + for (let i = 0; i <= 10; i++) { + const x = padding + (chartWidth / 10) * i; + ctx.beginPath(); + ctx.moveTo(x, padding); + ctx.lineTo(x, height - padding); + ctx.stroke(); + + const y = padding + (chartHeight / 10) * i; + ctx.beginPath(); + ctx.moveTo(padding, y); + ctx.lineTo(width - padding, y); + ctx.stroke(); + } + + // Draw axes + ctx.strokeStyle = '#2a3544'; + ctx.lineWidth = 2; + ctx.beginPath(); + ctx.moveTo(padding, padding); + ctx.lineTo(padding, height - padding); + ctx.lineTo(width - padding, height - padding); + ctx.stroke(); + + // Draw threshold line at 0.5 + ctx.strokeStyle = '#ff8c6a'; + ctx.lineWidth = 1; + ctx.setLineDash([5, 5]); + ctx.beginPath(); + ctx.moveTo(padding, scaleY(0.5)); + ctx.lineTo(width - padding, scaleY(0.5)); + ctx.stroke(); + ctx.setLineDash([]); + + // Draw sigmoid curve + ctx.strokeStyle = '#7ef0d4'; + ctx.lineWidth = 3; + ctx.beginPath(); + for (let z = zMin; z <= zMax; z += 0.1) { + const sig = 1 / (1 + Math.exp(-z)); + const x = scaleX(z); + const y = scaleY(sig); + if (z === zMin) ctx.moveTo(x, y); + else ctx.lineTo(x, y); + } + ctx.stroke(); + + // Labels + ctx.fillStyle = '#a9b4c2'; + ctx.font = '12px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText('z (input)', width / 2, height - 20); + ctx.save(); + ctx.translate(20, height / 2); + ctx.rotate(-Math.PI / 2); + ctx.fillText('σ(z) probability', 0, 0); + ctx.restore(); + + // Annotations + ctx.fillStyle = '#7ef0d4'; + ctx.textAlign = 'left'; + ctx.fillText('σ(z) = 1/(1+e⁻ᶻ)', padding + 10, padding + 25); + ctx.fillStyle = '#ff8c6a'; + ctx.fillText('Threshold = 0.5', padding + 10, scaleY(0.5) - 10); +} + +function initLogisticClassification() { + const canvas = document.getElementById('logistic-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + drawLogisticClassification(); +} + +function drawLogisticClassification() { + const canvas = document.getElementById('logistic-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 400; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const padding = 60; + const chartWidth = width - 2 * padding; + const chartHeight = height - 2 * padding; + + const hMin = 140, hMax = 210; + const scaleX = (h) => padding + ((h - hMin) / (hMax - hMin)) * chartWidth; + const scaleY = (p) => height - padding - p * chartHeight; + + // Draw sigmoid curve + ctx.strokeStyle = '#6aa9ff'; + ctx.lineWidth = 3; + ctx.beginPath(); + for (let h = hMin; h <= hMax; h += 1) { + const z = (h - 170) / 10; // Simple linear transformation + const p = 1 / (1 + Math.exp(-z)); + const x = scaleX(h); + const y = scaleY(p); + if (h === hMin) ctx.moveTo(x, y); + else ctx.lineTo(x, y); + } + ctx.stroke(); + + // Draw threshold line + ctx.strokeStyle = '#ff8c6a'; + ctx.setLineDash([5, 5]); + ctx.beginPath(); + ctx.moveTo(padding, scaleY(0.5)); + ctx.lineTo(width - padding, scaleY(0.5)); + ctx.stroke(); + ctx.setLineDash([]); + + // Draw data points + data.logistic.forEach(point => { + const x = scaleX(point.height); + const y = scaleY(point.prob); + + ctx.fillStyle = point.label === 1 ? '#7ef0d4' : '#ff8c6a'; + ctx.beginPath(); + ctx.arc(x, y, 6, 0, 2 * Math.PI); + ctx.fill(); + + // Label + ctx.fillStyle = '#e8eef6'; + ctx.font = '11px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText(point.height, x, height - padding + 20); + }); + + // Labels + ctx.fillStyle = '#a9b4c2'; + ctx.font = '12px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText('Height (cm)', width / 2, height - 20); + ctx.save(); + ctx.translate(20, height / 2); + ctx.rotate(-Math.PI / 2); + ctx.fillText('P(Tall)', 0, 0); + ctx.restore(); +} + +// KNN Visualization +let knnState = { testPoint: { x: 2.5, y: 2.5 }, k: 3, distanceMetric: 'euclidean', dragging: false }; + +function initKNN() { + const canvas = document.getElementById('knn-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + + const kSlider = document.getElementById('knn-k-slider'); + if (kSlider) { + kSlider.addEventListener('input', (e) => { + knnState.k = parseInt(e.target.value); + document.getElementById('knn-k-val').textContent = knnState.k; + drawKNN(); + }); + } + + const distanceRadios = document.querySelectorAll('input[name="knn-distance"]'); + distanceRadios.forEach(radio => { + radio.addEventListener('change', (e) => { + knnState.distanceMetric = e.target.value; + drawKNN(); + }); + }); + + canvas.addEventListener('mousedown', startDragKNN); + canvas.addEventListener('mousemove', dragKNN); + canvas.addEventListener('mouseup', stopDragKNN); + + drawKNN(); +} + +function startDragKNN(e) { + const canvas = document.getElementById('knn-canvas'); + const rect = canvas.getBoundingClientRect(); + const mx = e.clientX - rect.left; + const my = e.clientY - rect.top; + + const padding = 60; + const chartWidth = canvas.width - 2 * padding; + const chartHeight = canvas.height - 2 * padding; + + const tx = padding + (knnState.testPoint.x / 6) * chartWidth; + const ty = canvas.height - padding - (knnState.testPoint.y / 6) * chartHeight; + + if (Math.abs(mx - tx) < 15 && Math.abs(my - ty) < 15) { + knnState.dragging = true; + } +} + +function dragKNN(e) { + if (!knnState.dragging) return; + + const canvas = document.getElementById('knn-canvas'); + const rect = canvas.getBoundingClientRect(); + const mx = e.clientX - rect.left; + const my = e.clientY - rect.top; + + const padding = 60; + const chartWidth = canvas.width - 2 * padding; + const chartHeight = canvas.height - 2 * padding; + + knnState.testPoint.x = Math.max(0, Math.min(6, ((mx - padding) / chartWidth) * 6)); + knnState.testPoint.y = Math.max(0, Math.min(6, ((canvas.height - padding - my) / chartHeight) * 6)); + + drawKNN(); +} + +function stopDragKNN() { + knnState.dragging = false; +} + +function drawKNN() { + const canvas = document.getElementById('knn-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 450; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const padding = 60; + const chartWidth = width - 2 * padding; + const chartHeight = height - 2 * padding; + + const scaleX = (x) => padding + (x / 6) * chartWidth; + const scaleY = (y) => height - padding - (y / 6) * chartHeight; + + // Calculate distances + const distances = data.knn.map(point => { + let d; + if (knnState.distanceMetric === 'euclidean') { + d = Math.sqrt(Math.pow(point.x - knnState.testPoint.x, 2) + Math.pow(point.y - knnState.testPoint.y, 2)); + } else { + d = Math.abs(point.x - knnState.testPoint.x) + Math.abs(point.y - knnState.testPoint.y); + } + return { ...point, distance: d }; + }); + + distances.sort((a, b) => a.distance - b.distance); + const kNearest = distances.slice(0, knnState.k); + + // Count votes + const votes = {}; + kNearest.forEach(p => { + votes[p.class] = (votes[p.class] || 0) + 1; + }); + const prediction = Object.keys(votes).reduce((a, b) => votes[a] > votes[b] ? a : b); + + // Draw lines to K nearest + kNearest.forEach(point => { + ctx.strokeStyle = 'rgba(126, 240, 212, 0.3)'; + ctx.lineWidth = 1; + ctx.beginPath(); + ctx.moveTo(scaleX(knnState.testPoint.x), scaleY(knnState.testPoint.y)); + ctx.lineTo(scaleX(point.x), scaleY(point.y)); + ctx.stroke(); + }); + + // Draw training points + distances.forEach(point => { + const x = scaleX(point.x); + const y = scaleY(point.y); + const isNearest = kNearest.includes(point); + + ctx.fillStyle = point.class === 'orange' ? '#ff8c6a' : '#ffeb3b'; + ctx.globalAlpha = isNearest ? 1 : 0.5; + ctx.beginPath(); + ctx.arc(x, y, 8, 0, 2 * Math.PI); + ctx.fill(); + + if (isNearest) { + ctx.strokeStyle = '#7ef0d4'; + ctx.lineWidth = 2; + ctx.globalAlpha = 1; + ctx.beginPath(); + ctx.arc(x, y, 12, 0, 2 * Math.PI); + ctx.stroke(); + } + ctx.globalAlpha = 1; + }); + + // Draw test point + const tx = scaleX(knnState.testPoint.x); + const ty = scaleY(knnState.testPoint.y); + ctx.fillStyle = prediction === 'orange' ? '#ff8c6a' : '#ffeb3b'; + ctx.beginPath(); + ctx.arc(tx, ty, 12, 0, 2 * Math.PI); + ctx.fill(); + ctx.strokeStyle = '#6aa9ff'; + ctx.lineWidth = 3; + ctx.stroke(); + + // Info + ctx.fillStyle = '#7ef0d4'; + ctx.font = '14px sans-serif'; + ctx.textAlign = 'left'; + ctx.fillText(`K=${knnState.k} | Prediction: ${prediction}`, padding + 10, padding + 25); + ctx.fillText(`Votes: Orange=${votes.orange || 0}, Yellow=${votes.yellow || 0}`, padding + 10, padding + 50); +} + +// Model Evaluation +function initModelEvaluation() { + initConfusionMatrix(); + initROC(); + initR2(); +} + +function initConfusionMatrix() { + const canvas = document.getElementById('confusion-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + drawConfusionMatrix(); +} + +function drawConfusionMatrix() { + const canvas = document.getElementById('confusion-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 300; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const size = Math.min(width, height) - 100; + const cellSize = size / 2; + const startX = (width - size) / 2; + const startY = 50; + + const cm = { tp: 600, fp: 100, fn: 300, tn: 900 }; + + // Draw cells + const cells = [ + { x: startX, y: startY, val: cm.tp, label: 'TP', color: '#7ef0d4' }, + { x: startX + cellSize, y: startY, val: cm.fn, label: 'FN', color: '#ff8c6a' }, + { x: startX, y: startY + cellSize, val: cm.fp, label: 'FP', color: '#ff8c6a' }, + { x: startX + cellSize, y: startY + cellSize, val: cm.tn, label: 'TN', color: '#7ef0d4' } + ]; + + cells.forEach(cell => { + ctx.fillStyle = cell.color + '22'; + ctx.fillRect(cell.x, cell.y, cellSize, cellSize); + ctx.strokeStyle = cell.color; + ctx.lineWidth = 2; + ctx.strokeRect(cell.x, cell.y, cellSize, cellSize); + + ctx.fillStyle = cell.color; + ctx.font = 'bold 16px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText(cell.label, cell.x + cellSize / 2, cell.y + cellSize / 2 - 10); + ctx.font = 'bold 32px sans-serif'; + ctx.fillText(cell.val, cell.x + cellSize / 2, cell.y + cellSize / 2 + 25); + }); + + // Labels + ctx.fillStyle = '#a9b4c2'; + ctx.font = '14px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText('Predicted Positive', startX + cellSize / 2, startY - 15); + ctx.fillText('Predicted Negative', startX + cellSize * 1.5, startY - 15); + ctx.save(); + ctx.translate(startX - 30, startY + cellSize / 2); + ctx.rotate(-Math.PI / 2); + ctx.fillText('Actual Positive', 0, 0); + ctx.restore(); + ctx.save(); + ctx.translate(startX - 30, startY + cellSize * 1.5); + ctx.rotate(-Math.PI / 2); + ctx.fillText('Actual Negative', 0, 0); + ctx.restore(); +} + +let rocState = { threshold: 0.5 }; + +function initROC() { + const canvas = document.getElementById('roc-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + + const slider = document.getElementById('roc-threshold-slider'); + if (slider) { + slider.addEventListener('input', (e) => { + rocState.threshold = parseFloat(e.target.value); + document.getElementById('roc-threshold-val').textContent = rocState.threshold.toFixed(1); + drawROC(); + }); + } + + drawROC(); +} + +function drawROC() { + const canvas = document.getElementById('roc-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 450; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const padding = 60; + const chartSize = Math.min(width - 2 * padding, height - 2 * padding); + const chartX = (width - chartSize) / 2; + const chartY = (height - chartSize) / 2; + + // Calculate ROC points + const rocPoints = []; + for (let t = 0; t <= 1; t += 0.1) { + let tp = 0, fp = 0, tn = 0, fn = 0; + data.roc.forEach(e => { + const pred = e.score >= t ? 1 : 0; + if (e.true_label === 1 && pred === 1) tp++; + else if (e.true_label === 0 && pred === 1) fp++; + else if (e.true_label === 1 && pred === 0) fn++; + else tn++; + }); + const tpr = tp / (tp + fn) || 0; + const fpr = fp / (fp + tn) || 0; + rocPoints.push({ t, tpr, fpr }); + } + + // Current threshold point + let tp = 0, fp = 0, tn = 0, fn = 0; + data.roc.forEach(e => { + const pred = e.score >= rocState.threshold ? 1 : 0; + if (e.true_label === 1 && pred === 1) tp++; + else if (e.true_label === 0 && pred === 1) fp++; + else if (e.true_label === 1 && pred === 0) fn++; + else tn++; + }); + const tpr = tp / (tp + fn) || 0; + const fpr = fp / (fp + tn) || 0; + + // Draw diagonal (random) + ctx.strokeStyle = 'rgba(255, 140, 106, 0.5)'; + ctx.lineWidth = 2; + ctx.setLineDash([5, 5]); + ctx.beginPath(); + ctx.moveTo(chartX, chartY + chartSize); + ctx.lineTo(chartX + chartSize, chartY); + ctx.stroke(); + ctx.setLineDash([]); + + // Draw ROC curve + ctx.strokeStyle = '#6aa9ff'; + ctx.lineWidth = 3; + ctx.beginPath(); + rocPoints.forEach((p, i) => { + const x = chartX + p.fpr * chartSize; + const y = chartY + chartSize - p.tpr * chartSize; + if (i === 0) ctx.moveTo(x, y); + else ctx.lineTo(x, y); + }); + ctx.stroke(); + + // Draw current point + const cx = chartX + fpr * chartSize; + const cy = chartY + chartSize - tpr * chartSize; + ctx.fillStyle = '#7ef0d4'; + ctx.beginPath(); + ctx.arc(cx, cy, 8, 0, 2 * Math.PI); + ctx.fill(); + + // Draw axes + ctx.strokeStyle = '#2a3544'; + ctx.lineWidth = 2; + ctx.beginPath(); + ctx.rect(chartX, chartY, chartSize, chartSize); + ctx.stroke(); + + // Labels + ctx.fillStyle = '#a9b4c2'; + ctx.font = '12px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText('FPR (False Positive Rate)', width / 2, height - 20); + ctx.save(); + ctx.translate(20, height / 2); + ctx.rotate(-Math.PI / 2); + ctx.fillText('TPR (True Positive Rate)', 0, 0); + ctx.restore(); + + // Info + ctx.fillStyle = '#7ef0d4'; + ctx.font = '14px sans-serif'; + ctx.textAlign = 'left'; + ctx.fillText(`TPR: ${tpr.toFixed(2)} | FPR: ${fpr.toFixed(2)}`, chartX + 10, chartY + 25); + ctx.fillText(`TP=${tp} FP=${fp} TN=${tn} FN=${fn}`, chartX + 10, chartY + 50); +} + +function initR2() { + const canvas = document.getElementById('r2-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + drawR2(); +} + +function drawR2() { + const canvas = document.getElementById('r2-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 350; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + // Dummy R² data + const r2data = [ + { x: 150, y: 50, pred: 52 }, + { x: 160, y: 60, pred: 61 }, + { x: 170, y: 70, pred: 69 }, + { x: 180, y: 80, pred: 78 }, + { x: 190, y: 90, pred: 87 } + ]; + + const padding = 60; + const chartWidth = width - 2 * padding; + const chartHeight = height - 2 * padding; + + const xMin = 140, xMax = 200, yMin = 40, yMax = 100; + const scaleX = (x) => padding + ((x - xMin) / (xMax - xMin)) * chartWidth; + const scaleY = (y) => height - padding - ((y - yMin) / (yMax - yMin)) * chartHeight; + + // Mean + const mean = r2data.reduce((sum, p) => sum + p.y, 0) / r2data.length; + + // Draw mean line + ctx.strokeStyle = '#ff8c6a'; + ctx.setLineDash([5, 5]); + ctx.lineWidth = 2; + ctx.beginPath(); + ctx.moveTo(padding, scaleY(mean)); + ctx.lineTo(width - padding, scaleY(mean)); + ctx.stroke(); + ctx.setLineDash([]); + + // Draw regression line + ctx.strokeStyle = '#6aa9ff'; + ctx.lineWidth = 2; + ctx.beginPath(); + ctx.moveTo(scaleX(xMin), scaleY(40)); + ctx.lineTo(scaleX(xMax), scaleY(95)); + ctx.stroke(); + + // Draw points + r2data.forEach(p => { + // Residual line + ctx.strokeStyle = 'rgba(126, 240, 212, 0.3)'; + ctx.lineWidth = 1; + ctx.beginPath(); + ctx.moveTo(scaleX(p.x), scaleY(p.y)); + ctx.lineTo(scaleX(p.x), scaleY(p.pred)); + ctx.stroke(); + + // Actual point + ctx.fillStyle = '#7ef0d4'; + ctx.beginPath(); + ctx.arc(scaleX(p.x), scaleY(p.y), 6, 0, 2 * Math.PI); + ctx.fill(); + }); + + // Calculate R² + let ssRes = 0, ssTot = 0; + r2data.forEach(p => { + ssRes += Math.pow(p.y - p.pred, 2); + ssTot += Math.pow(p.y - mean, 2); + }); + const r2 = 1 - (ssRes / ssTot); + + // Info + ctx.fillStyle = '#7ef0d4'; + ctx.font = '16px sans-serif'; + ctx.textAlign = 'left'; + ctx.fillText(`R² = ${r2.toFixed(3)}`, padding + 10, padding + 25); + ctx.fillText(`Model explains ${(r2 * 100).toFixed(1)}% of variance`, padding + 10, padding + 50); +} + +// Regularization +let regState = { lambda: 0.1 }; + +function initRegularization() { + const canvas = document.getElementById('regularization-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + + const slider = document.getElementById('reg-lambda-slider'); + if (slider) { + slider.addEventListener('input', (e) => { + regState.lambda = parseFloat(e.target.value); + document.getElementById('reg-lambda-val').textContent = regState.lambda.toFixed(1); + drawRegularization(); + }); + } + + drawRegularization(); +} + +function drawRegularization() { + const canvas = document.getElementById('regularization-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 400; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const padding = 60; + const chartWidth = width - 2 * padding; + const chartHeight = height - 2 * padding; + + const features = ['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10']; + const vanilla = [100, 200, 300, 50, 150, 250, 80, 120, 90, 180]; + + // Simulate L1 and L2 effects + const l1 = vanilla.map(v => Math.abs(v) > 50 / regState.lambda ? v * (1 - regState.lambda * 0.5) : 0); + const l2 = vanilla.map(v => v / (1 + regState.lambda)); + + const barWidth = chartWidth / (features.length * 3.5); + const maxVal = Math.max(...vanilla); + + features.forEach((f, i) => { + const x = padding + (i * chartWidth / features.length); + + // Vanilla + const h1 = (vanilla[i] / maxVal) * chartHeight * 0.8; + ctx.fillStyle = '#a9b4c2'; + ctx.fillRect(x, height - padding - h1, barWidth, h1); + + // L1 + const h2 = (l1[i] / maxVal) * chartHeight * 0.8; + ctx.fillStyle = '#ff8c6a'; + ctx.fillRect(x + barWidth * 1.2, height - padding - h2, barWidth, h2); + + // L2 + const h3 = (l2[i] / maxVal) * chartHeight * 0.8; + ctx.fillStyle = '#6aa9ff'; + ctx.fillRect(x + barWidth * 2.4, height - padding - h3, barWidth, h3); + + // Feature label + ctx.fillStyle = '#a9b4c2'; + ctx.font = '11px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText(f, x + barWidth * 1.5, height - padding + 20); + }); + + // Legend + const legendY = padding + 20; + ctx.fillStyle = '#a9b4c2'; + ctx.fillRect(padding + 10, legendY, 15, 15); + ctx.fillStyle = '#e8eef6'; + ctx.font = '12px sans-serif'; + ctx.textAlign = 'left'; + ctx.fillText('Vanilla', padding + 30, legendY + 12); + + ctx.fillStyle = '#ff8c6a'; + ctx.fillRect(padding + 100, legendY, 15, 15); + ctx.fillStyle = '#e8eef6'; + ctx.fillText('L1 (Lasso)', padding + 120, legendY + 12); + + ctx.fillStyle = '#6aa9ff'; + ctx.fillRect(padding + 210, legendY, 15, 15); + ctx.fillStyle = '#e8eef6'; + ctx.fillText('L2 (Ridge)', padding + 230, legendY + 12); +} + +// Bias-Variance +function initBiasVariance() { + const canvas = document.getElementById('bias-variance-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + drawBiasVariance(); + + const canvas2 = document.getElementById('complexity-canvas'); + if (canvas2 && !canvas2.dataset.initialized) { + canvas2.dataset.initialized = 'true'; + drawComplexityCurve(); + } +} + +function drawBiasVariance() { + const canvas = document.getElementById('bias-variance-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 400; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const sectionWidth = width / 3; + const padding = 40; + const chartHeight = height - 2 * padding; + + // Generate curved data + const trueData = []; + for (let x = 0; x <= 10; x += 0.5) { + trueData.push({ x, y: 50 + 30 * Math.sin(x / 2) }); + } + + // Draw three scenarios + const scenarios = [ + { title: 'High Bias\n(Underfit)', color: '#ff8c6a', degree: 1 }, + { title: 'Good Fit', color: '#7ef0d4', degree: 2 }, + { title: 'High Variance\n(Overfit)', color: '#ff8c6a', degree: 8 } + ]; + + scenarios.forEach((scenario, idx) => { + const offsetX = idx * sectionWidth; + const scaleX = (x) => offsetX + padding + (x / 10) * (sectionWidth - 2 * padding); + const scaleY = (y) => padding + chartHeight - ((y - 20) / 80) * chartHeight; + + // Draw true curve + ctx.strokeStyle = 'rgba(106, 169, 255, 0.3)'; + ctx.lineWidth = 2; + ctx.beginPath(); + trueData.forEach((p, i) => { + if (i === 0) ctx.moveTo(scaleX(p.x), scaleY(p.y)); + else ctx.lineTo(scaleX(p.x), scaleY(p.y)); + }); + ctx.stroke(); + + // Draw model fit + ctx.strokeStyle = scenario.color; + ctx.lineWidth = 3; + ctx.beginPath(); + if (scenario.degree === 1) { + // Straight line + ctx.moveTo(scaleX(0), scaleY(50)); + ctx.lineTo(scaleX(10), scaleY(65)); + } else if (scenario.degree === 2) { + // Good fit + trueData.forEach((p, i) => { + const noise = (Math.random() - 0.5) * 3; + if (i === 0) ctx.moveTo(scaleX(p.x), scaleY(p.y + noise)); + else ctx.lineTo(scaleX(p.x), scaleY(p.y + noise)); + }); + } else { + // Wiggly overfit + for (let x = 0; x <= 10; x += 0.2) { + const y = 50 + 30 * Math.sin(x / 2) + 15 * Math.sin(x * 2); + if (x === 0) ctx.moveTo(scaleX(x), scaleY(y)); + else ctx.lineTo(scaleX(x), scaleY(y)); + } + } + ctx.stroke(); + + // Title + ctx.fillStyle = scenario.color; + ctx.font = 'bold 14px sans-serif'; + ctx.textAlign = 'center'; + const lines = scenario.title.split('\n'); + lines.forEach((line, i) => { + ctx.fillText(line, offsetX + sectionWidth / 2, 20 + i * 18); + }); + }); +} + +function drawComplexityCurve() { + const canvas = document.getElementById('complexity-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 350; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const padding = 60; + const chartWidth = width - 2 * padding; + const chartHeight = height - 2 * padding; + + const scaleX = (x) => padding + (x / 10) * chartWidth; + const scaleY = (y) => padding + chartHeight - (y / 100) * chartHeight; + + // Draw curves + ctx.strokeStyle = '#ff8c6a'; + ctx.lineWidth = 3; + ctx.beginPath(); + for (let x = 0; x <= 10; x += 0.1) { + const trainError = 80 * Math.exp(-x / 2) + 5; + if (x === 0) ctx.moveTo(scaleX(x), scaleY(trainError)); + else ctx.lineTo(scaleX(x), scaleY(trainError)); + } + ctx.stroke(); + + ctx.strokeStyle = '#6aa9ff'; + ctx.beginPath(); + for (let x = 0; x <= 10; x += 0.1) { + const testError = 80 * Math.exp(-x / 2) + 5 + 15 * (x / 10) ** 2; + if (x === 0) ctx.moveTo(scaleX(x), scaleY(testError)); + else ctx.lineTo(scaleX(x), scaleY(testError)); + } + ctx.stroke(); + + // Sweet spot + ctx.fillStyle = '#7ef0d4'; + ctx.beginPath(); + ctx.arc(scaleX(5), scaleY(18), 8, 0, 2 * Math.PI); + ctx.fill(); + + // Legend + ctx.fillStyle = '#ff8c6a'; + ctx.font = '12px sans-serif'; + ctx.textAlign = 'left'; + ctx.fillText('Training Error', padding + 10, padding + 20); + ctx.fillStyle = '#6aa9ff'; + ctx.fillText('Test Error', padding + 10, padding + 40); + ctx.fillStyle = '#7ef0d4'; + ctx.fillText('● Sweet Spot', padding + 10, padding + 60); + + // Labels + ctx.fillStyle = '#a9b4c2'; + ctx.textAlign = 'center'; + ctx.fillText('Model Complexity →', width / 2, height - 20); + ctx.save(); + ctx.translate(20, height / 2); + ctx.rotate(-Math.PI / 2); + ctx.fillText('Error', 0, 0); + ctx.restore(); +} + +// Cross-Validation +function initCrossValidation() { + const canvas = document.getElementById('cv-canvas'); + if (!canvas || canvas.dataset.initialized) return; + canvas.dataset.initialized = 'true'; + drawCrossValidation(); +} + +function drawCrossValidation() { + const canvas = document.getElementById('cv-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 400; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const blockSize = 50; + const gap = 10; + const numBlocks = 12; + const k = 3; + const blocksPerFold = numBlocks / k; + + const startX = (width - (numBlocks * blockSize + (numBlocks - 1) * gap)) / 2; + + const folds = [0.96, 0.84, 0.90]; + + for (let fold = 0; fold < k; fold++) { + const offsetY = 80 + fold * 120; + + // Fold label + ctx.fillStyle = '#e8eef6'; + ctx.font = 'bold 14px sans-serif'; + ctx.textAlign = 'right'; + ctx.fillText(`Fold ${fold + 1}:`, startX - 20, offsetY + blockSize / 2 + 5); + + // Draw blocks + for (let i = 0; i < numBlocks; i++) { + const x = startX + i * (blockSize + gap); + const isFold = i >= fold * blocksPerFold && i < (fold + 1) * blocksPerFold; + + ctx.fillStyle = isFold ? '#6aa9ff' : '#7ef0d4'; + ctx.fillRect(x, offsetY, blockSize, blockSize); + + // Label + ctx.fillStyle = '#1a2332'; + ctx.font = 'bold 12px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText(String.fromCharCode(65 + i), x + blockSize / 2, offsetY + blockSize / 2 + 5); + } + + // Accuracy + ctx.fillStyle = '#7ef0d4'; + ctx.font = '14px sans-serif'; + ctx.textAlign = 'left'; + ctx.fillText(`Acc: ${folds[fold].toFixed(2)}`, startX + numBlocks * (blockSize + gap) + 20, offsetY + blockSize / 2 + 5); + } + + // Legend + ctx.fillStyle = '#6aa9ff'; + ctx.fillRect(startX, 30, 30, 20); + ctx.fillStyle = '#e8eef6'; + ctx.font = '12px sans-serif'; + ctx.textAlign = 'left'; + ctx.fillText('Test Set', startX + 40, 45); + + ctx.fillStyle = '#7ef0d4'; + ctx.fillRect(startX + 120, 30, 30, 20); + ctx.fillText('Training Set', startX + 160, 45); + + // Final result + const mean = folds.reduce((a, b) => a + b) / folds.length; + const std = Math.sqrt(folds.reduce((sum, x) => sum + Math.pow(x - mean, 2), 0) / folds.length); + + ctx.fillStyle = '#7ef0d4'; + ctx.font = 'bold 16px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText(`Final Score: ${mean.toFixed(2)} ± ${std.toFixed(3)}`, width / 2, height - 20); +} + +// Preprocessing +function initPreprocessing() { + const canvas = document.getElementById('scaling-canvas'); + if (canvas && !canvas.dataset.initialized) { + canvas.dataset.initialized = 'true'; + drawScaling(); + } + + const canvas2 = document.getElementById('pipeline-canvas'); + if (canvas2 && !canvas2.dataset.initialized) { + canvas2.dataset.initialized = 'true'; + drawPipeline(); + } +} + +function drawScaling() { + const canvas = document.getElementById('scaling-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 350; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const before = [10, 20, 30, 40, 50]; + const standard = [-1.26, -0.63, 0, 0.63, 1.26]; + const minmax = [0, 0.25, 0.5, 0.75, 1.0]; + + const sectionWidth = width / 3; + const padding = 40; + const barWidth = 30; + + const datasets = [ + { data: before, title: 'Original', maxVal: 60 }, + { data: standard, title: 'StandardScaler', maxVal: 2 }, + { data: minmax, title: 'MinMaxScaler', maxVal: 1.2 } + ]; + + datasets.forEach((dataset, idx) => { + const offsetX = idx * sectionWidth; + const centerX = offsetX + sectionWidth / 2; + + // Title + ctx.fillStyle = '#7ef0d4'; + ctx.font = 'bold 14px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText(dataset.title, centerX, 30); + + // Draw bars + dataset.data.forEach((val, i) => { + const barHeight = Math.abs(val) / dataset.maxVal * 200; + const x = centerX - barWidth / 2; + const y = val >= 0 ? 200 - barHeight : 200; + + ctx.fillStyle = '#6aa9ff'; + ctx.fillRect(x, y, barWidth, barHeight); + + // Value label + ctx.fillStyle = '#a9b4c2'; + ctx.font = '10px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText(val.toFixed(2), centerX, val >= 0 ? y - 5 : y + barHeight + 15); + + centerX += 35; + }); + }); +} + +function drawPipeline() { + const canvas = document.getElementById('pipeline-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 300; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const steps = ['Raw Data', 'Handle Missing', 'Encode Categories', 'Scale Features', 'Train Model']; + const stepWidth = (width - 100) / steps.length; + const y = height / 2; + + steps.forEach((step, i) => { + const x = 50 + i * stepWidth; + + // Box + ctx.fillStyle = '#2a3544'; + ctx.fillRect(x, y - 30, stepWidth - 40, 60); + ctx.strokeStyle = '#6aa9ff'; + ctx.lineWidth = 2; + ctx.strokeRect(x, y - 30, stepWidth - 40, 60); + + // Text + ctx.fillStyle = '#e8eef6'; + ctx.font = '12px sans-serif'; + ctx.textAlign = 'center'; + const words = step.split(' '); + words.forEach((word, j) => { + ctx.fillText(word, x + (stepWidth - 40) / 2, y + j * 15 - 5); + }); + + // Arrow + if (i < steps.length - 1) { + ctx.strokeStyle = '#7ef0d4'; + ctx.lineWidth = 2; + ctx.beginPath(); + ctx.moveTo(x + stepWidth - 40, y); + ctx.lineTo(x + stepWidth - 10, y); + ctx.stroke(); + + // Arrowhead + ctx.fillStyle = '#7ef0d4'; + ctx.beginPath(); + ctx.moveTo(x + stepWidth - 10, y); + ctx.lineTo(x + stepWidth - 20, y - 5); + ctx.lineTo(x + stepWidth - 20, y + 5); + ctx.fill(); + } + }); +} + +// Loss Functions +function initLossFunctions() { + const canvas = document.getElementById('loss-comparison-canvas'); + if (canvas && !canvas.dataset.initialized) { + canvas.dataset.initialized = 'true'; + drawLossComparison(); + } + + const canvas2 = document.getElementById('loss-curves-canvas'); + if (canvas2 && !canvas2.dataset.initialized) { + canvas2.dataset.initialized = 'true'; + drawLossCurves(); + } +} + +function drawLossComparison() { + const canvas = document.getElementById('loss-comparison-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 400; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const actual = [10, 20, 30, 40, 50]; + const predicted = [12, 19, 32, 38, 51]; + + // Calculate losses + let mse = 0, mae = 0; + actual.forEach((a, i) => { + const error = a - predicted[i]; + mse += error * error; + mae += Math.abs(error); + }); + mse /= actual.length; + mae /= actual.length; + const rmse = Math.sqrt(mse); + + // Display + const padding = 60; + const barHeight = 60; + const startY = 100; + const maxWidth = width - 2 * padding; + + const losses = [ + { name: 'MSE', value: mse, color: '#ff8c6a' }, + { name: 'MAE', value: mae, color: '#6aa9ff' }, + { name: 'RMSE', value: rmse, color: '#7ef0d4' } + ]; + + const maxLoss = Math.max(...losses.map(l => l.value)); + + losses.forEach((loss, i) => { + const y = startY + i * (barHeight + 30); + const barWidth = (loss.value / maxLoss) * maxWidth; + + // Bar + ctx.fillStyle = loss.color; + ctx.fillRect(padding, y, barWidth, barHeight); + + // Label + ctx.fillStyle = '#e8eef6'; + ctx.font = 'bold 14px sans-serif'; + ctx.textAlign = 'left'; + ctx.fillText(loss.name, padding + 10, y + barHeight / 2 + 5); + + // Value + ctx.font = '16px sans-serif'; + ctx.textAlign = 'right'; + ctx.fillText(loss.value.toFixed(2), padding + barWidth - 10, y + barHeight / 2 + 5); + }); + + // Title + ctx.fillStyle = '#7ef0d4'; + ctx.font = 'bold 16px sans-serif'; + ctx.textAlign = 'center'; + ctx.fillText('Regression Loss Comparison', width / 2, 50); +} + +function drawLossCurves() { + const canvas = document.getElementById('loss-curves-canvas'); + if (!canvas) return; + + const ctx = canvas.getContext('2d'); + const width = canvas.width = canvas.offsetWidth; + const height = canvas.height = 350; + + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = '#1a2332'; + ctx.fillRect(0, 0, width, height); + + const padding = 60; + const chartWidth = width - 2 * padding; + const chartHeight = height - 2 * padding; + + const scaleX = (x) => padding + (x / 10) * chartWidth; + const scaleY = (y) => height - padding - (y / 100) * chartHeight; + + // Draw MSE curve + ctx.strokeStyle = '#ff8c6a'; + ctx.lineWidth = 3; + ctx.beginPath(); + for (let x = -10; x <= 10; x += 0.2) { + const y = x * x; + if (x === -10) ctx.moveTo(scaleX(x + 10), scaleY(y)); + else ctx.lineTo(scaleX(x + 10), scaleY(y)); + } + ctx.stroke(); + + // Draw MAE curve + ctx.strokeStyle = '#6aa9ff'; + ctx.lineWidth = 3; + ctx.beginPath(); + for (let x = -10; x <= 10; x += 0.2) { + const y = Math.abs(x) * 10; + if (x === -10) ctx.moveTo(scaleX(x + 10), scaleY(y)); + else ctx.lineTo(scaleX(x + 10), scaleY(y)); + } + ctx.stroke(); + + // Legend + ctx.fillStyle = '#ff8c6a'; + ctx.font = '12px sans-serif'; + ctx.textAlign = 'left'; + ctx.fillText('MSE (quadratic penalty)', padding + 10, padding + 20); + ctx.fillStyle = '#6aa9ff'; + ctx.fillText('MAE (linear penalty)', padding + 10, padding + 40); + + // Labels + ctx.fillStyle = '#a9b4c2'; + ctx.textAlign = 'center'; + ctx.fillText('Error', width / 2, height - 20); + ctx.save(); + ctx.translate(20, height / 2); + ctx.rotate(-Math.PI / 2); + ctx.fillText('Loss', 0, 0); + ctx.restore(); +} + +// Handle window resize +let resizeTimer; +window.addEventListener('resize', () => { + clearTimeout(resizeTimer); + resizeTimer = setTimeout(() => { + drawLinearRegression(); + drawGradientDescent(); + drawSigmoid(); + drawLogisticClassification(); + drawKNN(); + drawConfusionMatrix(); + drawROC(); + drawR2(); + drawRegularization(); + drawBiasVariance(); + drawComplexityCurve(); + drawCrossValidation(); + drawScaling(); + drawPipeline(); + drawLossComparison(); + drawLossCurves(); + drawSVMBasic(); + drawSVMMargin(); + drawSVMCParameter(); + drawSVMTraining(); + drawSVMKernel(); + }, 250); +}); diff --git a/ml-complete-all-topics/index.html b/ml-complete-all-topics/index.html new file mode 100644 index 0000000000000000000000000000000000000000..902d266217bfd3bd0bab2415bbf432c072c8959b --- /dev/null +++ b/ml-complete-all-topics/index.html @@ -0,0 +1,2386 @@ + + + + + + Machine Learning: Complete Educational Guide + + + +
+ + + + +
+
+

Machine Learning: Complete Educational Guide

+

A comprehensive learning resource for students - from fundamentals to advanced concepts

+
+ + +
+
+

1. Introduction to Machine Learning

+ +
+
+

Machine Learning is teaching computers to learn from experience, just like humans do. Instead of programming every rule, we let the computer discover patterns in data and make decisions on its own.

+ +
+
Key Concepts
+
    +
  • Learning from data instead of explicit programming
  • +
  • Three types: Supervised, Unsupervised, Reinforcement
  • +
  • Powers Netflix recommendations, Face ID, and more
  • +
  • Requires: Data, Algorithm, and Computing Power
  • +
+
+ +

Understanding Machine Learning

+

Imagine teaching a child to recognize animals. You show them pictures of cats and dogs, telling them which is which. After seeing many examples, the child learns to identify new animals they've never seen before. Machine Learning works the same way!

+ +

The Three Types of Learning:

+
    +
  1. Supervised Learning: Learning with a teacher. You provide labeled examples (like "this is a cat", "this is a dog"), and the model learns to predict labels for new data.
  2. +
  3. Unsupervised Learning: Learning without labels. The model finds hidden patterns on its own, like grouping similar customers together.
  4. +
  5. Reinforcement Learning: Learning by trial and error. The model tries actions and learns from rewards/punishments, like teaching a robot to walk.
  6. +
+ +
+
💡 Key Insight
+
+ ML is not magic! It's mathematics + statistics + computer science working together to find patterns in data. +
+
+ +

Real-World Applications

+
    +
  • Netflix: Recommends shows based on what you've watched
  • +
  • Face ID: Recognizes your face to unlock your phone
  • +
  • Gmail: Filters spam emails automatically
  • +
  • Google Maps: Predicts traffic and suggests fastest routes
  • +
  • Voice Assistants: Understands and responds to your speech
  • +
+ +
+
✓ Why ML Matters Today
+
+ We generate 2.5 quintillion bytes of data every day! ML helps make sense of this massive data to solve problems that were impossible before. +
+
+
+
+ + +
+
+

2. Linear Regression

+ +
+
+

Linear Regression is one of the simplest and most powerful techniques for predicting continuous values. It finds the "best fit line" through data points.

+ +
+
Key Concepts
+
    +
  • Predicts continuous values (prices, temperatures, etc.)
  • +
  • Finds the straight line that best fits the data
  • +
  • Uses equation: y = mx + c
  • +
  • Minimizes prediction errors
  • +
+
+ +

Understanding Linear Regression

+

Think of it like this: You want to predict house prices based on size. If you plot size vs. price on a graph, you'll see points scattered around. Linear regression draws the "best" line through these points that you can use to predict prices for houses of any size.

+ +
+ The Linear Equation: + y = mx + c +
where:
y = predicted value (output)
x = input feature
m = slope (how steep the line is)
c = intercept (where line crosses y-axis)
+
+ +

Example: Predicting Salary from Experience

+

Let's say we have data about employees' years of experience and their salaries:

+ + + + + + + + + + + + + + + + +
Experience (years)Salary ($k)
139.8
248.9
357.0
468.3
577.9
685.0
+ +

We can find a line (y = 7.5x + 32) that predicts: Someone with 7 years experience will earn approximately $84.5k.

+ +
+
+ +
+

Figure 1: Scatter plot showing experience vs. salary with the best fit line

+
+ +
+
+ + +
+
+ + +
+
+ +
+ Cost Function (Mean Squared Error): + MSE = Σ(y_actual - y_predicted)² / n +
This measures how wrong our predictions are. Lower MSE = better fit! +
+ +
+
💡 Key Insight
+
+ The "best fit line" is the one that minimizes the total error between actual points and predicted points. We square the errors so positive and negative errors don't cancel out. +
+
+ +
+
⚠️ Common Mistake
+
+ Linear regression assumes a straight-line relationship. If your data curves, you need polynomial regression or other techniques! +
+
+ +

Step-by-Step Process

+
    +
  1. Collect data with input (x) and output (y) pairs
  2. +
  3. Plot the points on a graph
  4. +
  5. Find values of m and c that minimize prediction errors
  6. +
  7. Use the equation y = mx + c to predict new values
  8. +
+
+
+ + +
+
+

3. Gradient Descent

+ +
+
+

Gradient Descent is the optimization algorithm that helps us find the best values for our model parameters (like m and c in linear regression). Think of it as rolling a ball downhill to find the lowest point.

+ +
+
Key Concepts
+
    +
  • Optimization algorithm to minimize loss function
  • +
  • Takes small steps in the direction of steepest descent
  • +
  • Learning rate controls step size
  • +
  • Stops when it reaches the minimum (convergence)
  • +
+
+ +

Understanding Gradient Descent

+

Imagine you're hiking down a mountain in thick fog. You can't see the bottom, but you can feel the slope under your feet. The smart strategy? Always step in the steepest downward direction. That's exactly what gradient descent does with mathematical functions!

+ +
+
💡 The Mountain Analogy
+
+ Your position on the mountain = current parameter values (m, c)
+ Your altitude = loss/error
+ Goal = reach the valley (minimum loss)
+ Gradient = tells you which direction is steepest +
+
+ +
+ Gradient Descent Update Rule: + θ_new = θ_old - α × ∇J(θ) +
where:
θ = parameters (m, c)
α = learning rate (step size)
∇J(θ) = gradient (direction and steepness)
+
+ +

The Learning Rate (α)

+

The learning rate is like your step size when walking down the mountain:

+
    +
  • Too small: You take tiny steps and it takes forever to reach the bottom
  • +
  • Too large: You take huge leaps and might jump over the valley or even go uphill!
  • +
  • Just right: You make steady progress toward the minimum
  • +
+ +
+
+ +
+

Figure 2: Loss surface showing gradient descent path to minimum

+
+ +
+
+ + +
+
+ + +
+
+ +
+ Gradients for Linear Regression: + ∂MSE/∂m = (2/n) × Σ(ŷ - y) × x
+ ∂MSE/∂c = (2/n) × Σ(ŷ - y) +
These tell us how much to adjust m and c +
+ +

Types of Gradient Descent

+
    +
  1. Batch Gradient Descent: Uses all data points for each update. Accurate but slow for large datasets.
  2. +
  3. Stochastic Gradient Descent (SGD): Uses one random data point per update. Fast but noisy.
  4. +
  5. Mini-batch Gradient Descent: Uses small batches (e.g., 32 points). Best of both worlds!
  6. +
+ +
+
⚠️ Watch Out!
+
+ Gradient descent can get stuck in local minima (small valleys) instead of finding the global minimum (deepest valley). This is more common with complex, non-convex loss functions. +
+
+ +

Convergence Criteria

+

How do we know when to stop? We stop when:

+
    +
  • Loss stops decreasing significantly (e.g., change < 0.0001)
  • +
  • Gradients become very small (near zero)
  • +
  • We reach maximum iterations (e.g., 1000 steps)
  • +
+
+
+ + +
+
+

4. Logistic Regression

+ +
+
+

Logistic Regression is used for binary classification - when you want to predict categories (yes/no, spam/not spam, disease/healthy) not numbers. Despite its name, it's a classification algorithm!

+ +
+
Key Concepts
+
    +
  • Binary classification (2 classes: 0 or 1)
  • +
  • Uses sigmoid function to output probabilities
  • +
  • Output is always between 0 and 1
  • +
  • Uses log loss (cross-entropy) instead of MSE
  • +
+
+ +

Why Not Linear Regression?

+

Imagine using linear regression (y = mx + c) for classification. The problems:

+
    +
  • Can predict values < 0 or > 1 (not valid probabilities!)
  • +
  • Sensitive to outliers pulling the line
  • +
  • No natural threshold for decision making
  • +
+ +
+
⚠️ The Problem
+
+ Linear regression: ŷ = mx + c can give ANY value (-∞ to +∞)
+ Classification needs: probability between 0 and 1 +
+
+ +

Enter the Sigmoid Function

+

The sigmoid function σ(z) squashes any input into the range [0, 1], making it perfect for probabilities!

+ +
+ Sigmoid Function: + σ(z) = 1 / (1 + e^(-z)) +
where:
z = w·x + b (linear combination)
σ(z) = probability (always between 0 and 1)
e ≈ 2.718 (Euler's number)
+
+ +

Sigmoid Properties:

+
    +
  • Input: Any real number (-∞ to +∞)
  • +
  • Output: Always between 0 and 1
  • +
  • Shape: S-shaped curve
  • +
  • At z=0: σ(0) = 0.5 (middle point)
  • +
  • As z→∞: σ(z) → 1
  • +
  • As z→-∞: σ(z) → 0
  • +
+ +
+
+ +
+

Figure: Sigmoid function transforms linear input to probability

+
+ +

Logistic Regression Formula

+
+ Complete Process: + 1. Linear combination: z = w·x + b
+ 2. Sigmoid transformation: p = σ(z) = 1/(1 + e^(-z))
+ 3. Decision: if p ≥ 0.5 → Class 1, else → Class 0 +
+ +

Example: Height Classification

+

Let's classify people as "Tall" (1) or "Not Tall" (0) based on height:

+ + + + + + + + + + + + + + + + + +
Height (cm)LabelProbability
1500 (Not Tall)0.2
16000.35
17000.5
1801 (Tall)0.65
19010.8
20010.9
+ +
+
+ +
+

Figure: Logistic regression with decision boundary at 0.5

+
+ +

Log Loss (Cross-Entropy)

+

We can't use MSE for logistic regression because it creates a non-convex optimization surface (multiple local minima). Instead, we use log loss:

+ +
+ Log Loss for Single Sample: + L(y, p) = -[y·log(p) + (1-y)·log(1-p)] +
where:
y = actual label (0 or 1)
p = predicted probability
+
+ +

Understanding Log Loss:

+

Case 1: Actual y=1, Predicted p=0.9

+

Loss = -[1·log(0.9) + 0·log(0.1)] = -log(0.9) = 0.105 ✓ Low loss (good!)

+ +

Case 2: Actual y=1, Predicted p=0.1

+

Loss = -[1·log(0.1) + 0·log(0.9)] = -log(0.1) = 2.303 ✗ High loss (bad!)

+ +

Case 3: Actual y=0, Predicted p=0.1

+

Loss = -[0·log(0.1) + 1·log(0.9)] = -log(0.9) = 0.105 ✓ Low loss (good!)

+ +
+
💡 Why Log Loss Works
+
+ Log loss heavily penalizes confident wrong predictions! If you predict 0.99 but the answer is 0, you get a huge penalty. This encourages the model to be accurate AND calibrated. +
+
+ +

Training with Gradient Descent

+

Just like linear regression, we use gradient descent to optimize weights:

+ +
+ Gradient for Logistic Regression: + ∂Loss/∂w = (p - y)·x
+ ∂Loss/∂b = (p - y) +
Update: w = w - α·∂Loss/∂w +
+ +
+
✅ Key Takeaway
+
+ Logistic regression = Linear regression + Sigmoid function + Log loss. It's called "regression" for historical reasons, but it's actually for classification! +
+
+
+
+ + +
+
+

5. Support Vector Machines (SVM)

+ +
+
+ +

What is SVM?

+

Support Vector Machine (SVM) is a powerful supervised machine learning algorithm used for both classification and regression tasks. Unlike logistic regression which just needs any line that separates the classes, SVM finds the BEST decision boundary - the one with the maximum margin between classes.

+ +
+
Key Concepts
+
    +
  • Finds the best decision boundary with maximum margin
  • +
  • Support vectors are critical points that define the margin
  • +
  • Score is proportional to distance from boundary
  • +
  • Only support vectors matter - other points don't affect boundary
  • +
+
+ +
+
💡 Key Insight
+
+ SVM doesn't just want w·x + b > 0, it wants every point to be confidently far from the boundary. The score is directly proportional to the distance from the decision boundary! +
+
+ + +

Dataset and Example

+

Let's work with a simple 2D dataset to understand SVM:

+ + + + + + + + + + + + + + + + + + +
PointX₁X₂Class
A27+1
B38+1
C47+1
D62-1
E73-1
F82-1
+ +

Initial parameters: w₁ = 1, w₂ = 1, b = -10

+ + +

Decision Boundary

+

The decision boundary is a line (or hyperplane in higher dimensions) that separates the two classes. It's defined by the equation:

+ +
+ Decision Boundary Equation: + w·x + b = 0 +
where:
w = [w₁, w₂] is the weight vector
x = [x₁, x₂] is the data point
b is the bias term
+
+ +
+
Interpretation
+
    +
  • w·x + b > 0 → point above line → class +1
  • +
  • w·x + b < 0 → point below line → class -1
  • +
  • w·x + b = 0 → exactly on boundary
  • +
+
+ +
+
+ +
+

Figure 3: SVM decision boundary with 6 data points. Hover to see scores.

+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + +

Margin and Support Vectors

+ +
+
📏 Understanding Margin
+
+ The margin is the distance between the decision boundary and the closest points from each class. Support vectors are the points exactly at the margin (with score = ±1). These are the points with "lowest acceptable confidence" and they're the only ones that matter for defining the boundary! +
+
+ +
+ Margin Constraints: + For positive points (yᵢ = +1): w·xᵢ + b ≥ +1
+ For negative points (yᵢ = -1): w·xᵢ + b ≤ -1
+
+ Combined: yᵢ(w·xᵢ + b) ≥ 1
+
+ Margin Width: 2/||w|| +
To maximize margin → minimize ||w|| +
+ +
+
+ +
+

Figure 4: Decision boundary with margin lines and support vectors highlighted in cyan

+
+ + +

Hard Margin vs Soft Margin

+ +

Hard Margin SVM

+

Hard margin SVM requires perfect separation - no points can violate the margin. It works only when data is linearly separable.

+ +
+ Hard Margin Optimization: + minimize (1/2)||w||²
+ subject to: yᵢ(w·xᵢ + b) ≥ 1 for all i +
+ +
+
⚠️ Hard Margin Limitation
+
+ Hard margin can lead to overfitting if we force perfect separation on noisy data! Real-world data often has outliers and noise. +
+
+ +

Soft Margin SVM

+

Soft margin SVM allows some margin violations, making it more practical for real-world data. It balances margin maximization with allowing some misclassifications.

+ +
+ Soft Margin Cost Function: + Cost = (1/2)||w||² + C·Σ max(0, 1 - yᵢ(w·xᵢ + b))
+       ↓                           ↓
+ Maximize margin      Hinge Loss
+                           (penalize violations) +
+ + +

The C Parameter

+

The C parameter controls the trade-off between maximizing the margin and minimizing classification errors. It acts like regularization in other ML algorithms.

+ +
+
Effects of C Parameter
+
    +
  • Small C (0.1 or 1): Wider margin, more violations allowed, better generalization, use when data is noisy
  • +
  • Large C (1000): Narrower margin, fewer violations, classify everything correctly, risk of overfitting, use when data is clean
  • +
+
+ +
+
+ +
+

Figure 5: Effect of C parameter on margin and violations

+
+ +
+
+ + +

Slide to see: 0.1 → 1 → 10 → 1000

+
+
+
+
Margin Width
+
2.00
+
+
+
Violations
+
0
+
+
+
+ + +

Training Algorithm

+

SVM can be trained using gradient descent. For each training sample (xᵢ, yᵢ), we check if it violates the margin and update weights accordingly.

+ +
+ Update Rules:
+
+ Case 1: No violation (yᵢ(w·xᵢ + b) ≥ 1)
+   w = w - η·w  (just regularization)
+   b = b
+
+ Case 2: Violation (yᵢ(w·xᵢ + b) < 1)
+   w = w - η(w - C·yᵢ·xᵢ)
+   b = b + η·C·yᵢ
+
+ where η = learning rate (e.g., 0.01) +
+ +
+
+ +
+

Figure 6: SVM training visualization - step through each point

+
+ +
+
+ + + +
+
+
Step: 0 / 6
+
Current Point: -
+
w = [0.00, 0.00]
+
b = 0.00
+
Violation: -
+
+
+ +
+
📝 Example Calculation (Point A)
+
+ A = (2, 7), y = +1

+ Check: y(w·x + b) = 1(0 + 0 + 0) = 0 < 1 ❌ Violation!

+ Update:
+ wnew = [0, 0] - 0.01(0 - 1·1·[2, 7])
+      = [0.02, 0.07]

+ bnew = 0 + 0.01·1·1 = 0.01 +
+
+ + +

SVM Kernels (Advanced)

+

Real-world data is often not linearly separable. Kernels transform data to higher dimensions where a linear boundary exists, which appears non-linear in the original space!

+ +
+
💡 The Kernel Trick
+
+ Kernels let us solve non-linear problems without explicitly computing high-dimensional features! They compute similarity between points in transformed space efficiently. +
+
+ +
+ Three Main Kernels:
+
+ 1. Linear Kernel
+ K(x₁, x₂) = x₁·x₂
+ Use case: Linearly separable data
+
+ 2. Polynomial Kernel (degree 2)
+ K(x₁, x₂) = (x₁·x₂ + 1)²
+ Use case: Curved boundaries, circular patterns
+
+ 3. RBF / Gaussian Kernel
+ K(x₁, x₂) = e^(-γ||x₁-x₂||²)
+ Use case: Complex non-linear patterns
+ Most popular in practice! +
+ +
+
+ +
+

Figure 7: Kernel comparison on non-linear data

+
+ +
+
+ +
+ + + +
+
+ +
+ + +

Key Formulas Summary

+ +
+ Essential SVM Formulas:
+
+ 1. Decision Boundary: w·x + b = 0
+
+ 2. Classification Rule: sign(w·x + b)
+
+ 3. Margin Width: 2/||w||
+
+ 4. Hard Margin Optimization:
+    minimize (1/2)||w||²
+    subject to yᵢ(w·xᵢ + b) ≥ 1
+
+ 5. Soft Margin Cost:
+    (1/2)||w||² + C·Σ max(0, 1 - yᵢ(w·xᵢ + b))
+
+ 6. Hinge Loss: max(0, 1 - yᵢ(w·xᵢ + b))
+
+ 7. Update Rules (if violation):
+    w = w - η(w - C·yᵢ·xᵢ)
+    b = b + η·C·yᵢ
+
+ 8. Kernel Functions:
+    Linear: K(x₁, x₂) = x₁·x₂
+    Polynomial: K(x₁, x₂) = (x₁·x₂ + 1)^d
+    RBF: K(x₁, x₂) = e^(-γ||x₁-x₂||²) +
+ + +

Practical Insights

+ +
+
✅ Why SVM is Powerful
+
+ SVM only cares about support vectors - the points closest to the boundary. Other points don't affect the decision boundary at all! This makes it memory efficient and robust. +
+
+ +
+
When to Use SVM
+
    +
  • Small to medium datasets (works great up to ~10,000 samples)
  • +
  • High-dimensional data (even more features than samples!)
  • +
  • Clear margin of separation exists between classes
  • +
  • Need interpretable decision boundary
  • +
+
+ +

Advantages

+
    +
  • Effective in high dimensions: Works well even when features > samples
  • +
  • Memory efficient: Only stores support vectors, not entire dataset
  • +
  • Versatile: Different kernels for different data patterns
  • +
  • Robust: Works well with clear margin of separation
  • +
+ +

Disadvantages

+
    +
  • Slow on large datasets: Training time grows quickly with >10k samples
  • +
  • No probability estimates: Doesn't directly provide confidence scores
  • +
  • Kernel choice: Requires expertise to select right kernel
  • +
  • Feature scaling: Very sensitive to feature scales
  • +
+ + +

Real-World Example: Email Spam Classification

+ +
+
📧 Email Spam Detection
+

Imagine we have emails with two features:

+
    +
  • x₁ = number of promotional words ("free", "buy", "limited")
  • +
  • x₂ = number of capital letters
  • +
+

+ SVM finds the widest "road" between spam and non-spam emails. Support vectors are the emails closest to this road - they're the trickiest cases that define our boundary! An email far from the boundary is clearly spam or clearly legitimate. +

+
+ +
+
🎯 Key Takeaway
+
+ Unlike other algorithms that try to classify all points correctly, SVM focuses on the decision boundary. It asks: "What's the safest road I can build between these two groups?" The answer: Make it as wide as possible! +
+
+
+
+ + +
+
+

6. K-Nearest Neighbors (KNN)

+ +
+
+

K-Nearest Neighbors is the simplest machine learning algorithm! To classify a new point, just look at its K nearest neighbors and take a majority vote. No training required!

+ +
+
Key Concepts
+
    +
  • Lazy learning: No training phase, just memorize data
  • +
  • K = number of neighbors to consider
  • +
  • Uses distance metrics (Euclidean, Manhattan)
  • +
  • Classification: majority vote | Regression: average
  • +
+
+ +

How KNN Works

+
    +
  1. Choose K: Decide how many neighbors (e.g., K=3)
  2. +
  3. Calculate distance: Find distance from new point to all training points
  4. +
  5. Find K nearest: Select K points with smallest distances
  6. +
  7. Vote: Majority class wins (or take average for regression)
  8. +
+ +

Distance Metrics

+ +
+ Euclidean Distance (straight line): + d = √[(x₁-x₂)² + (y₁-y₂)²] +
Like measuring with a ruler - shortest path +
+ +
+ Manhattan Distance (city blocks): + d = |x₁-x₂| + |y₁-y₂| +
Like walking on city grid - only horizontal/vertical +
+ +
+
+ +
+

Figure: KNN classification - drag the test point to see predictions

+
+ +
+
+ + +
+
+ +
+ + +
+
+
+ +

Worked Example

+

Test point at (2.5, 2.5), K=3:

+ + + + + + + + + + + + + +
PointPositionClassDistance
A(1.0, 2.0)Orange1.80
B(0.9, 1.7)Orange2.00
C(1.5, 2.5)Orange1.00 ← nearest!
D(4.0, 5.0)Yellow3.35
E(4.2, 4.8)Yellow3.15
F(3.8, 5.2)Yellow3.12
+ +

3-Nearest Neighbors: C (orange), A (orange), B (orange)

+

Vote: 3 orange, 0 yellow → Prediction: Orange 🟠

+ +

Choosing K

+
    +
  • K=1: Very sensitive to noise, overfits
  • +
  • Small K (3,5): Flexible boundaries, can capture local patterns
  • +
  • Large K (>10): Smoother boundaries, more stable but might underfit
  • +
  • Odd K: Avoids ties in binary classification
  • +
  • Rule of thumb: K = √n (where n = number of training samples)
  • +
+ +
+
⚠️ Critical: Feature Scaling!
+
+ Always scale features before using KNN! If one feature has range [0, 1000] and another [0, 1], the large feature dominates distance calculations. Use StandardScaler or MinMaxScaler. +
+
+ +

Advantages

+
    +
  • ✓ Simple to understand and implement
  • +
  • ✓ No training time (just stores data)
  • +
  • ✓ Works with any number of classes
  • +
  • ✓ Can learn complex decision boundaries
  • +
  • ✓ Naturally handles multi-class problems
  • +
+ +

Disadvantages

+
    +
  • ✗ Slow prediction (compares to ALL training points)
  • +
  • ✗ High memory usage (stores entire dataset)
  • +
  • ✗ Sensitive to feature scaling
  • +
  • ✗ Curse of dimensionality (struggles with many features)
  • +
  • ✗ Sensitive to irrelevant features
  • +
+ +
+
💡 When to Use KNN
+
+ KNN works best with small to medium datasets (<10,000 samples) with few features (<20). Great for recommendation systems, pattern recognition, and as a baseline to compare other models! +
+
+
+
+ +
+
+

7. Model Evaluation

+ +
+
+

How do we know if our model is good? Model evaluation provides metrics to measure performance and identify problems!

+ +
+
Key Metrics
+
    +
  • Confusion Matrix: Shows all prediction outcomes
  • +
  • Accuracy, Precision, Recall, F1-Score
  • +
  • ROC Curve & AUC: Performance across thresholds
  • +
  • R² Score: For regression problems
  • +
+
+ +

Confusion Matrix

+

The confusion matrix shows all possible outcomes of binary classification:

+ +
+ Confusion Matrix Structure: +
+                Predicted
+                Pos    Neg
+Actual  Pos     TP     FN
+        Neg     FP     TN
+
+ +

Definitions:

+
    +
  • True Positive (TP): Correctly predicted positive
  • +
  • True Negative (TN): Correctly predicted negative
  • +
  • False Positive (FP): Wrongly predicted positive (Type I error)
  • +
  • False Negative (FN): Wrongly predicted negative (Type II error)
  • +
+ +
+
+ +
+

Figure: Confusion matrix for spam detection (TP=600, FP=100, FN=300, TN=900)

+
+ +

Classification Metrics

+ +
+ Accuracy: + Accuracy = (TP + TN) / (TP + TN + FP + FN) +
Percentage of correct predictions overall +
+ +

Example: (600 + 900) / (600 + 900 + 100 + 300) = 1500/1900 = 0.789 (78.9%)

+ +
+
⚠️ Accuracy Paradox
+
+ Accuracy misleads on imbalanced data! If 99% emails are not spam, a model that always predicts "not spam" gets 99% accuracy but is useless! +
+
+ +
+ Precision: + Precision = TP / (TP + FP) +
"Of all predicted positives, how many are actually positive?" +
+ +

Example: 600 / (600 + 100) = 600/700 = 0.857 (85.7%)

+

Use when: False positives are costly (e.g., spam filter - don't want to block legitimate emails)

+ +
+ Recall (Sensitivity, TPR): + Recall = TP / (TP + FN) +
"Of all actual positives, how many did we catch?" +
+ +

Example: 600 / (600 + 300) = 600/900 = 0.667 (66.7%)

+

Use when: False negatives are costly (e.g., disease detection - can't miss sick patients)

+ +
+ F1-Score: + F1 = 2 × (Precision × Recall) / (Precision + Recall) +
Harmonic mean - balances precision and recall +
+ +

Example: 2 × (0.857 × 0.667) / (0.857 + 0.667) = 0.750 (75.0%)

+ +

ROC Curve & AUC

+

The ROC (Receiver Operating Characteristic) curve shows model performance across ALL possible thresholds!

+ +
+ ROC Components: + TPR (True Positive Rate) = TP / (TP + FN) = Recall
+ FPR (False Positive Rate) = FP / (FP + TN) +
Plot: FPR (x-axis) vs TPR (y-axis) +
+ +
+
+ +
+

Figure: ROC curve - slide threshold to see trade-off

+
+ +
+
+ + +
+
+ +

Understanding ROC:

+
    +
  • Top-left corner (0, 1): Perfect classifier
  • +
  • Diagonal line: Random guessing
  • +
  • Above diagonal: Better than random
  • +
  • Below diagonal: Worse than random (invert predictions!)
  • +
+ +
+ AUC (Area Under Curve): + AUC = Area under ROC curve +
AUC = 1.0: Perfect | AUC = 0.5: Random | AUC > 0.8: Good +
+ +

Regression Metrics: R² Score

+

For regression problems, R² (coefficient of determination) measures how well the model explains variance:

+ +
+ R² Formula: + R² = 1 - (SS_res / SS_tot)
+
+ SS_res = Σ(y - ŷ)² (sum of squared residuals)
+ SS_tot = Σ(y - ȳ)² (total sum of squares)
+
ȳ = mean of actual values +
+ +

Interpreting R²:

+
    +
  • R² = 1.0: Perfect fit (model explains 100% of variance)
  • +
  • R² = 0.7: Model explains 70% of variance (pretty good!)
  • +
  • R² = 0.0: Model no better than just using the mean
  • +
  • R² < 0: Model worse than mean (something's very wrong!)
  • +
+ +
+
+ +
+

Figure: R² calculation on height-weight regression

+
+ +
+
✅ Choosing the Right Metric
+
+ Balanced data: Use accuracy
+ Imbalanced data: Use F1-score, precision, or recall
+ Medical diagnosis: Prioritize recall (catch all diseases)
+ Spam filter: Prioritize precision (don't block legitimate emails)
+ Regression: Use R², RMSE, or MAE +
+
+
+
+ +
+
+

8. Regularization

+ +
+
+

Regularization prevents overfitting by penalizing complex models. It adds a "simplicity constraint" to force the model to generalize better!

+ +
+
Key Concepts
+
    +
  • Prevents overfitting by penalizing large coefficients
  • +
  • L1 (Lasso): Drives coefficients to zero, feature selection
  • +
  • L2 (Ridge): Shrinks coefficients proportionally
  • +
  • λ controls penalty strength
  • +
+
+ +

The Overfitting Problem

+

Without regularization, models can learn training data TOO well:

+
    +
  • Captures noise instead of patterns
  • +
  • High training accuracy, poor test accuracy
  • +
  • Large coefficient values
  • +
  • Model too complex for the problem
  • +
+ +
+
⚠️ Overfitting Example
+
+ Imagine fitting a 10th-degree polynomial to 12 data points. It perfectly fits training data (even noise) but fails on new data. Regularization prevents this! +
+
+ +

The Regularization Solution

+

Instead of minimizing just the loss, we minimize: Loss + Penalty

+ +
+ Regularized Cost Function: + Cost = Loss + λ × Penalty(θ) +
where:
θ = model parameters (weights)
λ = regularization strength
Penalty = function of parameter magnitudes
+
+ +

L1 Regularization (Lasso)

+
+ L1 Penalty: + Cost = MSE + λ × Σ|θᵢ| +
Sum of absolute values of coefficients +
+ +

L1 Effects:

+
    +
  • Feature selection: Drives coefficients to exactly 0
  • +
  • Sparse models: Only important features remain
  • +
  • Interpretable: Easy to see which features matter
  • +
  • Use when: Many features, few are important
  • +
+ +

L2 Regularization (Ridge)

+
+ L2 Penalty: + Cost = MSE + λ × Σθᵢ² +
Sum of squared coefficients +
+ +

L2 Effects:

+
    +
  • Shrinks coefficients: Makes them smaller, not zero
  • +
  • Keeps all features: No automatic selection
  • +
  • Smooth predictions: Less sensitive to individual features
  • +
  • Use when: Many correlated features (multicollinearity)
  • +
+ +
+
+ +
+

Figure: Comparing vanilla, L1, and L2 regularization effects

+
+ +
+
+ + +
+
+ +

The Lambda (λ) Parameter

+
    +
  • λ = 0: No regularization (original model, risk of overfitting)
  • +
  • Small λ (0.01): Weak penalty, slight regularization
  • +
  • Medium λ (1): Balanced, good generalization
  • +
  • Large λ (100): Strong penalty, risk of underfitting
  • +
+ +
+
💡 L1 vs L2: Quick Guide
+
+ Use L1 when:
+ • You suspect many features are irrelevant
+ • You want automatic feature selection
+ • You need interpretability
+
+ Use L2 when:
+ • All features might be useful
+ • Features are highly correlated
+ • You want smooth, stable predictions
+
+ Elastic Net: Combines both L1 and L2! +
+
+ +

Practical Example

+

Predicting house prices with 10 features (size, bedrooms, age, etc.):

+ +

Without regularization: All features have large, varying coefficients. Model overfits noise.

+ +

With L1: Only 4 features remain (size, location, bedrooms, age). Others set to 0. Simpler, more interpretable!

+ +

With L2: All features kept but coefficients shrunk. More stable predictions, handles correlated features well.

+ +
+
✅ Key Takeaway
+
+ Regularization is like adding a "simplicity tax" to your model. Complex models pay more tax, encouraging simpler solutions that generalize better! +
+
+
+
+ +
+
+

9. Bias-Variance Tradeoff

+ +
+
+

Every model makes two types of errors: bias and variance. The bias-variance tradeoff is the fundamental challenge in machine learning - we must balance them!

+ +
+
Key Concepts
+
    +
  • Bias = systematic error (underfitting)
  • +
  • Variance = sensitivity to training data (overfitting)
  • +
  • Can't minimize both simultaneously
  • +
  • Goal: Find the sweet spot
  • +
+
+ +

Understanding Bias

+

Bias is the error from overly simplistic assumptions. High bias causes underfitting.

+ +

Characteristics of High Bias:

+
    +
  • Model too simple for the problem
  • +
  • High error on training data
  • +
  • High error on test data
  • +
  • Can't capture underlying patterns
  • +
  • Example: Using a straight line for curved data
  • +
+ +
+
🎯 High Bias Example
+
+ Trying to fit a parabola with a straight line. No matter how much training data you have, a line can't capture the curve. That's bias! +
+
+ +

Understanding Variance

+

Variance is the error from sensitivity to small fluctuations in training data. High variance causes overfitting.

+ +

Characteristics of High Variance:

+
    +
  • Model too complex for the problem
  • +
  • Very low error on training data
  • +
  • High error on test data
  • +
  • Captures noise as if it were pattern
  • +
  • Example: Using 10th-degree polynomial for simple data
  • +
+ +
+
📊 High Variance Example
+
+ A wiggly curve that passes through every training point perfectly, including outliers. Change one data point and the entire curve changes dramatically. That's variance! +
+
+ +

The Tradeoff

+
+ Total Error Decomposition: + Total Error = Bias² + Variance + Irreducible Error +
Irreducible error = noise in data (can't be eliminated) +
+ +

The tradeoff:

+
    +
  • Decrease bias → Increase variance (more complex model)
  • +
  • Decrease variance → Increase bias (simpler model)
  • +
  • Goal: Minimize total error by balancing both
  • +
+ +
+
+ +
+

Figure: Three models showing underfitting, good fit, and overfitting

+
+ +

The Driving Test Analogy

+

Think of learning to drive:

+ +
+
Driving Test Analogy
+
    +
  • + High Bias (Underfitting):
    + Failed practice tests, failed real test
    + → Can't learn to drive at all +
  • +
  • + Good Balance:
    + Passed practice tests, passed real test
    + → Actually learned to drive! +
  • +
  • + High Variance (Overfitting):
    + Perfect on practice tests, failed real test
    + → Memorized practice, didn't truly learn +
  • +
+
+ +

How to Find the Balance

+ +

Reduce Bias (if underfitting):

+
    +
  • Use more complex model (more features, higher degree polynomial)
  • +
  • Add more features
  • +
  • Reduce regularization
  • +
  • Train longer (more iterations)
  • +
+ +

Reduce Variance (if overfitting):

+
    +
  • Use simpler model (fewer features, lower degree)
  • +
  • Get more training data
  • +
  • Add regularization (L1, L2)
  • +
  • Use cross-validation
  • +
  • Feature selection or dimensionality reduction
  • +
+ +

Model Complexity Curve

+
+
+ +
+

Figure: Error vs model complexity - find the sweet spot

+
+ +
+
💡 Detecting Bias vs Variance
+
+ High Bias:
+ Training error: High 🔴
+ Test error: High 🔴
+ Gap: Small
+
+ High Variance:
+ Training error: Low 🟢
+ Test error: High 🔴
+ Gap: Large ⚠️
+
+ Good Model:
+ Training error: Low 🟢
+ Test error: Low 🟢
+ Gap: Small ✓ +
+
+ +
+
✅ Key Takeaway
+
+ The bias-variance tradeoff is unavoidable. You can't have zero bias AND zero variance. The art of machine learning is finding the sweet spot where total error is minimized! +
+
+
+
+ +
+
+

10. Cross-Validation

+ +
+
+

Cross-validation gives more reliable performance estimates by testing your model on multiple different splits of the data!

+ +
+
Key Concepts
+
    +
  • Splits data into K folds
  • +
  • Trains K times, each with different test fold
  • +
  • Averages results for robust estimate
  • +
  • Reduces variance in performance estimate
  • +
+
+ +

The Problem with Simple Train-Test Split

+

With a single 80-20 split:

+
    +
  • Performance depends on which data you randomly picked
  • +
  • Might get lucky/unlucky with the split
  • +
  • 20% of data wasted (not used for training)
  • +
  • One number doesn't tell you about variance
  • +
+ +
+
⚠️ Single Split Problem
+
+ You test once and get 85% accuracy. Is that good? Or did you just get lucky with an easy test set? Without multiple tests, you don't know! +
+
+ +

K-Fold Cross-Validation

+

The solution: Split data into K folds and test K times!

+ +
+ K-Fold Algorithm: + 1. Split data into K equal folds
+ 2. For i = 1 to K:
+    - Use fold i as test set
+    - Use all other folds as training set
+    - Train model and record accuracyᵢ
+ 3. Final score = mean(accuracy₁, ..., accuracyₖ)
+ 4. Also report std dev for confidence +
+ +
+
+ +
+

Figure: 3-Fold Cross-Validation - each fold serves as test set once

+
+ +

Example: 3-Fold CV

+

Dataset with 12 samples (A through L), split into 3 folds:

+ + + + + + + + + + + + + + + + + + + + + + + + + +
FoldTest SetTraining SetAccuracy
1A, B, C, DE, F, G, H, I, J, K, L0.96
2E, F, G, HA, B, C, D, I, J, K, L0.84
3I, J, K, LA, B, C, D, E, F, G, H0.90
+ +
+ Final Score: + Mean = (0.96 + 0.84 + 0.90) / 3 = 0.90 (90%)
+ Std Dev = 0.049
+
+ Report: 90% ± 5% +
+ +

Choosing K

+
    +
  • K=5: Most common, good balance
  • +
  • K=10: More reliable, standard in research
  • +
  • K=n (Leave-One-Out): Maximum data usage, but expensive
  • +
  • Larger K: More computation, less bias, more variance
  • +
  • Smaller K: Less computation, more bias, less variance
  • +
+ +

Stratified K-Fold

+

For classification with imbalanced classes, use stratified K-fold to maintain class proportions in each fold!

+ +
+
💡 Example
+
+ Dataset: 80% class 0, 20% class 1
+
+ Regular K-fold: One fold might have 90% class 0, another 70%
+ Stratified K-fold: Every fold has 80% class 0, 20% class 1 ✓ +
+
+ +

Leave-One-Out Cross-Validation (LOOCV)

+

Special case where K = n (number of samples):

+
    +
  • Each sample is test set once
  • +
  • Train on n-1 samples, test on 1
  • +
  • Repeat n times
  • +
  • Maximum use of training data
  • +
  • Very expensive for large datasets
  • +
+ +

Benefits of Cross-Validation

+
    +
  • ✓ More reliable performance estimate
  • +
  • ✓ Uses all data for both training and testing
  • +
  • ✓ Reduces variance in estimate
  • +
  • ✓ Detects overfitting (high variance across folds)
  • +
  • ✓ Better for small datasets
  • +
+ +

Drawbacks

+
    +
  • ✗ Computationally expensive (train K times)
  • +
  • ✗ Not suitable for time series (can't shuffle)
  • +
  • ✗ Still need final train-test split for final model
  • +
+ +
+
✅ Best Practice
+
+ 1. Use cross-validation to evaluate models and tune hyperparameters
+ 2. Once you pick the best model, train on ALL training data
+ 3. Test once on held-out test set for final unbiased estimate
+
+ Never use test set during cross-validation! +
+
+
+
+ +
+
+

11. Data Preprocessing

+ +
+
+

Raw data is messy! Data preprocessing cleans and transforms data into a format that machine learning algorithms can use effectively.

+ +
+
Key Steps
+
    +
  • Handle missing values
  • +
  • Encode categorical variables
  • +
  • Scale/normalize features
  • +
  • Split data properly
  • +
+
+ +

1. Handling Missing Values

+

Real-world data often has missing values. We can't just ignore them!

+ +

Strategies:

+
    +
  • Drop rows: If only few values missing (<5%)
  • +
  • Mean imputation: Replace with column mean (numerical)
  • +
  • Median imputation: Replace with median (robust to outliers)
  • +
  • Mode imputation: Replace with most frequent (categorical)
  • +
  • Forward/backward fill: Use previous/next value (time series)
  • +
  • Predictive imputation: Train model to predict missing values
  • +
+ +
+
⚠️ Warning
+
+ Never drop columns with many missing values without investigation! The missingness itself might be informative (e.g., income not reported might correlate with high income). +
+
+ +

2. Encoding Categorical Variables

+

Most ML algorithms need numerical input. We must convert categories to numbers!

+ +

One-Hot Encoding

+

Creates binary column for each category. Use for nominal data (no order).

+ +
+ Example: + Color: ["Red", "Blue", "Green", "Blue"]
+
+ Becomes three columns:
+ Red:   [1, 0, 0, 0]
+ Blue:  [0, 1, 0, 1]
+ Green: [0, 0, 1, 0] +
+ +

Label Encoding

+

Assigns integer to each category. Use for ordinal data (has order).

+ +
+ Example: + Size: ["Small", "Large", "Medium", "Small"]
+
+ Becomes: [0, 2, 1, 0]
+ (Small=0, Medium=1, Large=2) +
+ +
+
⚠️ Don't Mix Them Up!
+
+ Never use label encoding for nominal data! If you encode ["Red", "Blue", "Green"] as [0, 1, 2], the model thinks Green > Blue > Red, which is meaningless! +
+
+ +

3. Feature Scaling

+

Different features have different scales. Age (0-100) vs Income ($0-$1M). This causes problems!

+ +

Why Scale?

+
    +
  • Gradient descent converges faster
  • +
  • Distance-based algorithms (KNN, SVM) need it
  • +
  • Regularization treats features equally
  • +
  • Neural networks train better
  • +
+ +

StandardScaler (Z-score normalization)

+
+ Formula: + z = (x - μ) / σ +
where:
μ = mean of feature
σ = standard deviation
Result: mean=0, std=1
+
+ +

Example: [10, 20, 30, 40, 50]

+

μ = 30, σ = 15.81

+

Scaled: [-1.26, -0.63, 0, 0.63, 1.26]

+ +

MinMaxScaler

+
+ Formula: + x' = (x - min) / (max - min) +
Result: range [0, 1] +
+ +

Example: [10, 20, 30, 40, 50]

+

Scaled: [0, 0.25, 0.5, 0.75, 1.0]

+ +
+
+ +
+

Figure: Feature distributions before and after scaling

+
+ +

Critical: fit_transform vs transform

+

This is where many beginners make mistakes!

+ +
+ fit_transform():
+ 1. Learns parameters (μ, σ, min, max) from data
+ 2. Transforms the data
+ Use on: Training data ONLY
+
+ transform():
+ 1. Uses already-learned parameters
+ 2. Transforms the data
+ Use on: Test data, new data +
+ +
+
⚠️ DATA LEAKAGE!
+
+ WRONG:
+ scaler.fit(test_data) # Learns from test data!
+
+ CORRECT:
+ scaler.fit(train_data) # Learn from train only
+ train_scaled = scaler.transform(train_data)
+ test_scaled = scaler.transform(test_data)
+
+ If you fit on test data, you're "peeking" at the answers! +
+
+ +

4. Train-Test Split

+

Always split data BEFORE any preprocessing that learns parameters!

+ +
+ Correct Order:
+ 1. Split data → train (80%), test (20%)
+ 2. Handle missing values (fit on train)
+ 3. Encode categories (fit on train)
+ 4. Scale features (fit on train)
+ 5. Train model
+ 6. Test model (using same transformations) +
+ +

Complete Pipeline Example

+
+
+ +
+

Figure: Complete preprocessing pipeline

+
+ +
+
✅ Golden Rules
+
+ 1. Split first! Before any preprocessing
+ 2. Fit on train only! Never on test
+ 3. Transform both! Apply same transformations to test
+ 4. Pipeline everything! Use scikit-learn Pipeline to avoid mistakes
+ 5. Save your scaler! You'll need it for new predictions +
+
+
+
+ +
+
+

12. Loss Functions

+ +
+
+

Loss functions measure how wrong our predictions are. Different problems need different loss functions! The choice dramatically affects what your model learns.

+ +
+
Key Concepts
+
    +
  • Loss = how wrong a single prediction is
  • +
  • Cost = average loss over all samples
  • +
  • Regression: MSE, MAE, RMSE
  • +
  • Classification: Log Loss, Hinge Loss
  • +
+
+ +

Loss Functions for Regression

+ +

Mean Squared Error (MSE)

+
+ Formula: + MSE = (1/n) × Σ(y - ŷ)² +
where:
y = actual value
ŷ = predicted value
n = number of samples
+
+ +
Characteristics:
+
    +
  • Squares errors: Penalizes large errors heavily
  • +
  • Always positive: Minimum is 0 (perfect predictions)
  • +
  • Differentiable: Great for gradient descent
  • +
  • Sensitive to outliers: One huge error dominates
  • +
  • Units: Squared units (harder to interpret)
  • +
+ +

Example: Predictions [12, 19, 32], Actual [10, 20, 30]

+

Errors: [2, -1, 2]

+

Squared: [4, 1, 4]

+

MSE = (4 + 1 + 4) / 3 = 3.0

+ +

Mean Absolute Error (MAE)

+
+ Formula: + MAE = (1/n) × Σ|y - ŷ| +
Absolute value of errors +
+ +
Characteristics:
+
    +
  • Linear penalty: All errors weighted equally
  • +
  • Robust to outliers: One huge error doesn't dominate
  • +
  • Interpretable units: Same units as target
  • +
  • Not differentiable at 0: Slightly harder to optimize
  • +
+ +

Example: Predictions [12, 19, 32], Actual [10, 20, 30]

+

Errors: [2, -1, 2]

+

Absolute: [2, 1, 2]

+

MAE = (2 + 1 + 2) / 3 = 1.67

+ +

Root Mean Squared Error (RMSE)

+
+ Formula: + RMSE = √MSE +
Square root of MSE +
+ +
Characteristics:
+
    +
  • Same units as target: More interpretable than MSE
  • +
  • Still sensitive to outliers: But less than MSE
  • +
  • Common in competitions: Kaggle, etc.
  • +
+ +
+
+ +
+

Figure: Comparing MSE, MAE, and their response to errors

+
+ +

Loss Functions for Classification

+ +

Log Loss (Cross-Entropy)

+
+ Binary Cross-Entropy: + Loss = -(1/n) × Σ[y·log(ŷ) + (1-y)·log(1-ŷ)] +
where:
y ∈ {0, 1} = actual label
ŷ ∈ (0, 1) = predicted probability
+
+ +
Characteristics:
+
    +
  • For probabilities: Output must be [0, 1]
  • +
  • Heavily penalizes confident wrong predictions: Good!
  • +
  • Convex: No local minima, easy to optimize
  • +
  • Probabilistic interpretation: Maximum likelihood
  • +
+ +

Example: y=1 (spam), predicted p=0.9

+

Loss = -[1·log(0.9) + 0·log(0.1)] = -log(0.9) = 0.105 (low, good!)

+ +

Example: y=1 (spam), predicted p=0.1

+

Loss = -[1·log(0.1) + 0·log(0.9)] = -log(0.1) = 2.303 (high, bad!)

+ +

Hinge Loss (for SVM)

+
+ Formula: + Loss = max(0, 1 - y·score) +
where:
y ∈ {-1, +1}
score = w·x + b
+
+ +
Characteristics:
+
    +
  • Margin-based: Encourages confident predictions
  • +
  • Zero loss for correct & confident: When y·score ≥ 1
  • +
  • Linear penalty: For violations
  • +
  • Used in SVM: Maximizes margin
  • +
+ +

When to Use Which Loss?

+ +
+
Regression Problems
+
    +
  • + MSE: Default choice, smooth optimization, use when outliers are errors +
  • +
  • + MAE: When you have outliers that are valid data points +
  • +
  • + RMSE: When you need interpretable metric in original units +
  • +
  • + Huber Loss: Combines MSE and MAE - best of both worlds! +
  • +
+
+ +
+
Classification Problems
+
    +
  • + Log Loss: Default for binary/multi-class, when you need probabilities +
  • +
  • + Hinge Loss: For SVM, when you want maximum margin +
  • +
  • + Focal Loss: For highly imbalanced datasets +
  • +
+
+ +

Visualizing Loss Curves

+
+
+ +
+

Figure: How different losses respond to errors

+
+ +
+
💡 Impact of Outliers
+
+ Imagine predictions [100, 102, 98, 150] for actuals [100, 100, 100, 100]:
+
+ MSE: (0 + 4 + 4 + 2500) / 4 = 627 ← Dominated by outlier!
+ MAE: (0 + 2 + 2 + 50) / 4 = 13.5 ← More balanced
+
+ MSE is 48× larger because it squares the huge error! +
+
+ +
+
✅ Key Takeaways
+
+ 1. Loss function choice affects what your model learns
+ 2. MSE penalizes large errors more than MAE
+ 3. Use MAE when outliers are valid, MSE when they're errors
+ 4. Log loss for classification with probabilities
+ 5. Always plot your errors to understand what's happening!
+
+ The loss function IS your model's objective! +
+
+ +

🎉 Congratulations!

+

+ You've completed all 12 machine learning topics! You now understand the fundamentals of ML from linear regression to loss functions. Keep practicing and building projects! 🚀 +

+
+
+ +
+
+ + + + \ No newline at end of file diff --git a/ml-complete-all-topics/style.css b/ml-complete-all-topics/style.css new file mode 100644 index 0000000000000000000000000000000000000000..23c062e35bc01825075176de29bb689730d96dcb --- /dev/null +++ b/ml-complete-all-topics/style.css @@ -0,0 +1,1532 @@ +:root { + /* Primitive Color Tokens */ + --color-white: rgba(255, 255, 255, 1); + --color-black: rgba(0, 0, 0, 1); + --color-cream-50: rgba(252, 252, 249, 1); + --color-cream-100: rgba(255, 255, 253, 1); + --color-gray-200: rgba(245, 245, 245, 1); + --color-gray-300: rgba(167, 169, 169, 1); + --color-gray-400: rgba(119, 124, 124, 1); + --color-slate-500: rgba(98, 108, 113, 1); + --color-brown-600: rgba(94, 82, 64, 1); + --color-charcoal-700: rgba(31, 33, 33, 1); + --color-charcoal-800: rgba(38, 40, 40, 1); + --color-slate-900: rgba(19, 52, 59, 1); + --color-teal-300: rgba(50, 184, 198, 1); + --color-teal-400: rgba(45, 166, 178, 1); + --color-teal-500: rgba(33, 128, 141, 1); + --color-teal-600: rgba(29, 116, 128, 1); + --color-teal-700: rgba(26, 104, 115, 1); + --color-teal-800: rgba(41, 150, 161, 1); + --color-red-400: rgba(255, 84, 89, 1); + --color-red-500: rgba(192, 21, 47, 1); + --color-orange-400: rgba(230, 129, 97, 1); + --color-orange-500: rgba(168, 75, 47, 1); + + /* RGB versions for opacity control */ + --color-brown-600-rgb: 94, 82, 64; + --color-teal-500-rgb: 33, 128, 141; + --color-slate-900-rgb: 19, 52, 59; + --color-slate-500-rgb: 98, 108, 113; + --color-red-500-rgb: 192, 21, 47; + --color-red-400-rgb: 255, 84, 89; + --color-orange-500-rgb: 168, 75, 47; + --color-orange-400-rgb: 230, 129, 97; + + /* Background color tokens (Light Mode) */ + --color-bg-1: rgba(59, 130, 246, 0.08); /* Light blue */ + --color-bg-2: rgba(245, 158, 11, 0.08); /* Light yellow */ + --color-bg-3: rgba(34, 197, 94, 0.08); /* Light green */ + --color-bg-4: rgba(239, 68, 68, 0.08); /* Light red */ + --color-bg-5: rgba(147, 51, 234, 0.08); /* Light purple */ + --color-bg-6: rgba(249, 115, 22, 0.08); /* Light orange */ + --color-bg-7: rgba(236, 72, 153, 0.08); /* Light pink */ + --color-bg-8: rgba(6, 182, 212, 0.08); /* Light cyan */ + + /* Semantic Color Tokens (Light Mode) */ + --color-background: var(--color-cream-50); + --color-surface: var(--color-cream-100); + --color-text: var(--color-slate-900); + --color-text-secondary: var(--color-slate-500); + --color-primary: var(--color-teal-500); + --color-primary-hover: var(--color-teal-600); + --color-primary-active: var(--color-teal-700); + --color-secondary: rgba(var(--color-brown-600-rgb), 0.12); + --color-secondary-hover: rgba(var(--color-brown-600-rgb), 0.2); + --color-secondary-active: rgba(var(--color-brown-600-rgb), 0.25); + --color-border: rgba(var(--color-brown-600-rgb), 0.2); + --color-btn-primary-text: var(--color-cream-50); + --color-card-border: rgba(var(--color-brown-600-rgb), 0.12); + --color-card-border-inner: rgba(var(--color-brown-600-rgb), 0.12); + --color-error: var(--color-red-500); + --color-success: var(--color-teal-500); + --color-warning: var(--color-orange-500); + --color-info: var(--color-slate-500); + --color-focus-ring: rgba(var(--color-teal-500-rgb), 0.4); + --color-select-caret: rgba(var(--color-slate-900-rgb), 0.8); + + /* Common style patterns */ + --focus-ring: 0 0 0 3px var(--color-focus-ring); + --focus-outline: 2px solid var(--color-primary); + --status-bg-opacity: 0.15; + --status-border-opacity: 0.25; + --select-caret-light: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23134252' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E"); + --select-caret-dark: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23f5f5f5' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E"); + + /* RGB versions for opacity control */ + --color-success-rgb: 33, 128, 141; + --color-error-rgb: 192, 21, 47; + --color-warning-rgb: 168, 75, 47; + --color-info-rgb: 98, 108, 113; + + /* Typography */ + --font-family-base: "FKGroteskNeue", "Geist", "Inter", -apple-system, + BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + --font-family-mono: "Berkeley Mono", ui-monospace, SFMono-Regular, Menlo, + Monaco, Consolas, monospace; + --font-size-xs: 11px; + --font-size-sm: 12px; + --font-size-base: 14px; + --font-size-md: 14px; + --font-size-lg: 16px; + --font-size-xl: 18px; + --font-size-2xl: 20px; + --font-size-3xl: 24px; + --font-size-4xl: 30px; + --font-weight-normal: 400; + --font-weight-medium: 500; + --font-weight-semibold: 550; + --font-weight-bold: 600; + --line-height-tight: 1.2; + --line-height-normal: 1.5; + --letter-spacing-tight: -0.01em; + + /* Spacing */ + --space-0: 0; + --space-1: 1px; + --space-2: 2px; + --space-4: 4px; + --space-6: 6px; + --space-8: 8px; + --space-10: 10px; + --space-12: 12px; + --space-16: 16px; + --space-20: 20px; + --space-24: 24px; + --space-32: 32px; + + /* Border Radius */ + --radius-sm: 6px; + --radius-base: 8px; + --radius-md: 10px; + --radius-lg: 12px; + --radius-full: 9999px; + + /* Shadows */ + --shadow-xs: 0 1px 2px rgba(0, 0, 0, 0.02); + --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.04), 0 1px 2px rgba(0, 0, 0, 0.02); + --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.04), + 0 2px 4px -1px rgba(0, 0, 0, 0.02); + --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.04), + 0 4px 6px -2px rgba(0, 0, 0, 0.02); + --shadow-inset-sm: inset 0 1px 0 rgba(255, 255, 255, 0.15), + inset 0 -1px 0 rgba(0, 0, 0, 0.03); + + /* Animation */ + --duration-fast: 150ms; + --duration-normal: 250ms; + --ease-standard: cubic-bezier(0.16, 1, 0.3, 1); + + /* Layout */ + --container-sm: 640px; + --container-md: 768px; + --container-lg: 1024px; + --container-xl: 1280px; +} + +/* Dark mode colors */ +@media (prefers-color-scheme: dark) { + :root { + /* RGB versions for opacity control (Dark Mode) */ + --color-gray-400-rgb: 119, 124, 124; + --color-teal-300-rgb: 50, 184, 198; + --color-gray-300-rgb: 167, 169, 169; + --color-gray-200-rgb: 245, 245, 245; + + /* Background color tokens (Dark Mode) */ + --color-bg-1: rgba(29, 78, 216, 0.15); /* Dark blue */ + --color-bg-2: rgba(180, 83, 9, 0.15); /* Dark yellow */ + --color-bg-3: rgba(21, 128, 61, 0.15); /* Dark green */ + --color-bg-4: rgba(185, 28, 28, 0.15); /* Dark red */ + --color-bg-5: rgba(107, 33, 168, 0.15); /* Dark purple */ + --color-bg-6: rgba(194, 65, 12, 0.15); /* Dark orange */ + --color-bg-7: rgba(190, 24, 93, 0.15); /* Dark pink */ + --color-bg-8: rgba(8, 145, 178, 0.15); /* Dark cyan */ + + /* Semantic Color Tokens (Dark Mode) */ + --color-background: var(--color-charcoal-700); + --color-surface: var(--color-charcoal-800); + --color-text: var(--color-gray-200); + --color-text-secondary: rgba(var(--color-gray-300-rgb), 0.7); + --color-primary: var(--color-teal-300); + --color-primary-hover: var(--color-teal-400); + --color-primary-active: var(--color-teal-800); + --color-secondary: rgba(var(--color-gray-400-rgb), 0.15); + --color-secondary-hover: rgba(var(--color-gray-400-rgb), 0.25); + --color-secondary-active: rgba(var(--color-gray-400-rgb), 0.3); + --color-border: rgba(var(--color-gray-400-rgb), 0.3); + --color-error: var(--color-red-400); + --color-success: var(--color-teal-300); + --color-warning: var(--color-orange-400); + --color-info: var(--color-gray-300); + --color-focus-ring: rgba(var(--color-teal-300-rgb), 0.4); + --color-btn-primary-text: var(--color-slate-900); + --color-card-border: rgba(var(--color-gray-400-rgb), 0.2); + --color-card-border-inner: rgba(var(--color-gray-400-rgb), 0.15); + --shadow-inset-sm: inset 0 1px 0 rgba(255, 255, 255, 0.1), + inset 0 -1px 0 rgba(0, 0, 0, 0.15); + --button-border-secondary: rgba(var(--color-gray-400-rgb), 0.2); + --color-border-secondary: rgba(var(--color-gray-400-rgb), 0.2); + --color-select-caret: rgba(var(--color-gray-200-rgb), 0.8); + + /* Common style patterns - updated for dark mode */ + --focus-ring: 0 0 0 3px var(--color-focus-ring); + --focus-outline: 2px solid var(--color-primary); + --status-bg-opacity: 0.15; + --status-border-opacity: 0.25; + --select-caret-light: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23134252' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E"); + --select-caret-dark: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23f5f5f5' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E"); + + /* RGB versions for dark mode */ + --color-success-rgb: var(--color-teal-300-rgb); + --color-error-rgb: var(--color-red-400-rgb); + --color-warning-rgb: var(--color-orange-400-rgb); + --color-info-rgb: var(--color-gray-300-rgb); + } +} + +/* Data attribute for manual theme switching */ +[data-color-scheme="dark"] { + /* RGB versions for opacity control (dark mode) */ + --color-gray-400-rgb: 119, 124, 124; + --color-teal-300-rgb: 50, 184, 198; + --color-gray-300-rgb: 167, 169, 169; + --color-gray-200-rgb: 245, 245, 245; + + /* Colorful background palette - Dark Mode */ + --color-bg-1: rgba(29, 78, 216, 0.15); /* Dark blue */ + --color-bg-2: rgba(180, 83, 9, 0.15); /* Dark yellow */ + --color-bg-3: rgba(21, 128, 61, 0.15); /* Dark green */ + --color-bg-4: rgba(185, 28, 28, 0.15); /* Dark red */ + --color-bg-5: rgba(107, 33, 168, 0.15); /* Dark purple */ + --color-bg-6: rgba(194, 65, 12, 0.15); /* Dark orange */ + --color-bg-7: rgba(190, 24, 93, 0.15); /* Dark pink */ + --color-bg-8: rgba(8, 145, 178, 0.15); /* Dark cyan */ + + /* Semantic Color Tokens (Dark Mode) */ + --color-background: var(--color-charcoal-700); + --color-surface: var(--color-charcoal-800); + --color-text: var(--color-gray-200); + --color-text-secondary: rgba(var(--color-gray-300-rgb), 0.7); + --color-primary: var(--color-teal-300); + --color-primary-hover: var(--color-teal-400); + --color-primary-active: var(--color-teal-800); + --color-secondary: rgba(var(--color-gray-400-rgb), 0.15); + --color-secondary-hover: rgba(var(--color-gray-400-rgb), 0.25); + --color-secondary-active: rgba(var(--color-gray-400-rgb), 0.3); + --color-border: rgba(var(--color-gray-400-rgb), 0.3); + --color-error: var(--color-red-400); + --color-success: var(--color-teal-300); + --color-warning: var(--color-orange-400); + --color-info: var(--color-gray-300); + --color-focus-ring: rgba(var(--color-teal-300-rgb), 0.4); + --color-btn-primary-text: var(--color-slate-900); + --color-card-border: rgba(var(--color-gray-400-rgb), 0.15); + --color-card-border-inner: rgba(var(--color-gray-400-rgb), 0.15); + --shadow-inset-sm: inset 0 1px 0 rgba(255, 255, 255, 0.1), + inset 0 -1px 0 rgba(0, 0, 0, 0.15); + --color-border-secondary: rgba(var(--color-gray-400-rgb), 0.2); + --color-select-caret: rgba(var(--color-gray-200-rgb), 0.8); + + /* Common style patterns - updated for dark mode */ + --focus-ring: 0 0 0 3px var(--color-focus-ring); + --focus-outline: 2px solid var(--color-primary); + --status-bg-opacity: 0.15; + --status-border-opacity: 0.25; + --select-caret-light: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23134252' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E"); + --select-caret-dark: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23f5f5f5' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E"); + + /* RGB versions for dark mode */ + --color-success-rgb: var(--color-teal-300-rgb); + --color-error-rgb: var(--color-red-400-rgb); + --color-warning-rgb: var(--color-orange-400-rgb); + --color-info-rgb: var(--color-gray-300-rgb); +} + +[data-color-scheme="light"] { + /* RGB versions for opacity control (light mode) */ + --color-brown-600-rgb: 94, 82, 64; + --color-teal-500-rgb: 33, 128, 141; + --color-slate-900-rgb: 19, 52, 59; + + /* Semantic Color Tokens (Light Mode) */ + --color-background: var(--color-cream-50); + --color-surface: var(--color-cream-100); + --color-text: var(--color-slate-900); + --color-text-secondary: var(--color-slate-500); + --color-primary: var(--color-teal-500); + --color-primary-hover: var(--color-teal-600); + --color-primary-active: var(--color-teal-700); + --color-secondary: rgba(var(--color-brown-600-rgb), 0.12); + --color-secondary-hover: rgba(var(--color-brown-600-rgb), 0.2); + --color-secondary-active: rgba(var(--color-brown-600-rgb), 0.25); + --color-border: rgba(var(--color-brown-600-rgb), 0.2); + --color-btn-primary-text: var(--color-cream-50); + --color-card-border: rgba(var(--color-brown-600-rgb), 0.12); + --color-card-border-inner: rgba(var(--color-brown-600-rgb), 0.12); + --color-error: var(--color-red-500); + --color-success: var(--color-teal-500); + --color-warning: var(--color-orange-500); + --color-info: var(--color-slate-500); + --color-focus-ring: rgba(var(--color-teal-500-rgb), 0.4); + + /* RGB versions for light mode */ + --color-success-rgb: var(--color-teal-500-rgb); + --color-error-rgb: var(--color-red-500-rgb); + --color-warning-rgb: var(--color-orange-500-rgb); + --color-info-rgb: var(--color-slate-500-rgb); +} + +/* Base styles */ +html { + font-size: var(--font-size-base); + font-family: var(--font-family-base); + line-height: var(--line-height-normal); + color: var(--color-text); + background-color: var(--color-background); + -webkit-font-smoothing: antialiased; + box-sizing: border-box; +} + +body { + margin: 0; + padding: 0; +} + +*, +*::before, +*::after { + box-sizing: inherit; +} + +/* Typography */ +h1, +h2, +h3, +h4, +h5, +h6 { + margin: 0; + font-weight: var(--font-weight-semibold); + line-height: var(--line-height-tight); + color: var(--color-text); + letter-spacing: var(--letter-spacing-tight); +} + +h1 { + font-size: var(--font-size-4xl); +} +h2 { + font-size: var(--font-size-3xl); +} +h3 { + font-size: var(--font-size-2xl); +} +h4 { + font-size: var(--font-size-xl); +} +h5 { + font-size: var(--font-size-lg); +} +h6 { + font-size: var(--font-size-md); +} + +p { + margin: 0 0 var(--space-16) 0; +} + +a { + color: var(--color-primary); + text-decoration: none; + transition: color var(--duration-fast) var(--ease-standard); +} + +a:hover { + color: var(--color-primary-hover); +} + +code, +pre { + font-family: var(--font-family-mono); + font-size: calc(var(--font-size-base) * 0.95); + background-color: var(--color-secondary); + border-radius: var(--radius-sm); +} + +code { + padding: var(--space-1) var(--space-4); +} + +pre { + padding: var(--space-16); + margin: var(--space-16) 0; + overflow: auto; + border: 1px solid var(--color-border); +} + +pre code { + background: none; + padding: 0; +} + +/* Buttons */ +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + padding: var(--space-8) var(--space-16); + border-radius: var(--radius-base); + font-size: var(--font-size-base); + font-weight: 500; + line-height: 1.5; + cursor: pointer; + transition: all var(--duration-normal) var(--ease-standard); + border: none; + text-decoration: none; + position: relative; +} + +.btn:focus-visible { + outline: none; + box-shadow: var(--focus-ring); +} + +.btn--primary { + background: var(--color-primary); + color: var(--color-btn-primary-text); +} + +.btn--primary:hover { + background: var(--color-primary-hover); +} + +.btn--primary:active { + background: var(--color-primary-active); +} + +.btn--secondary { + background: var(--color-secondary); + color: var(--color-text); +} + +.btn--secondary:hover { + background: var(--color-secondary-hover); +} + +.btn--secondary:active { + background: var(--color-secondary-active); +} + +.btn--outline { + background: transparent; + border: 1px solid var(--color-border); + color: var(--color-text); +} + +.btn--outline:hover { + background: var(--color-secondary); +} + +.btn--sm { + padding: var(--space-4) var(--space-12); + font-size: var(--font-size-sm); + border-radius: var(--radius-sm); +} + +.btn--lg { + padding: var(--space-10) var(--space-20); + font-size: var(--font-size-lg); + border-radius: var(--radius-md); +} + +.btn--full-width { + width: 100%; +} + +.btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +/* Form elements */ +.form-control { + display: block; + width: 100%; + padding: var(--space-8) var(--space-12); + font-size: var(--font-size-md); + line-height: 1.5; + color: var(--color-text); + background-color: var(--color-surface); + border: 1px solid var(--color-border); + border-radius: var(--radius-base); + transition: border-color var(--duration-fast) var(--ease-standard), + box-shadow var(--duration-fast) var(--ease-standard); +} + +textarea.form-control { + font-family: var(--font-family-base); + font-size: var(--font-size-base); +} + +select.form-control { + padding: var(--space-8) var(--space-12); + -webkit-appearance: none; + -moz-appearance: none; + appearance: none; + background-image: var(--select-caret-light); + background-repeat: no-repeat; + background-position: right var(--space-12) center; + background-size: 16px; + padding-right: var(--space-32); +} + +/* Add a dark mode specific caret */ +@media (prefers-color-scheme: dark) { + select.form-control { + background-image: var(--select-caret-dark); + } +} + +/* Also handle data-color-scheme */ +[data-color-scheme="dark"] select.form-control { + background-image: var(--select-caret-dark); +} + +[data-color-scheme="light"] select.form-control { + background-image: var(--select-caret-light); +} + +.form-control:focus { + border-color: var(--color-primary); + outline: var(--focus-outline); +} + +.form-label { + display: block; + margin-bottom: var(--space-8); + font-weight: var(--font-weight-medium); + font-size: var(--font-size-sm); +} + +.form-group { + margin-bottom: var(--space-16); +} + +/* Card component */ +.card { + background-color: var(--color-surface); + border-radius: var(--radius-lg); + border: 1px solid var(--color-card-border); + box-shadow: var(--shadow-sm); + overflow: hidden; + transition: box-shadow var(--duration-normal) var(--ease-standard); +} + +.card:hover { + box-shadow: var(--shadow-md); +} + +.card__body { + padding: var(--space-16); +} + +.card__header, +.card__footer { + padding: var(--space-16); + border-bottom: 1px solid var(--color-card-border-inner); +} + +/* Status indicators - simplified with CSS variables */ +.status { + display: inline-flex; + align-items: center; + padding: var(--space-6) var(--space-12); + border-radius: var(--radius-full); + font-weight: var(--font-weight-medium); + font-size: var(--font-size-sm); +} + +.status--success { + background-color: rgba( + var(--color-success-rgb, 33, 128, 141), + var(--status-bg-opacity) + ); + color: var(--color-success); + border: 1px solid + rgba(var(--color-success-rgb, 33, 128, 141), var(--status-border-opacity)); +} + +.status--error { + background-color: rgba( + var(--color-error-rgb, 192, 21, 47), + var(--status-bg-opacity) + ); + color: var(--color-error); + border: 1px solid + rgba(var(--color-error-rgb, 192, 21, 47), var(--status-border-opacity)); +} + +.status--warning { + background-color: rgba( + var(--color-warning-rgb, 168, 75, 47), + var(--status-bg-opacity) + ); + color: var(--color-warning); + border: 1px solid + rgba(var(--color-warning-rgb, 168, 75, 47), var(--status-border-opacity)); +} + +.status--info { + background-color: rgba( + var(--color-info-rgb, 98, 108, 113), + var(--status-bg-opacity) + ); + color: var(--color-info); + border: 1px solid + rgba(var(--color-info-rgb, 98, 108, 113), var(--status-border-opacity)); +} + +/* Container layout */ +.container { + width: 100%; + margin-right: auto; + margin-left: auto; + padding-right: var(--space-16); + padding-left: var(--space-16); +} + +@media (min-width: 640px) { + .container { + max-width: var(--container-sm); + } +} +@media (min-width: 768px) { + .container { + max-width: var(--container-md); + } +} +@media (min-width: 1024px) { + .container { + max-width: var(--container-lg); + } +} +@media (min-width: 1280px) { + .container { + max-width: var(--container-xl); + } +} + +/* Utility classes */ +.flex { + display: flex; +} +.flex-col { + flex-direction: column; +} +.items-center { + align-items: center; +} +.justify-center { + justify-content: center; +} +.justify-between { + justify-content: space-between; +} +.gap-4 { + gap: var(--space-4); +} +.gap-8 { + gap: var(--space-8); +} +.gap-16 { + gap: var(--space-16); +} + +.m-0 { + margin: 0; +} +.mt-8 { + margin-top: var(--space-8); +} +.mb-8 { + margin-bottom: var(--space-8); +} +.mx-8 { + margin-left: var(--space-8); + margin-right: var(--space-8); +} +.my-8 { + margin-top: var(--space-8); + margin-bottom: var(--space-8); +} + +.p-0 { + padding: 0; +} +.py-8 { + padding-top: var(--space-8); + padding-bottom: var(--space-8); +} +.px-8 { + padding-left: var(--space-8); + padding-right: var(--space-8); +} +.py-16 { + padding-top: var(--space-16); + padding-bottom: var(--space-16); +} +.px-16 { + padding-left: var(--space-16); + padding-right: var(--space-16); +} + +.block { + display: block; +} +.hidden { + display: none; +} + +/* Accessibility */ +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border-width: 0; +} + +:focus-visible { + outline: var(--focus-outline); + outline-offset: 2px; +} + +/* Dark mode specifics */ +[data-color-scheme="dark"] .btn--outline { + border: 1px solid var(--color-border-secondary); +} + +@font-face { + font-family: 'FKGroteskNeue'; + src: url('https://r2cdn.perplexity.ai/fonts/FKGroteskNeue.woff2') + format('woff2'); +} + +/* END PERPLEXITY DESIGN SYSTEM */ +:root { + /* Primitive Color Tokens */ + --color-white: rgba(255, 255, 255, 1); + --color-black: rgba(0, 0, 0, 1); + --color-cream-50: rgba(252, 252, 249, 1); + --color-cream-100: rgba(255, 255, 253, 1); + --color-gray-200: rgba(245, 245, 245, 1); + --color-gray-300: rgba(167, 169, 169, 1); + --color-gray-400: rgba(119, 124, 124, 1); + --color-slate-500: rgba(98, 108, 113, 1); + --color-brown-600: rgba(94, 82, 64, 1); + --color-charcoal-700: rgba(31, 33, 33, 1); + --color-charcoal-800: rgba(38, 40, 40, 1); + --color-slate-900: rgba(19, 52, 59, 1); + --color-teal-300: rgba(50, 184, 198, 1); + --color-teal-400: rgba(45, 166, 178, 1); + --color-teal-500: rgba(33, 128, 141, 1); + --color-teal-600: rgba(29, 116, 128, 1); + --color-teal-700: rgba(26, 104, 115, 1); + --color-teal-800: rgba(41, 150, 161, 1); + --color-red-400: rgba(255, 84, 89, 1); + --color-red-500: rgba(192, 21, 47, 1); + --color-orange-400: rgba(230, 129, 97, 1); + --color-orange-500: rgba(168, 75, 47, 1); + + /* RGB versions for opacity control */ + --color-brown-600-rgb: 94, 82, 64; + --color-teal-500-rgb: 33, 128, 141; + --color-slate-900-rgb: 19, 52, 59; + --color-slate-500-rgb: 98, 108, 113; + --color-red-500-rgb: 192, 21, 47; + --color-red-400-rgb: 255, 84, 89; + --color-orange-500-rgb: 168, 75, 47; + --color-orange-400-rgb: 230, 129, 97; + + /* Background color tokens (Light Mode) */ + --color-bg-1: rgba(59, 130, 246, 0.08); + --color-bg-2: rgba(245, 158, 11, 0.08); + --color-bg-3: rgba(34, 197, 94, 0.08); + --color-bg-4: rgba(239, 68, 68, 0.08); + --color-bg-5: rgba(147, 51, 234, 0.08); + --color-bg-6: rgba(249, 115, 22, 0.08); + --color-bg-7: rgba(236, 72, 153, 0.08); + --color-bg-8: rgba(6, 182, 212, 0.08); + + /* Semantic Color Tokens (Light Mode) */ + --color-background: var(--color-cream-50); + --color-surface: var(--color-cream-100); + --color-text: var(--color-slate-900); + --color-text-secondary: var(--color-slate-500); + --color-primary: var(--color-teal-500); + --color-primary-hover: var(--color-teal-600); + --color-primary-active: var(--color-teal-700); + --color-secondary: rgba(var(--color-brown-600-rgb), 0.12); + --color-secondary-hover: rgba(var(--color-brown-600-rgb), 0.2); + --color-secondary-active: rgba(var(--color-brown-600-rgb), 0.25); + --color-border: rgba(var(--color-brown-600-rgb), 0.2); + --color-btn-primary-text: var(--color-cream-50); + --color-card-border: rgba(var(--color-brown-600-rgb), 0.12); + --color-card-border-inner: rgba(var(--color-brown-600-rgb), 0.12); + --color-error: var(--color-red-500); + --color-success: var(--color-teal-500); + --color-warning: var(--color-orange-500); + --color-info: var(--color-slate-500); + --color-focus-ring: rgba(var(--color-teal-500-rgb), 0.4); + --color-select-caret: rgba(var(--color-slate-900-rgb), 0.8); + + /* Typography */ + --font-family-base: "FKGroteskNeue", "Geist", "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + --font-family-mono: "Berkeley Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + --font-size-xs: 11px; + --font-size-sm: 12px; + --font-size-base: 14px; + --font-size-md: 14px; + --font-size-lg: 16px; + --font-size-xl: 18px; + --font-size-2xl: 20px; + --font-size-3xl: 24px; + --font-size-4xl: 30px; + --font-weight-normal: 400; + --font-weight-medium: 500; + --font-weight-semibold: 550; + --font-weight-bold: 600; + --line-height-tight: 1.2; + --line-height-normal: 1.5; + --letter-spacing-tight: -0.01em; + + /* Spacing */ + --space-0: 0; + --space-1: 1px; + --space-2: 2px; + --space-4: 4px; + --space-6: 6px; + --space-8: 8px; + --space-10: 10px; + --space-12: 12px; + --space-16: 16px; + --space-20: 20px; + --space-24: 24px; + --space-32: 32px; + + /* Border Radius */ + --radius-sm: 6px; + --radius-base: 8px; + --radius-md: 10px; + --radius-lg: 12px; + --radius-full: 9999px; + + /* Shadows */ + --shadow-xs: 0 1px 2px rgba(0, 0, 0, 0.02); + --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.04), 0 1px 2px rgba(0, 0, 0, 0.02); + --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.04), 0 2px 4px -1px rgba(0, 0, 0, 0.02); + --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.04), 0 4px 6px -2px rgba(0, 0, 0, 0.02); + --shadow-inset-sm: inset 0 1px 0 rgba(255, 255, 255, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.03); + + /* Animation */ + --duration-fast: 150ms; + --duration-normal: 250ms; + --ease-standard: cubic-bezier(0.16, 1, 0.3, 1); +} + +@media (prefers-color-scheme: dark) { + :root { + --color-gray-400-rgb: 119, 124, 124; + --color-teal-300-rgb: 50, 184, 198; + --color-gray-300-rgb: 167, 169, 169; + --color-gray-200-rgb: 245, 245, 245; + + --color-bg-1: rgba(29, 78, 216, 0.15); + --color-bg-2: rgba(180, 83, 9, 0.15); + --color-bg-3: rgba(21, 128, 61, 0.15); + --color-bg-4: rgba(185, 28, 28, 0.15); + --color-bg-5: rgba(107, 33, 168, 0.15); + --color-bg-6: rgba(194, 65, 12, 0.15); + --color-bg-7: rgba(190, 24, 93, 0.15); + --color-bg-8: rgba(8, 145, 178, 0.15); + + --color-background: var(--color-charcoal-700); + --color-surface: var(--color-charcoal-800); + --color-text: var(--color-gray-200); + --color-text-secondary: rgba(var(--color-gray-300-rgb), 0.7); + --color-primary: var(--color-teal-300); + --color-primary-hover: var(--color-teal-400); + --color-primary-active: var(--color-teal-800); + --color-secondary: rgba(var(--color-gray-400-rgb), 0.15); + --color-secondary-hover: rgba(var(--color-gray-400-rgb), 0.25); + --color-secondary-active: rgba(var(--color-gray-400-rgb), 0.3); + --color-border: rgba(var(--color-gray-400-rgb), 0.3); + --color-error: var(--color-red-400); + --color-success: var(--color-teal-300); + --color-warning: var(--color-orange-400); + --color-info: var(--color-gray-300); + --color-focus-ring: rgba(var(--color-teal-300-rgb), 0.4); + --color-btn-primary-text: var(--color-slate-900); + --color-card-border: rgba(var(--color-gray-400-rgb), 0.2); + --color-card-border-inner: rgba(var(--color-gray-400-rgb), 0.15); + --shadow-inset-sm: inset 0 1px 0 rgba(255, 255, 255, 0.1), inset 0 -1px 0 rgba(0, 0, 0, 0.15); + } +} + +@font-face { + font-family: 'FKGroteskNeue'; + src: url('https://r2cdn.perplexity.ai/fonts/FKGroteskNeue.woff2') format('woff2'); +} + +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +html, body { + height: 100%; + font-family: var(--font-family-base); + font-size: var(--font-size-base); + line-height: var(--line-height-normal); + color: var(--color-text); + background-color: var(--color-background); + -webkit-font-smoothing: antialiased; +} + +.app-container { + display: flex; + height: 100vh; + overflow: hidden; +} + +/* Sidebar Navigation */ +.sidebar { + width: 260px; + background-color: var(--color-surface); + border-right: 1px solid var(--color-border); + display: flex; + flex-direction: column; + overflow-y: auto; +} + +.sidebar-header { + padding: var(--space-24) var(--space-20); + border-bottom: 1px solid var(--color-border); +} + +.sidebar-header h1 { + font-size: var(--font-size-2xl); + font-weight: var(--font-weight-bold); + color: var(--color-text); + margin-bottom: var(--space-4); +} + +.sidebar-header p { + font-size: var(--font-size-sm); + color: var(--color-text-secondary); +} + +.nav-menu { + list-style: none; + padding: var(--space-12); +} + +.nav-item { + display: flex; + align-items: center; + padding: var(--space-12) var(--space-16); + margin-bottom: var(--space-4); + border-radius: var(--radius-base); + cursor: pointer; + transition: all var(--duration-fast) var(--ease-standard); + color: var(--color-text); +} + +.nav-item:hover { + background-color: var(--color-secondary); +} + +.nav-item.active { + background-color: var(--color-primary); + color: var(--color-btn-primary-text); +} + +.nav-icon { + font-size: var(--font-size-xl); + margin-right: var(--space-12); +} + +.nav-label { + font-size: var(--font-size-base); + font-weight: var(--font-weight-medium); +} + +/* Main Content */ +.main-content { + flex: 1; + overflow-y: auto; + padding: var(--space-32); +} + +.module { + max-width: 1400px; + margin: 0 auto; +} + +.module-header { + margin-bottom: var(--space-32); +} + +.module-header h2 { + font-size: var(--font-size-4xl); + font-weight: var(--font-weight-bold); + margin-bottom: var(--space-8); + color: var(--color-text); +} + +.module-header p { + font-size: var(--font-size-lg); + color: var(--color-text-secondary); +} + +.content-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(500px, 1fr)); + gap: var(--space-24); +} + +.section { + background-color: var(--color-surface); + border: 1px solid var(--color-card-border); + border-radius: var(--radius-lg); + padding: var(--space-24); +} + +.section h3 { + font-size: var(--font-size-xl); + font-weight: var(--font-weight-semibold); + margin-bottom: var(--space-16); + color: var(--color-text); +} + +.section h4 { + font-size: var(--font-size-lg); + font-weight: var(--font-weight-medium); + margin-bottom: var(--space-12); + color: var(--color-text); +} + +.chart-section { + display: flex; + flex-direction: column; + align-items: center; +} + +.chart-section canvas { + max-width: 100%; + height: auto; +} + +.full-width { + grid-column: 1 / -1; +} + +/* Tables */ +.table-container { + overflow-x: auto; +} + +.data-table { + width: 100%; + border-collapse: collapse; +} + +.data-table thead { + background-color: var(--color-secondary); +} + +.data-table th, +.data-table td { + padding: var(--space-12); + text-align: left; + border-bottom: 1px solid var(--color-border); +} + +.data-table th { + font-weight: var(--font-weight-semibold); + font-size: var(--font-size-sm); + color: var(--color-text); +} + +.data-table td { + font-size: var(--font-size-base); + color: var(--color-text); +} + +.data-table tbody tr:hover { + background-color: var(--color-secondary); +} + +/* Controls */ +.controls { + display: flex; + flex-direction: column; + gap: var(--space-16); +} + +.control-group { + display: flex; + flex-direction: column; + gap: var(--space-8); +} + +.control-group label { + font-size: var(--font-size-sm); + font-weight: var(--font-weight-medium); + color: var(--color-text); +} + +.control-group input[type="range"] { + width: 100%; + height: 6px; + border-radius: var(--radius-full); + background: var(--color-secondary); + outline: none; + cursor: pointer; +} + +.control-group input[type="range"]::-webkit-slider-thumb { + -webkit-appearance: none; + appearance: none; + width: 18px; + height: 18px; + border-radius: 50%; + background: var(--color-primary); + cursor: pointer; +} + +.control-group input[type="range"]::-moz-range-thumb { + width: 18px; + height: 18px; + border-radius: 50%; + background: var(--color-primary); + cursor: pointer; + border: none; +} + +.radio-group { + display: flex; + gap: var(--space-16); + flex-wrap: wrap; +} + +.radio-group label { + display: flex; + align-items: center; + gap: var(--space-6); + cursor: pointer; + font-size: var(--font-size-base); +} + +.radio-group input[type="radio"] { + cursor: pointer; +} + +/* Buttons */ +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + padding: var(--space-10) var(--space-20); + border-radius: var(--radius-base); + font-size: var(--font-size-base); + font-weight: var(--font-weight-medium); + cursor: pointer; + transition: all var(--duration-normal) var(--ease-standard); + border: none; + text-decoration: none; +} + +.btn--primary { + background: var(--color-primary); + color: var(--color-btn-primary-text); +} + +.btn--primary:hover { + background: var(--color-primary-hover); +} + +.btn--secondary { + background: var(--color-secondary); + color: var(--color-text); +} + +.btn--secondary:hover { + background: var(--color-secondary-hover); +} + +/* Info Cards */ +.info-card { + background-color: var(--color-bg-1); + border: 1px solid var(--color-border); + border-radius: var(--radius-base); + padding: var(--space-16); + margin-top: var(--space-16); +} + +.info-card h4 { + font-size: var(--font-size-sm); + font-weight: var(--font-weight-medium); + color: var(--color-text-secondary); + margin-bottom: var(--space-8); +} + +.metric-value { + font-size: var(--font-size-3xl); + font-weight: var(--font-weight-bold); + color: var(--color-primary); +} + +.metric-detail { + font-size: var(--font-size-sm); + color: var(--color-text-secondary); + margin-top: var(--space-4); +} + +/* Explanation Cards */ +.explanation-card { + background-color: var(--color-bg-2); + border: 1px solid var(--color-border); + border-radius: var(--radius-base); + padding: var(--space-20); +} + +.explanation-card h4 { + font-size: var(--font-size-lg); + font-weight: var(--font-weight-semibold); + margin-bottom: var(--space-12); +} + +.explanation-card p { + margin-bottom: var(--space-12); + line-height: 1.6; +} + +.explanation-card ul { + padding-left: var(--space-20); + margin-top: var(--space-12); +} + +.explanation-card li { + margin-bottom: var(--space-8); + line-height: 1.6; +} + +.formula { + font-family: var(--font-family-mono); + background-color: var(--color-surface); + padding: var(--space-8) var(--space-12); + border-radius: var(--radius-sm); + display: inline-block; + margin: var(--space-8) 0; + border: 1px solid var(--color-border); +} + +/* Confusion Matrix */ +.confusion-matrix { + display: grid; + grid-template-columns: 1fr 1fr; + gap: var(--space-12); + margin-bottom: var(--space-20); +} + +.cm-cell { + padding: var(--space-20); + border-radius: var(--radius-base); + text-align: center; + display: flex; + flex-direction: column; + gap: var(--space-8); +} + +.cm-label { + font-size: var(--font-size-sm); + font-weight: var(--font-weight-medium); + color: var(--color-text-secondary); +} + +.cm-value { + font-size: var(--font-size-3xl); + font-weight: var(--font-weight-bold); +} + +.cm-tn { + background-color: var(--color-bg-3); + border: 2px solid var(--color-success); +} + +.cm-tn .cm-value { + color: var(--color-success); +} + +.cm-fp { + background-color: var(--color-bg-4); + border: 2px solid var(--color-error); +} + +.cm-fp .cm-value { + color: var(--color-error); +} + +.cm-fn { + background-color: var(--color-bg-4); + border: 2px solid var(--color-error); +} + +.cm-fn .cm-value { + color: var(--color-error); +} + +.cm-tp { + background-color: var(--color-bg-3); + border: 2px solid var(--color-success); +} + +.cm-tp .cm-value { + color: var(--color-success); +} + +/* Metrics Panel */ +.metrics-panel { + display: flex; + gap: var(--space-20); + flex-wrap: wrap; + margin-top: var(--space-16); +} + +.metric-item { + flex: 1; + min-width: 150px; + padding: var(--space-12); + background-color: var(--color-secondary); + border-radius: var(--radius-base); + display: flex; + flex-direction: column; + gap: var(--space-4); +} + +.metric-label { + font-size: var(--font-size-sm); + color: var(--color-text-secondary); +} + +.metric-val { + font-size: var(--font-size-xl); + font-weight: var(--font-weight-bold); + color: var(--color-text); +} + +/* Three Charts Layout */ +.three-charts { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: var(--space-20); + width: 100%; +} + +.chart-container { + display: flex; + flex-direction: column; + align-items: center; + gap: var(--space-12); +} + +.chart-container h4 { + font-size: var(--font-size-base); + font-weight: var(--font-weight-semibold); + text-align: center; +} + +.chart-desc { + font-size: var(--font-size-sm); + color: var(--color-text-secondary); + text-align: center; + margin-top: var(--space-8); +} + +/* Calculation Panel */ +.calculation-panel { + display: flex; + flex-direction: column; + gap: var(--space-12); +} + +.calc-item { + display: flex; + justify-content: space-between; + align-items: center; + padding: var(--space-12); + background-color: var(--color-secondary); + border-radius: var(--radius-base); +} + +.calc-item strong { + font-weight: var(--font-weight-medium); +} + +.calc-item span { + font-family: var(--font-family-mono); + color: var(--color-primary); + font-weight: var(--font-weight-semibold); +} + +/* Responsive adjustments */ +@media (max-width: 1200px) { + .content-grid { + grid-template-columns: 1fr; + } + + .three-charts { + grid-template-columns: 1fr; + } +} + +/* Pipeline Flow */ +.pipeline-flow { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: var(--space-16); +} + +.pipeline-stage { + background: var(--color-bg-1); + border: 1px solid var(--color-border); + border-radius: var(--radius-base); + padding: var(--space-16); +} + +.pipeline-stage h4 { + font-size: var(--font-size-base); + margin-bottom: var(--space-12); + color: var(--color-primary); +} + +/* Workflow Container */ +.workflow-container { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: var(--space-16); + padding: var(--space-24); +} + +.workflow-stage { + flex: 1; + min-width: 140px; + background: var(--color-bg-1); + border: 2px solid var(--color-border); + border-radius: var(--radius-lg); + padding: var(--space-20); + text-align: center; + transition: all var(--duration-normal) var(--ease-standard); + cursor: pointer; +} + +.workflow-stage:hover { + transform: translateY(-4px); + box-shadow: var(--shadow-lg); + border-color: var(--color-primary); +} + +.workflow-stage.active { + background: var(--color-primary); + color: var(--color-btn-primary-text); + border-color: var(--color-primary); +} + +.stage-icon { + font-size: 32px; + margin-bottom: var(--space-8); +} + +.workflow-stage h4 { + font-size: var(--font-size-base); + margin-bottom: var(--space-8); +} + +.workflow-stage p { + font-size: var(--font-size-sm); + color: var(--color-text-secondary); + margin-bottom: var(--space-12); +} + +.workflow-stage.active p { + color: var(--color-btn-primary-text); + opacity: 0.9; +} + +.workflow-arrow { + font-size: 24px; + color: var(--color-primary); + font-weight: bold; +} + +.stage-btn { + font-size: var(--font-size-sm); + padding: var(--space-6) var(--space-12); +} + +@media (max-width: 1200px) { + .workflow-container { + flex-direction: column; + } + + .workflow-arrow { + transform: rotate(90deg); + } +} + +@media (max-width: 768px) { + .sidebar { + width: 80px; + } + + .nav-label { + display: none; + } + + .sidebar-header h1 { + font-size: var(--font-size-lg); + } + + .sidebar-header p { + display: none; + } +} \ No newline at end of file