StandardScaler mock in Python
A pure-Python StandarScaler class that standardizes features to zero mean and unit variance without sklearn.
Python code
32 linesimport 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
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
- Use sklearn's StandardScaler with with_mean=True and with_std=True for the same result.
- 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
More from ML engineering pipelines
- Bayesian Optimization in Python: A Simplified Mock Implementation medium
- Build a Data Helper Class in Python for ML Pipelines easy
- Build a Mock Random Forest Classifier in Python easy
- Champion Challenger Deployment Mock in Python easy
- Compare Model A vs Model B Metrics in Python easy
- Create a Minimal Great Expectations Suite Mock in Python easy
Keep learning
Related tutorials and quizzes for this topic.