Coding for MLintermediatemust-know5 min

Implement Linear Regression from Scratch

Code linear regression from scratch with NumPy, a classic interview task.

Implement Linear Regression from Scratch demonstrates foundational machine learning coding fundamentals. The model fits a linear equation predicting continuous outputs by minimizing Mean Squared Error loss. The implementation covers weight and bias vector initialization, forward pass matrix multiplication, analytical prediction error calculation, and gradient descent backpropagation updates.

Coding for MLadvancedmust-know5 min

Implement Self-Attention from Scratch

Code attention from scratch in PyTorch, line by line.

Implement Self-Attention from Scratch builds the core mechanism of Transformer models. Scaled Dot-Product Attention transforms input sequence vectors into Query, Key, and Value matrices. The algorithm calculates query-key similarity dot products, scales by the square root of key dimension, applies Softmax normalization, and computes weighted sums over Value vectors.

Coding for MLbeginner5 min

NumPy Broadcasting & Vectorization

How NumPy combines arrays of different shapes, and how it bites you.

NumPy Broadcasting and Vectorization enables fast array operations without explicit C or Python loops. Broadcasting defines rules for operating on arrays of different shapes by implicitly stretching smaller dimensions. Vectorized operations execute low level BLAS linear algebra instructions, achieving 100x speedup over Python loops.

Coding for MLbeginner5 min

Pandas: GroupBy, Merge, Window

The pandas operations behind most feature engineering.

Pandas GroupBy, Merge, and Rolling Window functions form the primary toolkit for tabular feature engineering. GroupBy aggregates records across categorical partitions, Merge combines DataFrames using relational database join logic, and Rolling Window functions compute temporal moving averages. Writing clean Pandas operations enables rapid feature extraction for machine learning models.

Coding for MLintermediate5 min

Implement Logistic Regression from Scratch

Code logistic regression from scratch, from the sigmoid to the loss.

Implement Logistic Regression from Scratch covers binary classification coding fundamentals. The model transforms linear combination logits into probability values between 0 and 1 using the Sigmoid activation function. The implementation calculates Binary Cross Entropy loss gradients and updates weights via gradient descent.

Coding for MLintermediate5 min

Implement k-Means from Scratch

Code k-means from scratch in a few clean lines.

Implement k-Means from Scratch builds the classic unsupervised clustering algorithm using NumPy. The algorithm partitions unlabeled data into K distinct clusters by alternating between assigning points to the nearest centroid and recomputing centroids as class means until convergence. The implementation covers centroid initialization strategies, Euclidean distance matrix calculation, cluster assignment, and centroid mean updates.

Coding for MLintermediate5 min

Implement k-NN Efficiently

Code k-nearest neighbours fast, without slow loops.

Implementing k-nearest neighbours efficiently is a common coding question. There is no training step: you just store the data. The slow part is prediction, which needs the distance from each new point to every stored point. Looping over pairs is far too slow, so compute all distances at once with matrix operations, using the fact that squared distance equals both squared lengths added together minus twice their dot product. Then take the k smallest with a partial sort rather than sorting everything.

Coding for MLintermediate5 min

Implement Softmax + Cross-Entropy Stably

Code softmax and cross-entropy without the numbers overflowing.

Implement Softmax and Cross-Entropy Stably prevents numerical overflow and underflow in multi-class classification. Raw Softmax exponentiation of large logits produces floating point NaN errors. The stable implementation subtracts maximum logit values before exponentiation and combines Softmax with Cross Entropy loss into a unified Log-Sum-Exp derivative form.

Coding for MLintermediate5 min

Implement Vector Similarity Search

Code a simple vector search from scratch with one matrix multiply.

Implement Vector Similarity Search builds exact dense vector retrieval engines in NumPy. Vector search ranks candidate document embeddings against query vectors using Cosine Similarity or Dot Product distance. The implementation normalizes vectors to unit length, performs parallel matrix multiplication, and extracts top K nearest neighbor indices.

Coding for MLintermediate5 min

Implement ROC-AUC from Scratch

Code ROC-AUC from scratch, without calling a library.

ROC-AUC measures how well a model ranks positive examples above negative ones, across every possible threshold. A score of 1 means every positive is ranked above every negative, and 0.5 means the ranking is no better than a coin flip. To implement it, sort examples by predicted score, then walk down the list, tracking the true positive rate and false positive rate as the threshold moves. That traces the ROC curve, and adding up the area underneath with trapezoids gives the AUC.

Coding for MLintermediate5 min

Implement Non-Max Suppression

Code the step that removes duplicate boxes in object detection.

Implement Non-Max Suppression (NMS) builds the essential post-processing step for computer vision object detectors. Object detection models (like YOLO) output hundreds of overlapping candidate bounding boxes for a single object. Non-Max Suppression filters redundant detection boxes by sorting candidates by confidence score and discarding overlapping boxes that cross Intersection over Union (IoU) thresholds.

Coding for MLintermediate5 min

Views, Copies & Memory in NumPy

When changing one NumPy array silently changes another.

Views, Copies, and Memory Layout in NumPy govern how array data sits in system RAM memory. Array Views share underlying data memory buffers with original parent arrays, providing fast slicing without memory duplication. Modifying a View mutates original array values silently. Engineers use explicit copies, memory contiguous checks, and C vs Fortran order layouts to write high performance, bug free machine learning code.

Coding for MLintermediate5 min

The PyTorch Training Loop

The five lines at the heart of every PyTorch training loop.

The PyTorch Training Loop represents the core execution pattern for training neural networks. Unlike high level abstractions, PyTorch training requires explicitly managing data batch iteration, zeroing gradient buffers, executing model forward passes, calculating loss, invoking backward autograd, and stepping optimizer parameters.

