Tag: Data Eng

  • ML0061 KNN and K-means

    What are the key differences between KNN and K-means?

    A question card shows two notebook cells, one calling KNeighborsClassifier with n_neighbors=5 and the other calling KMeans with n_clusters=5, each followed by blank prompts asking what K counts, what input data it needs and what it outputs.

    The Problem: A teammate’s notebook has two cells that both set K = 5, one for KNN and one for K-means, and treats them as interchangeable. Fill in the blanks for each cell: what does K count, what data does the method need, and what does it return? Are these really the same kind of algorithm?

    Answer

    KNN (K-Nearest Neighbors) is a supervised algorithm that classifies data using the labels of its nearest neighbors: prediction from historical labeled data. K-means is an unsupervised clustering technique that groups data purely by similarity, using no labels at all. Despite the shared “K”, they solve different problems.

    (1) Learning Type: KNN is supervised (classification/regression); K-means is unsupervised (clustering).
    (2) Objective: KNN predicts a new sample’s label from the majority vote (or average) of its K nearest neighbors; K-means partitions the dataset into K clusters by minimizing intra-cluster distance.
    (3) Training: KNN has no explicit training: it stores the entire dataset; K-means iteratively learns cluster centroids.
    (4) Prediction Cost: KNN is expensive at prediction (distance to every training point, sort, take the top K, then vote/average); K-means is cheap: distances to K centroids, assign the nearest.
    (5) Distance Use And Output: KNN uses distance to find neighbors and outputs a label or value; K-means uses distance to assign points to centroids and outputs cluster assignments plus centroids.

    FeatureK-Nearest Neighbors (KNN)K-Means
    TypeSupervised LearningUnsupervised Learning
    TaskClassification, RegressionClustering
    Data RequiredLabeled dataUnlabeled data
    Training PhaseStores all training data (lazy learner)Iterative centroid calculation
    Prediction PhaseFinds K nearest neighbors and assigns label/valueAssigns new points to closest cluster centroid
    Compute CostHigh at prediction (distance calculations for each new point)High at training (iterative updates); low at prediction (centroid assignment)
    GoalPredict label/value for new dataGroup data into K clusters
    OutputClass label or predicted valueData points assigned to clusters

    Mathematical Formulation:
    \hat{y} = \arg\max_{c \in \mathcal{C}} \; \sum_{i=1}^{K} \mathbb{1}(y_i = c)
    \min_{C_1, \ldots, C_K} \; \sum_{k=1}^{K} \sum_{x \in C_k} \|x - \mu_k\|^2

    Where:

    • KNN (first line): \hat{y} is the predicted class, \mathcal{C} the class set, y_i the label of the i-th nearest neighbor, and \mathbb{1}(\cdot) the vote-counting indicator.
    • K-means (second line): C_k is cluster k and \mu_k its centroid; the algorithm minimizes total within-cluster squared distance: no labels appear anywhere.
    Two panels on crescent moon data showing KNN separating the moons correctly while K-means cuts through them

    Figure 1: Same data, different goals: with labels, KNN’s local votes trace the two crescents perfectly (left); without labels, K-means can only split by nearest-centroid geometry and slices through both moons (right). KNN performs well here thanks to local decision-making; K-means fails because it assumes spherical clusters with linear boundaries.


    Login to view more content
  • ML0059 K-means II

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0058 K-means++

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0054 KNN Classification

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0053 Hinge Loss for SVM

    Explain the Hinge Loss function used in SVM.

    A two-panel question card: on the left, a two-class dataset with a linear SVM boundary and two dashed margin lines, with four points labeled A to D. On the right, a table lists each point's true label and classifier score, with the penalty column left as question marks.

    The Problem: A trained linear SVM has a decision boundary f = 0 and margin lines at f = -1 and f = +1. Four training points A to D sit at different places relative to the boundary and margins. Given each point’s true label y and score f(x), how much should each point cost in the SVM training objective, and why?

    Answer

    The hinge loss is the key element of Support Vector Machines: it penalizes both misclassified points and correctly classified points that lie inside the margin. Points classified correctly with margin to spare get zero loss; the loss grows linearly as a point moves toward or across the decision boundary. This structure is exactly what pushes the SVM to maximize the margin, promoting robust, generalizable boundaries.

    (1) Zero Loss Zone: When y \cdot f(\mathbf{x}) \geq 1, the point is correctly classified and outside (or exactly on) the margin, the loss is 0.
    (2) Linear Penalty Zone: When y \cdot f(\mathbf{x}) falls below 1, i.e., inside the margin or misclassified, the loss grows linearly with the violation.
    (3) Convex But Not Smooth: The kink at y \cdot f(\mathbf{x}) = 1 makes the function non-differentiable there, so optimization uses subgradients instead of plain gradients.

    Hinge loss curve at zero beyond margin one and increasing linearly for smaller or negative margins with a kink at one

    Figure 1: Hinge loss vs the margin y \cdot f(\mathbf{x}): flat at zero once the point is beyond the margin (right of the dashed line at 1), ramping up linearly inside the margin and for misclassified points (left of it). The kink at 1 is where subgradients take over.

    Mathematical Formulation:
    \text{Hinge Loss} = \max\big(0,\; 1 - y \cdot f(\mathbf{x})\big)

    Where:

    • y \in \{-1, +1\} is the true label.
    • f(\mathbf{x}) is the raw model output (the signed score, before any threshold).
    • The product y \cdot f(\mathbf{x}) is the (functional) margin: positive means correctly classified, ≥ 1 means correct with margin.

    Login to view more content
  • ML0052 Non-Linear SVM

    Can you explain the concept of a non-linear Support Vector Machine (SVM)?

    A two-panel question card: on the left, a scatter of blue dots clustered in the center and surrounded by a ring of gray crosses with no boundary drawn; on the right, a linear SVM box leading to a scorecard with about 50 percent train and test accuracy, and the question of how an SVM could separate such data.

    The Problem: A bullseye dataset puts one class in a central blob and the other in a surrounding ring. A standard linear SVM scores near coin-flip accuracy on it, so how can an SVM classify data that no straight line can split?

    Answer

    A non-linear SVM classifies data that is not linearly separable by using a kernel function to implicitly project the data into a higher-dimensional space where a linear separator exists. This kernel trick provides flexibility for complex datasets while staying computationally efficient: the algorithm never computes the high-dimensional coordinates, only inner products through the kernel. The kernel choice (RBF, polynomial, sigmoid) strongly influences performance and adaptability.

    (1) Kernel Trick: Replace inner products with a kernel K(\mathbf{x}_i, \mathbf{x}_j), which measures similarity as if the data were mapped to a higher-dimensional space, where a linear separation becomes possible.
    (2) Common Kernels: Polynomial (captures feature interactions of degree d), RBF/Gaussian (local similarity decaying with distance), sigmoid (imitates a neural activation).
    (3) Objective: Find the margin-maximizing hyperplane in the transformed space; in the original space its image is a curved decision boundary.

    Two panels on interleaving moons data showing the linear SVM's straight boundary cutting through a class and the RBF SVM's curved boundary separating them cleanly

    Figure 1: Same data, two SVMs: the linear kernel can only slice the moons with a straight line (left), while the RBF kernel’s implicit high-dimensional map lets the boundary bend around both crescents (right).

    Mathematical Formulation:
    K(\mathbf{x}_i, \mathbf{x}_j) = (\gamma\, \mathbf{x}_i^\top \mathbf{x}_j + c)^d
    K(\mathbf{x}_i, \mathbf{x}_j) = \exp\big(-\gamma \|\mathbf{x}_i - \mathbf{x}_j\|^2\big)
    K(\mathbf{x}_i, \mathbf{x}_j) = \tanh(\gamma\, \mathbf{x}_i^\top \mathbf{x}_j + c)

    Where (polynomial, RBF, sigmoid kernels in order):

    • \mathbf{x}_i, \mathbf{x}_j are input vectors; \gamma scales the inner product or controls the RBF width (\gamma = 1/(2\sigma^2), with \sigma the Gaussian spread).
    • c is a constant (bias) term and d the polynomial degree.
    • \|\mathbf{x}_i - \mathbf{x}_j\|^2 is the squared Euclidean distance: nearby points get RBF similarity near 1, distant points near 0.
    Left panel one dimensional class data not separable by a point, right panel the same data lifted to two dimensions by x squared mapping and separated by a straight line

    Figure 2: The kernel idea made concrete: in 1-D the blue class sits between the oranges and no single threshold separates them; after the explicit lift x \mapsto (x, x^2) the classes part vertically and one straight line suffices. Kernels compute as if this lift happened, without ever forming the new coordinates.


    Login to view more content
  • ML0051 Linear SVM

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0049 Logistic Regression II

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0043 Feature Scaling

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0038 Validation and Test

    What are the key purposes of using both a validation and a test set when building machine learning models?

    A three-panel whiteboard sketch shows 10,000 labeled emails, two ways to split them (an 80/20 train and hold-out split versus a 70/15/15 split with two held-out sets), and an unchecked to-do list of tuning, model selection, early stopping and final reporting.

    The Problem: A team building a spam classifier must split 10,000 labeled emails. One option keeps a single 20% hold-out set, and the other carves out two separate held-out sets of 15% each. With tuning, model selection and a final reported accuracy still ahead, why would they hold out two sets instead of one?

    Answer

    The validation set and the test set play two different roles that must not be merged: validation guides every development decision, the test set is touched exactly once for the final unbiased verdict. During development you use the validation set to tune hyperparameters (learning rate, architecture, regularization), select among candidate models, and monitor overfitting (e.g., for early stopping): it is the “unseen” data you are allowed to peek at repeatedly. But because those repeated peeks gradually fit your decisions to the validation set, its score becomes optimistically biased. The test set therefore stays locked away until the model and all its settings are frozen: evaluating on it once simulates real-world performance on genuinely unseen data and guarantees no information from it leaked into any modeling choice. Using the validation set as the test set destroys that guarantee; with very scarce data, rigorous cross-validation during development is the acceptable compromise.

    (1) Validation Set: Tunes hyperparameters, selects models, watches for overfitting: the decision-making dataset.
    (2) Test Set: One-shot final evaluation of the frozen model: the unbiased estimate of real-world performance.
    (3) Separation Why: Repeated validation peeking biases its score; only an untouched set can certify generalization.

    Workflow of training set fitting candidates, validation set selecting the best, and test set used once for the final score

    Figure 1: The role of each split: the training set fits many candidates; the validation set is queried repeatedly to tune and pick the winner (feedback loop); the test set is used exactly once, after everything is frozen; no arrow leads back from it.

    Mathematical Formulation:
    \hat{\lambda} = \arg\min_{\lambda} \; \mathcal{L}_{\text{val}}\big(\hat{\theta}(\lambda)\big)
    \hat{\theta}(\lambda) = \arg\min_{\theta} \; \mathcal{L}_{\text{train}}(\theta; \lambda)
    \text{Final estimate:} \quad \mathcal{L}_{\text{test}}\big(\hat{\theta}(\hat{\lambda})\big) \quad \text{(computed once, model frozen)}

    Where:

    • \theta are model parameters fitted on the training set; \lambda the hyperparameters chosen on the validation set.
    • \mathcal{L}_{\text{val}} is optimized indirectly through many modeling decisions, so it underestimates true error; \mathcal{L}_{\text{test}} enters no optimization and stays unbiased.

    Login to view more content