StandardScaler mock in Python

A pure-Python StandarScaler class that standardizes features to zero mean and unit variance without sklearn.

Easy Python 3.9+ Aug 9, 2026 ML engineering pipelines 12 views 0 copies

Python code

32 lines
Python 3.9+
import math

class StandardScaler:
    def __init__(self):
        self.mean_ = None
        self.std_ = None

    def fit(self, X):
        n = len(X)
        self.mean_ = [sum(col) / n for col in zip(*X)]
        self.std_ = []
        for col in zip(*X):
            variance = sum((x - self.mean_[i]) ** 2 for i, x in enumerate(col)) / n
            self.std_.append(math.sqrt(variance))
        return self

    def transform(self, X):
        if self.mean_ is None or self.std_ is None:
            raise ValueError("Scaler not fitted yet")
        return [[(x - self.mean_[i]) / self.std_[i] for i, x in enumerate(row)] for row in X]

    def fit_transform(self, X):
        return self.fit(X).transform(X)


if __name__ == "__main__":
    data = [[1, 2], [3, 4], [5, 6]]
    scaler = StandardScaler()
    scaled = scaler.fit_transform(data)
    print(f"Means: {scaler.mean_}")
    print(f"Stds: {scaler.std_}")
    print(f"Scaled data: {scaled}")

Output

stdout
Means: [3.0, 4.0]
Stds: [1.632993161855452, 1.632993161855452]
Scaled data: [[-1.224744871391589, -1.224744871391589], [0.0, 0.0], [1.224744871391589, 1.224744871391589]]

How it works

The fit method computes the mean and standard deviation for each feature column using zip(*X) to transpose the list of lists. Population standard deviation is used (divide by n), not sample standard deviation, matching sklearn's default behavior. The transform method then subtracts the mean and divides by the standard deviation for each element, producing standardized columns. By merging fit and transform in fit_transform, you can standardize data in one call after fitting the scaler.

Common mistakes

  • Using sample standard deviation (n-1) instead of population (n) — gives slightly different scaling.
  • Forgetting to call fit before transform, causing a ValueError.
  • Assuming the input is a NumPy array; this code works with regular Python lists.
  • Not handling zero standard deviation columns, which would cause division by zero.

Variations

  1. Use sklearn's StandardScaler with with_mean=True and with_std=True for the same result.
  2. Implement using NumPy and vectorized operations for better performance on large datasets.

Real-world use cases

  • Preprocessing features before training a machine learning model to ensure equal scale contribution.
  • Scaling input columns for clustering algorithms like k-means so distance measures are meaningful.
  • Standardizing data for dimensionality reduction methods like PCA to meet variance assumptions.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from ML engineering pipelines

Related tutorials and quizzes for this topic.