Coding for MLintermediate5 min

Dataset & DataLoader Patterns

Feeding data to a PyTorch model efficiently, in batches.

PyTorch Dataset and DataLoader abstractions separate data storage logic from mini-batch iteration pipelines. The Dataset class defines how individual data samples and targets are loaded and transformed. The DataLoader wraps Datasets to handle multi-threaded parallel data loading, automatic mini-batch collating, data shuffling, and GPU memory pinning.

Coding for MLintermediate5 min

Making Pandas Fast

Making slow pandas code fast, and knowing when to switch to Polars.

Making Pandas Fast optimizes data processing speed and RAM utilization for large datasets. Unoptimized Pandas pipelines suffer from slow Python row iteration and inefficient object datatypes. Engineers speed up Pandas operations by eliminating iterrows loops in favor of vectorization, downcasting numeric types, converting text to categorical types, and adopting modern multi-threaded engines like Polars.

Coding for MLintermediate5 min

Complexity Questions in ML Coding

How fast is your code as data grows? Big-O for ML engineers.

Complexity Questions in ML Coding evaluates your ability to analyze Big-O time and space complexity for machine learning algorithms. Interviewers expect candidates to state time and space bounds for matrix operations, tree algorithms, nearest neighbor lookups, and attention mechanisms. Stating exact complexity bounds demonstrates engineering rigor when designing scalable systems.

Coding for MLintermediate5 min

Your Loss Is NaN. Now What?

Your loss just became NaN. Here is where to look.

Debugging NaN Loss provides a systematic troubleshooting guide for training neural networks. A training loss returning NaN (Not a Number) indicates numerical instability in mathematical operations. Engineers fix NaN losses by detecting exploding gradients with gradient clipping, adding epsilon constants inside logarithms, checking input features for un-normalized nulls, and lowering high learning rates.

Coding for MLintermediate5 min

Writing ML Code Someone Else Can Run

Structuring ML code so it is easy to test and rerun.

Writing Testable ML Code ensures that machine learning code bases can be reproduced, maintained, and audited by teammates. Jupyter notebooks are great for quick exploratory analysis but suffer from out of order cell execution and global state pollution. Production ML code modularizes pipelines into pure functions, manages parameters using YAML configuration files, sets deterministic random seeds, and writes unit tests.

Coding for MLadvanced5 min

Implement Multi-Head Attention

Code multi-head attention from scratch, and get the shapes right.

Implement Multi-Head Attention builds the full attention module used in Transformer architectures. Instead of computing a single attention pass, Multi-Head Attention projects Query, Key, and Value vectors into H parallel sub spaces. This enables the model to jointly attend to information from different representation sub spaces and positions simultaneously, concatenating head outputs through a final linear projection.

Coding for MLadvanced5 min

Implement Backprop for an MLP

Code backpropagation by hand for a small network in NumPy.

Implement Backprop for an MLP demonstrates how neural networks learn parameters using automatic chain rule differentiation. The implementation covers dense layer matrix multiplication, non-linear activation forward passes (ReLU/Sigmoid), loss calculation, and backward pass gradient propagation through chain rule matrix calculus.

Coding for MLadvanced5 min

Implement BatchNorm Forward & Backward

Code batch norm from scratch, including the backward pass.

Implement BatchNorm Forward and Backward builds the landmark deep learning normalization layer introduced by Ioffe and Szegedy. Batch Normalization standardizes intermediate layer activations across mini-batches to zero mean and unit variance, applying learnable gamma scale and beta shift parameters. The implementation covers forward batch normalization, tracking exponential moving averages for inference, and calculating analytical backpropagation gradients.

Coding for MLadvanced5 min

Implement Conv2D from Scratch

Code a convolution layer from scratch, and then make it fast.

Implement Conv2D from Scratch demonstrates the foundational spatial feature extraction layer of Computer Vision. A 2D Convolution layer slides learnable filter kernels across spatial image dimensions, computing element wise dot products to extract local visual patterns like edges, textures, and shapes. The efficient implementation transforms 2D spatial image patches into matrix columns using im2col for fast parallel GPU matrix multiplication.

Coding for MLadvanced5 min

Implement a Decision Tree Split

Code a decision tree from scratch, one split at a time.

Implement a Decision Tree Split demonstrates greedy recursive tree partitioning. A Decision Tree finds optimal feature thresholds by searching across all features to maximize Information Gain or reduce Gini Impurity. The implementation covers Gini Impurity calculation, best split threshold search over continuous features, recursive binary node splitting, and tree stopping criteria.

Coding for MLadvanced5 min

Implement a Toy BPE Tokenizer

Code a BPE tokenizer from scratch by merging the most common pairs.

Implement a Toy BPE Tokenizer builds subword tokenization algorithms used by GPT models. Byte Pair Encoding starts by representing text as individual characters. The algorithm iteratively counts adjacent character pairs across a text corpus, merging the single most frequent pair into a new combined subword token until target vocabulary size is achieved.

Coding for MLadvanced5 min

Autograd Gotchas: detach, no_grad, retain_graph

The PyTorch mistakes that leak memory or quietly stop learning.

Autograd Gotchas in PyTorch cause subtle GPU memory leaks and computational graph crashes. PyTorch dynamically constructs computational graphs during forward passes to compute automatic backpropagation gradients. Engineers use tensor.detach(), torch.no_grad(), retain_graph=True, and item() conversions correctly to avoid out of memory exceptions and graph execution bugs.

SCROLL · SAVE · TAP TO GO DEEPER