Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
## Machine Learning
* [Gradient Boosting](https://github.com/TheAlgorithms/R/blob/HEAD/machine_learning/gradient_boosting.r)
* [Perceptron](https://github.com/TheAlgorithms/R/blob/HEAD/machine_learning/perceptron.r)
* [Sefr](https://github.com/TheAlgorithms/R/blob/HEAD/machine_learning/sefr.r)


## Mathematics
Expand Down
112 changes: 112 additions & 0 deletions machine_learning/sefr.r
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# sefr.r
# SEFR: a 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 (positive and negative), each feature j is first min-max
# scaled to [0, 1] using the training data. Then:
# p_j = mean of feature j over the positive samples
# n_j = mean of feature j over the negative samples
# w_j = (p_j - n_j) / (p_j + n_j)
# so every weight lies in [-1, 1]. The sample scores s = w . x give a
# threshold b, the average of the two class mean scores weighted by the
# size of the opposite class:
# b = (N_neg * mean(s | positive) + N_pos * mean(s | negative)) / N
# A sample is labelled positive when w . x - b > 0.
#
# More than two classes are handled one-vs-rest: one weight vector per class,
# and the predicted class is the one with the largest w . x - b.
#
# Input: a numeric matrix or data.frame X (rows are samples) and a vector or
# factor y of class labels with at least two distinct values.
# Output: a model list; sefr_predict() returns predicted labels.
# Dependencies: base R only.
#
# Time Complexity: training O(n_samples * n_features + n_classes * n_features)
# prediction O(n_classes * n_features) per sample
# Space Complexity: O(n_classes * n_features)
#
# Reference: H. Keshavarz, M. S. Abadeh, R. Rawassizadeh, "SEFR: A Fast Linear-Time
# Classifier for Ultra-Low Power Devices", https://arxiv.org/abs/2006.04620

sefr_check_matrix <- function(X) {
if (is.data.frame(X)) X <- as.matrix(X)
if (is.vector(X)) X <- matrix(X, nrow = 1)
if (!is.matrix(X) || !is.numeric(X)) stop("X must be a numeric matrix or data.frame.")
if (any(is.na(X))) stop("X must not contain missing values.")
X
}

sefr_fit <- function(X, y) {
X <- sefr_check_matrix(X)
if (length(y) != nrow(X)) stop("Length of y must match the number of rows of X.")
if (any(is.na(y))) stop("y must not contain missing values.")
y <- as.character(y)
classes <- sort(unique(y))
if (length(classes) < 2) stop("SEFR needs at least two classes.")

# Min-max scaling to [0, 1]; constant features get range 1 and end up at 0.
feature_min <- apply(X, 2, min)
feature_range <- apply(X, 2, max) - feature_min
feature_range[feature_range == 0] <- 1
Z <- sweep(sweep(X, 2, feature_min), 2, feature_range, "/")

# Two classes need one weight vector, scored for the second class.
heads <- if (length(classes) == 2) classes[2] else classes
weights <- matrix(0, nrow = length(heads), ncol = ncol(Z), dimnames = list(heads, colnames(X)))
bias <- setNames(numeric(length(heads)), heads)

class_ids <- match(y, classes)
class_counts <- tabulate(class_ids, nbins = length(classes))
class_sums <- rowsum(Z, group = class_ids, reorder = TRUE)
total_sums <- colSums(class_sums)
head_ids <- match(heads, classes)

for (k in seq_along(heads)) {
n_pos <- class_counts[head_ids[k]]
n_neg <- nrow(Z) - n_pos
pos_sum <- class_sums[head_ids[k], ]
p <- pos_sum / n_pos
n <- (total_sums - pos_sum) / n_neg
denom <- p + n
w <- ifelse(denom > 0, (p - n) / denom, 0)
weights[k, ] <- w
bias[k] <- (n_neg * sum(p * w) + n_pos * sum(n * w)) / (n_pos + n_neg)
}

list(classes = classes, weights = weights, bias = bias,
feature_min = feature_min, feature_range = feature_range)
}

# Decision scores w . x - b, one column per weight vector.
sefr_decision_function <- function(model, X) {
X <- sefr_check_matrix(X)
if (ncol(X) != ncol(model$weights)) stop("X has a different number of features than the training data.")
Z <- sweep(sweep(X, 2, model$feature_min), 2, model$feature_range, "/")
sweep(Z %*% t(model$weights), 2, model$bias)
}

sefr_predict <- function(model, X) {
scores <- sefr_decision_function(model, X)
if (length(model$classes) == 2) {
return(unname(ifelse(scores[, 1] > 0, model$classes[2], model$classes[1])))
}
model$classes[max.col(scores, ties.method = "first")]
}

# Example usage
# Binary: a small hand-made dataset where the classes differ in both features.
X_small <- matrix(c(1, 2, 2, 1, 2, 3, 8, 9, 9, 8, 7, 9), ncol = 2, byrow = TRUE)
y_small <- c("a", "a", "a", "b", "b", "b")
model_small <- sefr_fit(X_small, y_small)
print(model_small$weights)
print(sefr_predict(model_small, rbind(c(1.5, 1.5), c(8.5, 8.5)))) # "a" "b"

# Multiclass: iris, with a random 70/30 split.
set.seed(42)
train_idx <- sample(nrow(iris), 105)
model_iris <- sefr_fit(iris[train_idx, 1:4], iris$Species[train_idx])
pred <- sefr_predict(model_iris, iris[-train_idx, 1:4])
cat("Iris test accuracy:", mean(pred == as.character(iris$Species[-train_idx])), "\n")
Loading