From 9fda8f362ba03f8d3cdd84588511d2eeee7c0042 Mon Sep 17 00:00:00 2001 From: Hamidreza Keshavarz <32555614+hamidkm9@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:25:08 +0100 Subject: [PATCH 1/2] feat: add SEFR linear classifier Co-Authored-By: Claude Opus 5.5 --- .../thealgorithms/machinelearning/Sefr.java | 242 ++++++++++++++++++ .../machinelearning/SefrTest.java | 86 +++++++ 2 files changed, 328 insertions(+) create mode 100644 src/main/java/com/thealgorithms/machinelearning/Sefr.java create mode 100644 src/test/java/com/thealgorithms/machinelearning/SefrTest.java diff --git a/src/main/java/com/thealgorithms/machinelearning/Sefr.java b/src/main/java/com/thealgorithms/machinelearning/Sefr.java new file mode 100644 index 000000000000..52abb85f2289 --- /dev/null +++ b/src/main/java/com/thealgorithms/machinelearning/Sefr.java @@ -0,0 +1,242 @@ +package com.thealgorithms.machinelearning; + +import java.util.Arrays; + +/** + * SEFR (Simple, Effective and Fast linear classifieR). + * + *

SEFR trains a linear classifier in a single pass over the data, with no + * iterations, no learning rate and no hyperparameters. It was designed for + * training on very small devices such as microcontrollers. + * + *

For two classes, every feature is first min-max scaled to [0, 1] with the + * training data. With {@code p[j]} and {@code n[j]} the means of feature + * {@code j} over the positive and the negative samples, the weight is + * {@code w[j] = (p[j] - n[j]) / (p[j] + n[j])}, so every weight lies in + * [-1, 1]. The threshold {@code b} is the average of the two class mean scores + * {@code w . x}, weighted by the size of the opposite class. A sample is + * positive when {@code w . x - b > 0}. + * + *

Labels may be any integers. With two distinct labels, the larger one is + * treated as the positive class. With more labels, one weight vector is + * trained per label (one-vs-rest) and the label with the largest score + * {@code w . x - b} is predicted. + * + *

Training takes O(samples * features + classes * features) time and the + * model takes O(classes * features) space. + * + * @see SEFR: A Fast Linear-Time + * Classifier for Ultra-Low Power Devices + */ +public final class Sefr { + private int[] classes; + private double[][] weights; + private double[] bias; + private double[] featureMin; + private double[] featureRange; + + /** + * Fits the classifier. + * + * @param features training samples, one row per sample, all rows of equal + * length + * @param labels class label of each row of {@code features} + * @throws IllegalArgumentException if the inputs are empty, of different + * lengths, not finite, or hold fewer than + * two distinct labels + */ + public void fit(double[][] features, int[] labels) { + if (features == null || labels == null || features.length == 0 || features.length != labels.length) { + throw new IllegalArgumentException("features and labels must be non-empty and of equal length"); + } + final int numFeatures = features[0].length; + if (numFeatures == 0) { + throw new IllegalArgumentException("samples must have at least one feature"); + } + for (double[] row : features) { + checkRow(row, numFeatures); + } + final int[] sortedLabels = Arrays.stream(labels).distinct().sorted().toArray(); + if (sortedLabels.length < 2) { + throw new IllegalArgumentException("SEFR needs at least two distinct labels"); + } + + final double[] min = features[0].clone(); + final double[] range = features[0].clone(); + for (double[] row : features) { + for (int j = 0; j < numFeatures; j++) { + min[j] = Math.min(min[j], row[j]); + range[j] = Math.max(range[j], row[j]); + } + } + for (int j = 0; j < numFeatures; j++) { + range[j] -= min[j]; + if (range[j] == 0.0) { + range[j] = 1.0; + } + } + + // Two classes need a single weight vector, scored for the larger label. + final int[] positives = sortedLabels.length == 2 ? new int[] {sortedLabels[1]} : sortedLabels; + final double[][] scaled = new double[features.length][]; + for (int i = 0; i < features.length; i++) { + scaled[i] = scale(features[i], min, range); + } + final double[][] w = new double[positives.length][]; + final double[] b = new double[positives.length]; + for (int k = 0; k < positives.length; k++) { + w[k] = trainWeights(scaled, labels, positives[k]); + b[k] = trainBias(scaled, labels, positives[k], w[k]); + } + + this.classes = sortedLabels; + this.featureMin = min; + this.featureRange = range; + this.weights = w; + this.bias = b; + } + + /** + * Returns the score {@code w . x - b} of one sample for each weight vector. + * With two classes there is a single score, positive for the larger label. + * + * @param sample feature vector with as many values as the training rows + * @return one score per weight vector + * @throws IllegalStateException if the classifier has not been fitted + * @throws IllegalArgumentException if the sample has the wrong length or is + * not finite + */ + public double[] decisionFunction(double[] sample) { + if (weights == null) { + throw new IllegalStateException("classifier has not been fitted"); + } + checkRow(sample, featureMin.length); + final double[] z = scale(sample, featureMin, featureRange); + final double[] scores = new double[weights.length]; + for (int k = 0; k < weights.length; k++) { + scores[k] = dot(weights[k], z) - bias[k]; + } + return scores; + } + + /** + * Predicts the label of one sample. + * + * @param sample feature vector with as many values as the training rows + * @return the predicted label + */ + public int predict(double[] sample) { + final double[] scores = decisionFunction(sample); + if (classes.length == 2) { + return scores[0] > 0.0 ? classes[1] : classes[0]; + } + int best = 0; + for (int k = 1; k < scores.length; k++) { + if (scores[k] > scores[best]) { + best = k; + } + } + return classes[best]; + } + + /** + * Predicts the labels of several samples. + * + * @param samples feature vectors, one row per sample + * @return the predicted label of each row + */ + public int[] predict(double[][] samples) { + final int[] predictions = new int[samples.length]; + for (int i = 0; i < samples.length; i++) { + predictions[i] = predict(samples[i]); + } + return predictions; + } + + /** + * Returns a copy of the weight vectors, one row per weight vector, in the + * min-max scaled feature space. + * + * @return the weights + * @throws IllegalStateException if the classifier has not been fitted + */ + public double[][] getWeights() { + if (weights == null) { + throw new IllegalStateException("classifier has not been fitted"); + } + final double[][] copy = new double[weights.length][]; + for (int k = 0; k < weights.length; k++) { + copy[k] = weights[k].clone(); + } + return copy; + } + + private static double[] trainWeights(double[][] scaled, int[] labels, int positive) { + final int numFeatures = scaled[0].length; + final double[] posSum = new double[numFeatures]; + final double[] negSum = new double[numFeatures]; + int numPos = 0; + for (int i = 0; i < scaled.length; i++) { + final double[] target = labels[i] == positive ? posSum : negSum; + if (labels[i] == positive) { + numPos++; + } + for (int j = 0; j < numFeatures; j++) { + target[j] += scaled[i][j]; + } + } + final int numNeg = scaled.length - numPos; + final double[] w = new double[numFeatures]; + for (int j = 0; j < numFeatures; j++) { + final double p = posSum[j] / numPos; + final double n = negSum[j] / numNeg; + w[j] = p + n > 0.0 ? (p - n) / (p + n) : 0.0; + } + return w; + } + + private static double trainBias(double[][] scaled, int[] labels, int positive, double[] w) { + double posScore = 0.0; + double negScore = 0.0; + int numPos = 0; + for (int i = 0; i < scaled.length; i++) { + final double s = dot(w, scaled[i]); + if (labels[i] == positive) { + posScore += s; + numPos++; + } else { + negScore += s; + } + } + final int numNeg = scaled.length - numPos; + // Mean scores of each class, weighted by the size of the opposite class. + return (numNeg * (posScore / numPos) + numPos * (negScore / numNeg)) / scaled.length; + } + + private static double[] scale(double[] row, double[] min, double[] range) { + final double[] z = new double[row.length]; + for (int j = 0; j < row.length; j++) { + z[j] = (row[j] - min[j]) / range[j]; + } + return z; + } + + private static double dot(double[] a, double[] b) { + double s = 0.0; + for (int j = 0; j < a.length; j++) { + s += a[j] * b[j]; + } + return s; + } + + private static void checkRow(double[] row, int numFeatures) { + if (row == null || row.length != numFeatures) { + throw new IllegalArgumentException("every sample must have " + numFeatures + " features"); + } + for (double v : row) { + if (!Double.isFinite(v)) { + throw new IllegalArgumentException("features must be finite numbers"); + } + } + } +} diff --git a/src/test/java/com/thealgorithms/machinelearning/SefrTest.java b/src/test/java/com/thealgorithms/machinelearning/SefrTest.java new file mode 100644 index 000000000000..7b3cea38b76e --- /dev/null +++ b/src/test/java/com/thealgorithms/machinelearning/SefrTest.java @@ -0,0 +1,86 @@ +package com.thealgorithms.machinelearning; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +class SefrTest { + + @Test + void computesWeightsAndBiasByHand() { + // Scaled to [0, 1]: class 0 rows are {0, 0} and {0, 1}, class 1 rows are {1, 0} and {1, 1}. + // p = {1, 0.5}, n = {0, 0.5}, so w = {1, 0}; scores are 0, 0, 1, 1 and b = 0.5. + double[][] features = {{2, 10}, {2, 20}, {4, 10}, {4, 20}}; + int[] labels = {0, 0, 1, 1}; + Sefr sefr = new Sefr(); + sefr.fit(features, labels); + + assertArrayEquals(new double[] {1.0, 0.0}, sefr.getWeights()[0], 1e-12); + assertEquals(0.5, sefr.decisionFunction(new double[] {4, 15})[0], 1e-12); + assertEquals(-0.5, sefr.decisionFunction(new double[] {2, 15})[0], 1e-12); + } + + @Test + void weightsStayWithinMinusOneAndOne() { + double[][] features = {{1, 9, 3}, {2, 8, 3}, {7, 1, 5}, {8, 2, 4}, {3, 5, 9}}; + int[] labels = {0, 0, 1, 1, 0}; + Sefr sefr = new Sefr(); + sefr.fit(features, labels); + for (double w : sefr.getWeights()[0]) { + assertTrue(w >= -1.0 && w <= 1.0); + } + } + + @Test + void separatesTwoClusters() { + double[][] features = {{1, 2}, {2, 1}, {2, 3}, {8, 9}, {9, 8}, {7, 9}}; + int[] labels = {3, 3, 3, 7, 7, 7}; + Sefr sefr = new Sefr(); + sefr.fit(features, labels); + + assertArrayEquals(labels, sefr.predict(features)); + assertEquals(3, sefr.predict(new double[] {1.5, 1.5})); + assertEquals(7, sefr.predict(new double[] {8.5, 8.5})); + } + + @Test + void handlesThreeClassesOneVsRest() { + double[][] features = {{0, 0}, {1, 0}, {0, 1}, {10, 0}, {11, 1}, {10, 1}, {0, 10}, {1, 11}, {1, 10}}; + int[] labels = {0, 0, 0, 1, 1, 1, 2, 2, 2}; + Sefr sefr = new Sefr(); + sefr.fit(features, labels); + + assertEquals(3, sefr.getWeights().length); + assertEquals(0, sefr.predict(new double[] {0.5, 0.5})); + assertEquals(1, sefr.predict(new double[] {10.5, 0.5})); + assertEquals(2, sefr.predict(new double[] {0.5, 10.5})); + } + + @Test + void constantFeatureGetsZeroWeight() { + double[][] features = {{5, 0}, {5, 1}, {5, 9}, {5, 10}}; + int[] labels = {0, 0, 1, 1}; + Sefr sefr = new Sefr(); + sefr.fit(features, labels); + + assertEquals(0.0, sefr.getWeights()[0][0], 1e-12); + assertEquals(1, sefr.predict(new double[] {5, 9.5})); + } + + @Test + void rejectsInvalidInput() { + Sefr sefr = new Sefr(); + assertThrows(IllegalStateException.class, () -> sefr.predict(new double[] {1, 2})); + assertThrows(IllegalArgumentException.class, () -> sefr.fit(new double[0][0], new int[0])); + assertThrows(IllegalArgumentException.class, () -> sefr.fit(new double[][] {{1}, {2}}, new int[] {0})); + assertThrows(IllegalArgumentException.class, () -> sefr.fit(new double[][] {{1}, {2}}, new int[] {0, 0})); + assertThrows(IllegalArgumentException.class, () -> sefr.fit(new double[][] {{1, 2}, {3}}, new int[] {0, 1})); + assertThrows(IllegalArgumentException.class, () -> sefr.fit(new double[][] {{1}, {Double.NaN}}, new int[] {0, 1})); + + sefr.fit(new double[][] {{1, 2}, {3, 4}}, new int[] {0, 1}); + assertThrows(IllegalArgumentException.class, () -> sefr.predict(new double[] {1})); + } +} From 9d350f021f2d6249041744efa9a2459c01671a55 Mon Sep 17 00:00:00 2001 From: Hamidreza Keshavarz <32555614+hamidkm9@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:51:50 +0100 Subject: [PATCH 2/2] test: cover the remaining input checks in SefrTest Co-Authored-By: Claude Opus 5.5 --- .../java/com/thealgorithms/machinelearning/SefrTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/test/java/com/thealgorithms/machinelearning/SefrTest.java b/src/test/java/com/thealgorithms/machinelearning/SefrTest.java index 7b3cea38b76e..63b265f2b356 100644 --- a/src/test/java/com/thealgorithms/machinelearning/SefrTest.java +++ b/src/test/java/com/thealgorithms/machinelearning/SefrTest.java @@ -74,7 +74,12 @@ void constantFeatureGetsZeroWeight() { void rejectsInvalidInput() { Sefr sefr = new Sefr(); assertThrows(IllegalStateException.class, () -> sefr.predict(new double[] {1, 2})); + assertThrows(IllegalStateException.class, sefr::getWeights); + assertThrows(IllegalArgumentException.class, () -> sefr.fit(null, new int[] {0, 1})); + assertThrows(IllegalArgumentException.class, () -> sefr.fit(new double[][] {{1}, {2}}, null)); assertThrows(IllegalArgumentException.class, () -> sefr.fit(new double[0][0], new int[0])); + assertThrows(IllegalArgumentException.class, () -> sefr.fit(new double[][] {{}, {}}, new int[] {0, 1})); + assertThrows(IllegalArgumentException.class, () -> sefr.fit(new double[][] {{1}, null}, new int[] {0, 1})); assertThrows(IllegalArgumentException.class, () -> sefr.fit(new double[][] {{1}, {2}}, new int[] {0})); assertThrows(IllegalArgumentException.class, () -> sefr.fit(new double[][] {{1}, {2}}, new int[] {0, 0})); assertThrows(IllegalArgumentException.class, () -> sefr.fit(new double[][] {{1, 2}, {3}}, new int[] {0, 1}));