🐍 High-Performance Python for Data Science & Machine Learning
While beginner Python tutorials focus on basic lists and dictionaries, professional data science and machine learning engineering require deep mastery of advanced built-in collections, memory-efficient generators, custom iterators, decorators, and object-oriented design patterns. This guide explores 10 real-world Python engineering patterns optimized for high-throughput data processing and modeling pipelines.
dataclasses provide a clean, typed structure for organizing feature records or configuration parameters without the verbosity of traditional classes.
from dataclasses import dataclass, field
from typing import List
@dataclass
def compute_default_weights():
return [1.0, 1.0, 1.0]
@dataclass
def PatientRecord:
patient_id: str
age: int
biomarkers: List[float]
risk_score: float = 0.0
weights: List[float] = field(default_factory=compute_default_weights)
def calculate_risk(self):
self.risk_score = sum(self.biomarkers) * 0.15 + (self.age * 0.05)
return self.risk_score
def run_dataclass_demo():
print("=" * 65)
print("📋 EXAMPLE 1: STRUCTURED FEATURE RECORDS VIA DATACLASSES")
print("=" * 65)
patient = PatientRecord(patient_id="PT-9021", age=45, biomarkers=[12.5, 8.2, 5.1])
score = patient.calculate_risk()
print(f"Patient Record : {patient}")
print(f"Computed Risk : {score:.2f}")
print("=" * 65)
if __name__ == "__main__":
run_dataclass_demo()
collections.defaultdict eliminates KeyErrors by automatically initializing missing keys with default values.
from collections import defaultdict
def run_defaultdict_demo():
print("=" * 65)
print("🗂️ EXAMPLE 2: MISSING KEY HANDLING VIA DEFAULTDICT")
print("=" * 65)
corpus = ["machine", "learning", "machine", "data", "science", "data", "data"]
# Automatically initialize missing word counts to integer 0
word_counts = defaultdict(int)
for word in corpus:
word_counts[word] += 1
print(f"Corpus Vocabulary Frequencies:")
for word, count in word_counts.items():
print(f" '{word}': {count}")
print("=" * 65)
if __name__ == "__main__":
run_defaultdict_demo()
collections.Counter is a specialized dictionary subclass designed for counting hashable objects, offering built-in methods like most_common(n) for feature extraction.
from collections import Counter
def run_counter_demo():
print("=" * 65)
print("📊 EXAMPLE 3: FREQUENCY ANALYSIS & TOP-N VIA COUNTER")
print("=" * 65)
tokens = ["the", "model", "accuracy", "is", "high", "the", "model", "loss", "is", "low", "model", "accuracy"]
counter = Counter(tokens)
top_2 = counter.most_common(2)
print(f"Full Token Counts : {counter}")
print(f"Top 2 Frequent : {top_2}")
print("=" * 65)
if __name__ == "__main__":
run_counter_demo()
collections.deque (double-ended queue) provides $O(1)$ time complexity for appends and pops from both ends, making it ideal for streaming time-series moving averages.
from collections import deque
class MovingAverageStream:
def __init__(self, window_size: int):
self.window = deque(maxlen=window_size)
def update(self, val: float) -> float:
self.window.append(val)
return sum(self.window) / len(self.window)
def run_deque_demo():
print("=" * 65)
print("🔄 EXAMPLE 4: SLIDING WINDOW MOVING AVERAGE VIA DEQUE")
print("=" * 65)
stream = MovingAverageStream(window_size=3)
readings = [10.0, 20.0, 30.0, 40.0, 50.0]
for val in readings:
avg = stream.update(val)
print(f"Added: {val} -> Moving Average (Window=3): {avg:.2f}")
print("=" * 65)
if __name__ == "__main__":
run_deque_demo()
heapq module implements min-heaps, allowing efficient retrieval of the largest or smallest $K$ elements in $O(N \log K)$ time without fully sorting massive datasets.
import heapq
def run_heapq_demo():
print("=" * 65)
print("🏆 EXAMPLE 5: TOP-K RECOMMENDATIONS VIA HEAPQ")
print("=" * 65)
# Item relevance scores from a recommender model
scores = [0.12, 0.95, 0.45, 0.88, 0.33, 0.99, 0.75]
k = 3
# Extract top 3 highest scores efficiently
top_k_scores = heapq.nlargest(k, scores)
print(f"All Scores : {scores}")
print(f"Top {k} Scores: {top_k_scores}")
print("=" * 65)
if __name__ == "__main__":
run_heapq_demo()
yield keyword to produce values lazily one-by-one, preventing RAM exhaustion when processing massive CSV log files or multi-gigabyte datasets.
def stream_large_dataset(filepath: str, mock_lines: list):
"""Simulates lazy streaming of lines from a massive file."""
for line in mock_lines:
yield line.strip().upper()
def run_generator_demo():
print("=" * 65)
print("⚡ EXAMPLE 6: LAZY STREAMING VIA GENERATORS")
print("=" * 65)
simulated_file = ["user_1,click", "user_2,purchase", "user_3,view"]
stream = stream_large_dataset("dummy.csv", simulated_file)
for record in stream:
print(f"Streamed & Processed Record: {record}")
print("=" * 65)
if __name__ == "__main__":
run_generator_demo()
class BatchDatasetIterator:
def __init__(self, data: list, batch_size: int):
self.data = data
self.batch_size = batch_size
self.index = 0
def __iter__(self):
self.index = 0
return self
def __next__(self):
if self.index >= len(self.data):
raise StopIteration
batch = self.data[self.index : self.index + self.batch_size]
self.index += self.batch_size
return batch
def run_iterator_demo():
print("=" * 65)
print("🔄 EXAMPLE 7: CUSTOM ITERATOR FOR ML BATCHING")
print("=" * 65)
dataset = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
loader = BatchDatasetIterator(dataset, batch_size=3)
for i, batch in enumerate(loader, 1):
print(f"Batch {i}: {batch}")
print("=" * 65)
if __name__ == "__main__":
run_iterator_demo()
import time
from functools import wraps
def time_execution(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
duration = time.time() - start_time
print(f"[Execution Timer] Function '{func.__name__}' took {duration:.4f} seconds.")
return result
return wrapper
@time_execution
def train_dummy_model(epochs: int):
time.sleep(0.1) # Simulate training delay
return f"Model trained for {epochs} epochs."
def run_decorator_demo():
print("=" * 65)
print("⏱️ EXAMPLE 8: EXECUTION TIMING DECORATOR")
print("=" * 65)
res = train_dummy_model(10)
print(res)
print("=" * 65)
if __name__ == "__main__":
run_decorator_demo()
fit and transform methods).
import numpy as np
class CustomStandardScaler:
def fit(self, X):
self.mean_ = np.mean(X, axis=0)
self.scale_ = np.std(X, axis=0)
return self
def transform(self, X):
return (X - self.mean_) / (self.scale_ + 1e-8)
def fit_transform(self, X):
return self.fit(X).transform(X)
def run_oop_demo():
print("=" * 65)
print("🏗️ EXAMPLE 9: OBJECT-ORIENTED CUSTOM DATA SCALER")
print("=" * 65)
X = np.array([[10.0, 100.0], [20.0, 200.0], [30.0, 300.0]])
scaler = CustomStandardScaler()
X_scaled = scaler.fit_transform(X)
print(f"Original Data :\n{X}")
print(f"Scaled Data :\n{np.round(X_scaled, 2)}")
print("=" * 65)
if __name__ == "__main__":
run_oop_demo()
__slots__ restricts attributes to a fixed array, drastically reducing memory overhead.
import sys
class StandardFeaturePoint:
def __init__(self, x: float, y: float, label: int):
self.x = x
self.y = y
self.label = label
class SlottedFeaturePoint:
__slots__ = ['x', 'y', 'label']
def __init__(self, x: float, y: float, label: int):
self.x = x
self.y = y
self.label = label
def run_slots_demo():
print("=" * 65)
print("💾 EXAMPLE 10: MEMORY OPTIMIZATION VIA __slots__")
print("=" * 65)
std_obj = StandardFeaturePoint(1.5, 2.5, 1)
slot_obj = SlottedFeaturePoint(1.5, 2.5, 1)
print(f"Standard Object Size (__dict__) : {sys.getsizeof(std_obj.__dict__) + sys.getsizeof(std_obj)} bytes")
print(f"Slotted Object Size (__slots__): {sys.getsizeof(slot_obj)} bytes")
print("=" * 65)
if __name__ == "__main__":
run_slots_demo()