Example 08
beginner
08
Classification
ML Basics

Logistic Regression

Logistic regression models the probability of class membership using a sigmoid function. This example loads the Iris dataset, filters to two classes (setosa vs. versicolor) for binary classification, splits and scales the data, trains a LogisticRegression model, evaluates with accuracy, precision, recall, F1 score, and displays the confusion matrix. You will see how logistic regression outputs probabilities that are thresholded at 0.5 to produce class predictions, and why it is one of the most widely used baselines for classification tasks.

Deepbox Modules Used

deepbox/datasetsdeepbox/mldeepbox/metricsdeepbox/preprocess

What You Will Learn

  • Train a LogisticRegression classifier for binary classification
  • Preprocess with StandardScaler for better convergence
  • Evaluate with accuracy, precision, recall, F1 score
  • Read confusion matrices: rows are true labels, columns are predictions

Source Code

08-logistic-regression/index.ts
1import { loadIris } from "deepbox/datasets";2import { LogisticRegression } from "deepbox/ml";3import { accuracy, confusionMatrix, f1Score, precision, recall } from "deepbox/metrics";4import { StandardScaler, trainTestSplit } from "deepbox/preprocess";56console.log("=== Logistic Regression ===\n");78// Load Iris and filter to binary (setosa vs versicolor)9const iris = loadIris();10// ... filter to classes 0 and 1 ...1112const [X_train, X_test, y_train, y_test] = trainTestSplit(13  X_binary, y_binary, { testSize: 0.2, randomState: 42 }14);1516const scaler = new StandardScaler();17scaler.fit(X_train);18const X_tr = scaler.transform(X_train);19const X_te = scaler.transform(X_test);2021const model = new LogisticRegression();22model.fit(X_tr, y_train);23const preds = model.predict(X_te);2425console.log("Accuracy: ", accuracy(y_test, preds).toFixed(3));26console.log("Precision:", precision(y_test, preds).toFixed(3));27console.log("Recall:   ", recall(y_test, preds).toFixed(3));28console.log("F1 Score: ", f1Score(y_test, preds).toFixed(3));29console.log("\nConfusion Matrix:");30console.log(confusionMatrix(y_test, preds).toString());

Console Output

$ npx tsx 08-logistic-regression/index.ts
=== Logistic Regression ===

Accuracy:  1.000
Precision: 1.000
Recall:    1.000
F1 Score:  1.000

Confusion Matrix:
[[10,  0],
 [ 0, 10]]