diff --git a/docs/DEVELOPER_GUIDE.md b/docs/DEVELOPER_GUIDE.md index 5bd4bda..136604f 100644 --- a/docs/DEVELOPER_GUIDE.md +++ b/docs/DEVELOPER_GUIDE.md @@ -705,12 +705,14 @@ const handleInput = (event: Event) => { ### Unit Testing -Use Vitest for unit tests: +All unit tests live directly in the top-level `tests/` directory following the naming convention `tests/-algorithm.test.ts` (e.g. `tests/knn-algorithm.test.ts`, `tests/linear-regression-algorithm.test.ts`). + +Tests use Vitest and should cover `fit()`, `predict()`, performance metrics (`getMetrics()`), visualization payloads (`getVisualizationData()`), input validation, and `reset()`. ```typescript -// algorithms/__tests__/ExampleAlgorithm.test.ts +// tests/example-algorithm.test.ts import { describe, it, expect } from 'vitest'; -import { ExampleAlgorithm } from '../ExampleAlgorithm'; +import { ExampleAlgorithm } from '../algorithms/regression/ExampleAlgorithm'; describe('ExampleAlgorithm', () => { it('should initialize with default parameters', () => { diff --git a/tests/feature-scaling-algorithm.test.ts b/tests/feature-scaling-algorithm.test.ts new file mode 100644 index 0000000..12ce576 --- /dev/null +++ b/tests/feature-scaling-algorithm.test.ts @@ -0,0 +1,140 @@ +/** + * Feature Scaling Algorithm Tests + * + * Tests for normalization (Min-Max) and standardization (Z-Score) preprocessing algorithms + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { FeatureScaling } from '../algorithms/preprocessing/FeatureScaling'; + +describe('FeatureScaling Algorithm', () => { + let scaler: FeatureScaling; + + beforeEach(() => { + scaler = new FeatureScaling(); + }); + + describe('Min-Max Normalization', () => { + it('should scale features to [0, 1] range', () => { + const data = [ + [0, 10], + [5, 20], + [10, 30] + ]; + scaler.setData(data); + + const result = scaler.normalize(); + + expect(result.method).toBe('normalize'); + expect(result.scaled).toEqual([ + [0, 0], + [0.5, 0.5], + [1, 1] + ]); + + expect(result.statistics.originalMin).toEqual([0, 10]); + expect(result.statistics.originalMax).toEqual([10, 30]); + expect(result.statistics.scaledMin).toEqual([0, 0]); + expect(result.statistics.scaledMax).toEqual([1, 1]); + }); + + it('should handle constant feature columns without division by zero', () => { + const data = [ + [5, 10], + [5, 20], + [5, 30] + ]; + scaler.setData(data); + + const result = scaler.normalize(); + + // Constant column should be scaled to 0 + expect(result.scaled.map(row => row[0])).toEqual([0, 0, 0]); + expect(result.scaled.map(row => row[1])).toEqual([0, 0.5, 1]); + }); + }); + + describe('Z-Score Standardization', () => { + it('should transform features to have zero mean and unit variance', () => { + // Symmetrical data around mean + const data = [ + [-2, 10], + [0, 20], + [2, 30] + ]; + scaler.setData(data); + + const result = scaler.standardize(); + + expect(result.method).toBe('standardize'); + expect(result.scaled).toHaveLength(3); + + // Mean should be 0 for both features + const mean0 = (result.scaled[0][0] + result.scaled[1][0] + result.scaled[2][0]) / 3; + const mean1 = (result.scaled[0][1] + result.scaled[1][1] + result.scaled[2][1]) / 3; + + expect(mean0).toBeCloseTo(0, 5); + expect(mean1).toBeCloseTo(0, 5); + + // Statistics check + expect(result.statistics.originalMean![0]).toBeCloseTo(0, 5); + expect(result.statistics.originalMean![1]).toBeCloseTo(20, 5); + expect(result.statistics.scaledMean![0]).toBeCloseTo(0, 5); + expect(result.statistics.scaledMean![1]).toBeCloseTo(0, 5); + expect(result.statistics.scaledStd![0]).toBeCloseTo(1, 5); + expect(result.statistics.scaledStd![1]).toBeCloseTo(1, 5); + }); + + it('should handle zero-variance constant column', () => { + const data = [ + [7, 100], + [7, 200], + [7, 300] + ]; + scaler.setData(data); + + const result = scaler.standardize(); + + // Constant feature standardizes to 0 (since std is 0) + expect(result.scaled.map(row => row[0])).toEqual([0, 0, 0]); + expect(result.statistics.originalStd![0]).toBe(0); + }); + }); + + describe('State Management and Reset', () => { + it('should initialize with constructor data', () => { + const initial = [[1, 2], [3, 4]]; + const s = new FeatureScaling(initial); + const res = s.getResult(); + + expect(res.original).toEqual(initial); + expect(res.scaled).toEqual(initial); + expect(res.method).toBe('none'); + }); + + it('should reset scaled data and statistics back to none', () => { + const data = [[1, 2], [3, 4]]; + scaler.setData(data); + scaler.normalize(); + + expect(scaler.getResult().method).toBe('normalize'); + + scaler.reset(); + const afterReset = scaler.getResult(); + + expect(afterReset.method).toBe('none'); + expect(afterReset.scaled).toEqual(data); + expect(afterReset.statistics).toEqual({}); + }); + }); + + describe('Error Handling', () => { + it('should throw error when normalizing empty data', () => { + expect(() => scaler.normalize()).toThrow('No data to normalize'); + }); + + it('should throw error when standardizing empty data', () => { + expect(() => scaler.standardize()).toThrow('No data to standardize'); + }); + }); +}); diff --git a/tests/kmeans-algorithm.test.ts b/tests/kmeans-algorithm.test.ts new file mode 100644 index 0000000..6ab4ffd --- /dev/null +++ b/tests/kmeans-algorithm.test.ts @@ -0,0 +1,213 @@ +/** + * K-Means Algorithm Tests + * + * Tests for K-Means Clustering algorithm with k-means++ and random initialization + * Requirements: 2.4, 4.6 + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { KMeans } from '../algorithms/clustering/KMeans'; + +describe('KMeans Algorithm', () => { + let kmeans: KMeans; + + beforeEach(() => { + kmeans = new KMeans({ + k: 2, + maxIterations: 50, + tolerance: 1e-4, + initialization: 'kmeans++', + randomSeed: 42 + }); + }); + + describe('Basic Clustering Functionality', () => { + it('should separate two well-spaced 2D clusters', async () => { + // Two distinct clusters around (1, 1) and (10, 10) + const X = [ + [0.9, 1.1], + [1.0, 0.9], + [1.1, 1.0], + [0.8, 1.2], + [9.9, 10.1], + [10.0, 9.9], + [10.1, 10.0], + [9.8, 10.2] + ]; + + await kmeans.fit(X); + const assignments = kmeans.predict(X); + + expect(assignments).toHaveLength(8); + + // First 4 samples should belong to one cluster, next 4 to the other + const clusterA = assignments[0]; + const clusterB = assignments[4]; + + expect(clusterA).not.toBe(clusterB); + expect(assignments.slice(0, 4).every(c => c === clusterA)).toBe(true); + expect(assignments.slice(4, 8).every(c => c === clusterB)).toBe(true); + }); + + it('should assign unseen test points to nearest centroid', async () => { + const X = [ + [1, 1], + [1.2, 0.8], + [10, 10], + [10.2, 9.8] + ]; + + await kmeans.fit(X); + + const testPoints = [ + [1.1, 1.1], // Close to (1, 1) + [9.9, 10.1] // Close to (10, 10) + ]; + const predictions = kmeans.predict(testPoints); + + const trainPredictions = kmeans.predict([[1, 1], [10, 10]]); + expect(predictions[0]).toBe(trainPredictions[0]); + expect(predictions[1]).toBe(trainPredictions[1]); + }); + }); + + describe('Initialization Modes', () => { + it('should support random initialization', async () => { + const kmeansRandom = new KMeans({ + k: 2, + maxIterations: 50, + tolerance: 1e-4, + initialization: 'random', + randomSeed: 123 + }); + + const X = [ + [0, 0], + [0.2, 0.1], + [5, 5], + [5.1, 4.9] + ]; + + await kmeansRandom.fit(X); + const centroids = kmeansRandom.getCentroids(); + + expect(centroids).toHaveLength(2); + expect(centroids[0]).toHaveLength(2); + expect(centroids[1]).toHaveLength(2); + }); + + it('should record iterative cluster history', async () => { + const X = [ + [1, 1], + [2, 2], + [8, 8], + [9, 9] + ]; + + await kmeans.fit(X); + const history = kmeans.getClusterHistory(); + + expect(Array.isArray(history)).toBe(true); + expect(history.length).toBeGreaterThan(0); + expect(history[0]).toHaveProperty('centroids'); + expect(history[0]).toHaveProperty('assignments'); + expect(history[0]).toHaveProperty('inertia'); + }); + }); + + describe('Metrics', () => { + it('should return empty metrics object before fitting', () => { + expect(kmeans.getMetrics()).toEqual({}); + }); + + it('should calculate clustering metrics (inertia, silhouetteScore, clusterSizes)', async () => { + const X = [ + [1, 1], + [1.2, 0.8], + [8, 8], + [8.2, 7.8] + ]; + + await kmeans.fit(X); + const metrics = kmeans.getMetrics(); + + expect(metrics.inertia).toBeDefined(); + expect(metrics.inertia!).toBeGreaterThanOrEqual(0); + expect(metrics.silhouetteScore).toBeDefined(); + expect(metrics.silhouetteScore!).toBeGreaterThan(0); + expect(metrics.iterations).toBeDefined(); + expect(metrics.clusterSizes).toBeDefined(); + expect(metrics.clusterSizes).toHaveLength(2); + expect(metrics.clusterSizes![0] + metrics.clusterSizes![1]).toBe(4); + }); + }); + + describe('Visualization Data', () => { + it('should return empty array before training', () => { + expect(kmeans.getVisualizationData()).toEqual([]); + }); + + it('should provide 2D scatter and line visualization data for 2D clusters', async () => { + const X = [ + [1, 1], + [2, 2], + [8, 8], + [9, 9] + ]; + + await kmeans.fit(X); + const viz = kmeans.getVisualizationData(); + + expect(Array.isArray(viz)).toBe(true); + expect(viz.length).toBe(2); + + const scatter = viz.find(v => v.type === 'scatter2d'); + const line = viz.find(v => v.type === 'line'); + + expect(scatter).toBeDefined(); + expect(scatter!.data).toHaveProperty('centroids'); + expect(scatter!.data).toHaveProperty('cluster0'); + expect(scatter!.data).toHaveProperty('cluster1'); + + expect(line).toBeDefined(); + expect(line!.data.name).toBe('Inertia'); + }); + }); + + describe('Error Handling', () => { + it('should throw error when predicting before training', () => { + expect(() => kmeans.predict([[1, 1]])).toThrow('K-Means Clustering must be trained before making predictions'); + }); + + it('should throw error when k is greater than number of samples', async () => { + const kLarge = new KMeans({ k: 5, maxIterations: 10, tolerance: 1e-4, initialization: 'kmeans++' }); + await expect(kLarge.fit([[1, 1], [2, 2]])).rejects.toThrow('cannot exceed number of samples'); + }); + + it('should throw error when k is less than 1', async () => { + const kZero = new KMeans({ k: 0, maxIterations: 10, tolerance: 1e-4, initialization: 'kmeans++' }); + await expect(kZero.fit([[1, 1]])).rejects.toThrow('Number of clusters must be at least 1'); + }); + + it('should throw error on predict with mismatched feature dimensions', async () => { + const X = [[1, 2], [3, 4], [5, 6]]; + await kmeans.fit(X); + expect(() => kmeans.predict([[1, 2, 3]])).toThrow(); + }); + }); + + describe('Reset', () => { + it('should reset model state and centroids', async () => { + const X = [[1, 1], [2, 2], [5, 5], [6, 6]]; + await kmeans.fit(X); + expect(() => kmeans.predict([[1, 1]])).not.toThrow(); + + kmeans.reset(); + expect(() => kmeans.predict([[1, 1]])).toThrow(); + expect(kmeans.getCentroids()).toHaveLength(0); + expect(kmeans.getAssignments()).toHaveLength(0); + expect(kmeans.getMetrics()).toEqual({}); + expect(kmeans.getVisualizationData()).toEqual([]); + }); + }); +}); diff --git a/tests/linear-regression-algorithm.test.ts b/tests/linear-regression-algorithm.test.ts new file mode 100644 index 0000000..1fc9762 --- /dev/null +++ b/tests/linear-regression-algorithm.test.ts @@ -0,0 +1,212 @@ +/** + * Linear Regression Algorithm Tests + * + * Tests for Linear Regression algorithm (gradient descent optimization) + * Requirements: 2.3, 4.1, 4.2 + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { LinearRegression } from '../algorithms/regression/LinearRegression'; + +describe('LinearRegression Algorithm', () => { + let lr: LinearRegression; + + beforeEach(() => { + lr = new LinearRegression({ + learningRate: 0.05, + epochs: 80, + normalize: false + }); + }); + + describe('Basic Functionality (1D Regression)', () => { + it('should train and predict on simple linear relationship (y = 2x + 1)', async () => { + // Deterministic synthetic points along y = 2x + 1 + const X = [[1], [2], [3], [4], [5]]; + const y = [3, 5, 7, 9, 11]; + + await lr.fit(X, y); + const predictions = lr.predict(X); + + expect(predictions).toHaveLength(5); + for (let i = 0; i < predictions.length; i++) { + expect(predictions[i]).toBeCloseTo(y[i], 0); + } + }); + + it('should generalize to unseen test points', async () => { + const X_train = [[1], [2], [3], [4], [5]]; + const y_train = [3, 5, 7, 9, 11]; + + await lr.fit(X_train, y_train); + + // x = 6 should produce ~ 13 (2*6 + 1) + const unseen = lr.predict([[6], [0]]); + expect(unseen[0]).toBeCloseTo(13, 0); + expect(unseen[1]).toBeCloseTo(1, 0); + }); + }); + + describe('Multi-Feature Regression', () => { + it('should fit multi-variable linear model (y = 2*x1 + 3*x2)', async () => { + const lrMulti = new LinearRegression({ + learningRate: 0.05, + epochs: 100, + normalize: false + }); + + const X = [ + [1, 1], + [2, 1], + [1, 2], + [2, 2], + [3, 1] + ]; + // y = 2*x1 + 3*x2 + const y = [5, 7, 8, 10, 9]; + + await lrMulti.fit(X, y); + const predictions = lrMulti.predict(X); + + expect(predictions).toHaveLength(5); + for (let i = 0; i < predictions.length; i++) { + expect(predictions[i]).toBeCloseTo(y[i], 0); + } + }); + }); + + describe('Feature Normalization', () => { + it('should support training with feature normalization enabled', async () => { + const lrNorm = new LinearRegression({ + learningRate: 0.1, + epochs: 80, + normalize: true + }); + + // Data on different scales + const X = [ + [100, 1], + [200, 2], + [300, 3], + [400, 4] + ]; + const y = [10, 20, 30, 40]; + + await lrNorm.fit(X, y); + const params = lrNorm.getParameters(); + + expect(params.normalized).toBe(true); + expect(params.featureMeans).toHaveLength(2); + expect(params.featureStds).toHaveLength(2); + + const predictions = lrNorm.predict(X); + for (let i = 0; i < predictions.length; i++) { + expect(predictions[i]).toBeCloseTo(y[i], 0); + } + }); + }); + + describe('Metrics', () => { + it('should return empty metrics object before fitting', () => { + const metrics = lr.getMetrics(); + expect(metrics).toEqual({}); + }); + + it('should calculate regression metrics (MSE, RMSE, R2, MAE) after fitting', async () => { + const X = [[1], [2], [3], [4], [5]]; + const y = [3, 5, 7, 9, 11]; + + await lr.fit(X, y); + const metrics = lr.getMetrics(); + + expect(metrics.mse).toBeDefined(); + expect(metrics.rmse).toBeDefined(); + expect(metrics.r2Score).toBeDefined(); + expect(metrics.mae).toBeDefined(); + + expect(metrics.mse!).toBeGreaterThanOrEqual(0); + expect(metrics.rmse!).toBeGreaterThanOrEqual(0); + expect(metrics.mae!).toBeGreaterThanOrEqual(0); + expect(metrics.r2Score!).toBeGreaterThan(0.9); + expect(metrics.rmse!).toBeCloseTo(Math.sqrt(metrics.mse!), 4); + }); + }); + + describe('Visualization Data', () => { + it('should return empty array before training', () => { + expect(lr.getVisualizationData()).toEqual([]); + }); + + it('should produce 1D regression visualization elements (scatter, residuals, loss)', async () => { + const X = [[1], [2], [3], [4]]; + const y = [2, 4, 6, 8]; + + await lr.fit(X, y); + const viz = lr.getVisualizationData(); + + expect(Array.isArray(viz)).toBe(true); + expect(viz.length).toBe(3); + + const scatterViz = viz.find(v => v.type === 'scatter2d' && v.data?.line); + const residualsViz = viz.find(v => v.type === 'scatter2d' && v.data?.residuals); + const lossViz = viz.find(v => v.type === 'line' && v.data?.name === 'Training Loss'); + + expect(scatterViz).toBeDefined(); + expect(residualsViz).toBeDefined(); + expect(lossViz).toBeDefined(); + expect(lossViz!.data.x.length).toBe(80); + }); + + it('should produce training loss line for multi-dimensional data', async () => { + const X = [[1, 2], [2, 3], [3, 4]]; + const y = [5, 8, 11]; + + await lr.fit(X, y); + const viz = lr.getVisualizationData(); + + expect(viz.length).toBe(1); + expect(viz[0].type).toBe('line'); + }); + }); + + describe('Error Handling', () => { + it('should throw error when predicting before training', () => { + expect(() => lr.predict([[1]])).toThrow('Linear Regression must be trained before making predictions'); + }); + + it('should throw error when predicting with mismatched feature dimension', async () => { + const X = [[1], [2], [3]]; + const y = [2, 4, 6]; + + await lr.fit(X, y); + expect(() => lr.predict([[1, 2]])).toThrow(); + }); + + it('should reject training on empty dataset', async () => { + await expect(lr.fit([], [])).rejects.toThrow(); + }); + + it('should reject training when X and y lengths do not match', async () => { + const X = [[1], [2], [3]]; + const y = [1, 2]; + + await expect(lr.fit(X, y)).rejects.toThrow(); + }); + }); + + describe('Reset', () => { + it('should reset model state and require re-training', async () => { + const X = [[1], [2], [3]]; + const y = [2, 4, 6]; + + await lr.fit(X, y); + expect(() => lr.predict([[1]])).not.toThrow(); + + lr.reset(); + expect(() => lr.predict([[1]])).toThrow(); + expect(lr.getMetrics()).toEqual({}); + expect(lr.getVisualizationData()).toEqual([]); + expect(lr.getParameters().weights).toHaveLength(0); + }); + }); +}); diff --git a/tests/logistic-regression-algorithm.test.ts b/tests/logistic-regression-algorithm.test.ts new file mode 100644 index 0000000..8732781 --- /dev/null +++ b/tests/logistic-regression-algorithm.test.ts @@ -0,0 +1,243 @@ +/** + * Logistic Regression Algorithm Tests + * + * Tests for binary Logistic Regression algorithm (gradient descent optimization) + * Requirements: 2.3, 3.1, 4.1 + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { LogisticRegression } from '../algorithms/classification/LogisticRegression'; + +describe('LogisticRegression Algorithm', () => { + let lr: LogisticRegression; + + beforeEach(() => { + lr = new LogisticRegression({ + learningRate: 0.1, + epochs: 80, + normalize: false, + regularization: 0 + }); + }); + + describe('Basic Classification Functionality', () => { + it('should train and predict on linearly separable 2D data', async () => { + // Two well-separated clusters + const X = [ + [0.5, 0.5], + [0.8, 1.0], + [1.0, 0.6], + [5.0, 5.0], + [5.2, 5.5], + [5.5, 5.1] + ]; + const y = [0, 0, 0, 1, 1, 1]; + + await lr.fit(X, y); + const predictions = lr.predict(X); + + expect(predictions).toHaveLength(6); + expect(predictions).toEqual(y); + }); + + it('should classify unseen test points correctly', async () => { + const X = [ + [1, 1], + [1.5, 1.2], + [6, 6], + [6.5, 6.2] + ]; + const y = [0, 0, 1, 1]; + + await lr.fit(X, y); + + const testPoints = [[0.8, 0.9], [7.0, 7.0]]; + const predictions = lr.predict(testPoints); + + expect(predictions[0]).toBe(0); + expect(predictions[1]).toBe(1); + }); + + it('should output calibrated probabilities in range [0, 1]', async () => { + const X = [ + [1, 1], + [2, 2], + [7, 7], + [8, 8] + ]; + const y = [0, 0, 1, 1]; + + await lr.fit(X, y); + const probas = lr.predictProba(X); + + expect(probas).toHaveLength(4); + probas.forEach(p => { + expect(p).toBeGreaterThanOrEqual(0); + expect(p).toBeLessThanOrEqual(1); + }); + + // Class 0 points should have low p, Class 1 points should have high p + expect(probas[0]).toBeLessThan(0.5); + expect(probas[3]).toBeGreaterThan(0.5); + }); + }); + + describe('Regularization and Normalization', () => { + it('should train successfully with L2 regularization', async () => { + const lrReg = new LogisticRegression({ + learningRate: 0.1, + epochs: 60, + regularization: 0.1, + normalize: false + }); + + const X = [ + [0, 0], + [1, 0], + [4, 4], + [5, 4] + ]; + const y = [0, 0, 1, 1]; + + await lrReg.fit(X, y); + const predictions = lrReg.predict(X); + expect(predictions).toEqual(y); + }); + + it('should train successfully with feature normalization', async () => { + const lrNorm = new LogisticRegression({ + learningRate: 0.1, + epochs: 60, + normalize: true, + regularization: 0 + }); + + // Unnormalized scale differences + const X = [ + [1000, 0.01], + [1100, 0.02], + [5000, 0.8], + [5200, 0.9] + ]; + const y = [0, 0, 1, 1]; + + await lrNorm.fit(X, y); + const params = lrNorm.getParameters(); + expect(params.normalized).toBe(true); + + const predictions = lrNorm.predict(X); + expect(predictions).toEqual(y); + }); + }); + + describe('Metrics', () => { + it('should return empty metrics before fitting', () => { + expect(lr.getMetrics()).toEqual({}); + }); + + it('should calculate classification metrics (accuracy, precision, recall, f1, confusion matrix)', async () => { + const X = [ + [1, 1], + [2, 2], + [6, 6], + [7, 7] + ]; + const y = [0, 0, 1, 1]; + + await lr.fit(X, y); + const metrics = lr.getMetrics(); + + expect(metrics.accuracy).toBeDefined(); + expect(metrics.accuracy).toBe(1); + expect(metrics.precision).toBe(1); + expect(metrics.recall).toBe(1); + expect(metrics.f1Score).toBe(1); + + expect(metrics.confusionMatrix).toBeDefined(); + expect(metrics.confusionMatrix).toEqual([ + [2, 0], + [0, 2] + ]); + }); + }); + + describe('Visualization Data', () => { + it('should return empty array before training', () => { + expect(lr.getVisualizationData()).toEqual([]); + }); + + it('should return scatter plot, heatmap, loss and accuracy curves for 2D classification', async () => { + const X = [ + [1, 1], + [2, 2], + [6, 6], + [7, 7] + ]; + const y = [0, 0, 1, 1]; + + await lr.fit(X, y); + const viz = lr.getVisualizationData(); + + expect(Array.isArray(viz)).toBe(true); + expect(viz.length).toBeGreaterThanOrEqual(3); + + const scatter = viz.find(v => v.type === 'scatter2d' && v.data?.class0 && v.data?.class1); + const heatmap = viz.find(v => v.type === 'heatmap'); + const lossCurve = viz.find(v => v.type === 'line' && v.data?.name === 'Training Loss'); + const accuracyCurve = viz.find(v => v.type === 'line' && v.data?.name === 'Training Accuracy'); + + expect(scatter).toBeDefined(); + expect(heatmap).toBeDefined(); + expect(lossCurve).toBeDefined(); + expect(accuracyCurve).toBeDefined(); + }); + }); + + describe('Error Handling', () => { + it('should throw error when predicting before training', () => { + expect(() => lr.predict([[1, 1]])).toThrow('Logistic Regression must be trained before making predictions'); + }); + + it('should throw error when predictProba is called before training', () => { + expect(() => lr.predictProba([[1, 1]])).toThrow('Logistic Regression must be trained before making predictions'); + }); + + it('should enforce exactly 2 classes', async () => { + const X = [[1], [2], [3]]; + const y = [0, 1, 2]; + + await expect(lr.fit(X, y)).rejects.toThrow('Logistic Regression requires exactly 2 classes'); + }); + + it('should enforce class labels 0 and 1', async () => { + const X = [[1], [2]]; + const y = [1, 2]; + + await expect(lr.fit(X, y)).rejects.toThrow('Labels must be 0 and 1 for binary classification'); + }); + + it('should reject dimension mismatch on predict', async () => { + const X = [[1, 2], [3, 4]]; + const y = [0, 1]; + + await lr.fit(X, y); + expect(() => lr.predict([[1]])).toThrow(); + }); + }); + + describe('Reset', () => { + it('should reset model state and require re-training', async () => { + const X = [[1, 1], [4, 4]]; + const y = [0, 1]; + + await lr.fit(X, y); + expect(() => lr.predict([[1, 1]])).not.toThrow(); + + lr.reset(); + expect(() => lr.predict([[1, 1]])).toThrow(); + expect(lr.getMetrics()).toEqual({}); + expect(lr.getVisualizationData()).toEqual([]); + expect(lr.getParameters().weights).toHaveLength(0); + }); + }); +});