Tag: Data Eng

  • ML0013 Accuracy

    What is accuracy?

    Whiteboard card with a table of eight test images, their true cat or dog labels, and the model's predicted labels beside a sticky note from a product lead asking for one number that says whether the model is good.

    The Problem: A cat-vs-dog classifier has labeled eight test images, and its predictions sit next to the true labels. A product lead wants a single score that summarizes how this model performs.

    Answer

    Accuracy is a metric that evaluates a classification model as the ratio of correct predictions to the total number of predictions: if a model classifies 99 of 100 samples correctly, its accuracy is 99%. It is intuitive and widely used because it directly answers “how often is the model right?” The four outcomes behind it are: true positives (positive correctly predicted), true negatives (negative correctly predicted), false positives (negative predicted as positive), and false negatives (positive predicted as negative). The important caveat: accuracy alone can be misleading on imbalanced data: a model that labels every patient “healthy” scores 99% on a dataset with 1% disease prevalence while being clinically useless. In such cases, precision, recall, and the F1 score give a truer picture.

    (1) Definition: Correct predictions divided by all predictions, simple and intuitive.
    (2) When It Works: Roughly balanced classes and symmetric error costs.
    (3) The Accuracy Paradox: On skewed data, a trivial “always predict the majority” model scores high accuracy with zero real skill.

    Grid of 100 samples with 90 majority class showing the trivial 90 percent accuracy paradox

    Figure 1: The accuracy paradox: with 90 negatives and 10 positives, predicting “negative” for everything yields 90% accuracy while catching zero positives.

    Mathematical Formulation:
    \text{Accuracy} = \frac{TP + TN}{TP + TN + FP + FN}

    Where:

    • TP and TN are the counts of correct positive and negative predictions: the numerator counts everything the model got right.
    • FP and FN are the false alarm and miss counts; the denominator is simply the total number of samples.
    • Because TN dominates on imbalanced data, high accuracy can hide a model that never identifies the minority class at all.

    Login to view more content
  • ML0012 F1 Score

    What is F1 Score?

    Whiteboard-style card showing an imbalanced dataset of 990 legitimate and 10 fraudulent transactions, plus two fraud-detector confusion matrices with their accuracies: a do-nothing model at 99.0 percent and a model that catches 8 of 10 frauds at 98.6 percent.

    The Problem: A fraud dataset has only 10 frauds in 1,000 transactions. A model that never flags anything scores 99.0% accuracy and beats a model that catches 8 of the 10 frauds. What single score would rank these two detectors sensibly?

    Answer

    The F1 score is a metric for classification models that combines precision and recall into a single number, and it is particularly useful when classes are imbalanced. It is the harmonic mean of the two: precision measures how many positive predictions are correct, recall measures how many actual positives are found, and the harmonic mean punishes imbalance between them: a high F1 requires both to be high at once. A model with 99% precision but 10% recall scores poorly on F1, because the harmonic mean is dominated by the smaller of the two values. This makes F1 a stricter, more informative summary than accuracy or either component alone when false positives and false negatives both matter.

    (1) Definition: The harmonic mean of precision and recall, one number summarizing both.
    (2) Key Property: It is dominated by the lower component, so it cannot be gamed by maximizing only precision or only recall.
    (3) When To Use: Imbalanced classes, or when false positives and false negatives carry comparable cost.

    F1 score contour lines over the recall-precision plane

    Figure 1: F1 contour lines over the recall–precision plane: to reach a higher F1 band you must improve both metrics: moving along one axis alone quickly flattens out.

    Mathematical Formulation:
    \text{F1} = \frac{2 \times \text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}}
    \text{F1} = \frac{2TP}{2TP + FP + FN}

    Where:

    • \text{Precision} is TP/(TP+FP) and \text{Recall} is TP/(TP+FN) (see the precision-and-recall question).
    • TP, FP, and FN are the true positive, false positive, and false negative counts.
    • The second line is the equivalent counts-only form; TN does not appear, which is why F1 stays meaningful under class imbalance.

    Login to view more content
  • ML0011 Precision and Recall

    What are Precision and Recall?

    Three-panel question card. A test set of 10,000 card transactions has only 50 fraud cases. Model A flags 60 transactions and scores 99.6 percent accuracy, while Model B flags nothing and still scores 99.5 percent. Missed fraud and false alarms each carry a different business cost.

    The Problem: A fraud model and a do-nothing model reach almost the same accuracy on a test set where only 0.5% of transactions are fraud, and each kind of mistake has a different cost. Which metrics would tell these models apart?

    Answer

    Precision and recall are two fundamental metrics for evaluating classification models, especially with imbalanced data or asymmetric error costs. Precision (positive predictive value) is the ratio of correctly predicted positives to all predicted positives: it answers “when the model says positive, how often is it right?” If a spam detector flags 100 emails and 99 are truly spam, precision is 99%. Recall (sensitivity, true positive rate) is the ratio of correctly predicted positives to all actual positives: it answers “of all the real positives, how many did the model catch?” If 100 spam emails exist and the model finds 90, recall is 90%. High precision means few false alarms (a spam filter that almost never marks good mail as spam); high recall means few misses (a cancer screening that almost never misses a real case). The two metrics sit on a trade-off controlled by the decision threshold.

    (1) Precision = Accuracy Of Positive Predictions: Minimizing false positives matters when false alarms are costly.
    (2) Recall = Coverage Of Actual Positives: Minimizing false negatives matters when misses are costly.
    (3) Trade-Off: Lowering the classification threshold raises recall and usually lowers precision; raising it does the reverse.

    Set diagram of relevant and retrieved items showing TP, FP, and FN regions

    Figure 1: The set view: precision is the share of the retrieved set that is correct, recall is the share of the relevant set that was retrieved.

    Mathematical Formulation:
    \text{Precision} = \frac{TP}{TP + FP}
    \text{Recall} = \frac{TP}{TP + FN}

    Where:

    • TP (true positives) is the count of positives correctly predicted as positive.
    • FP (false positives) is the count of negatives wrongly predicted as positive, the false alarms.
    • FN (false negatives) is the count of positives wrongly predicted as negative, the misses.
    • TN (true negatives) is the count of negatives correctly predicted as negative; it enters neither formula, which is why these metrics shine on imbalanced data.

    Login to view more content
  • ML0009 Batch Size Selection

    What are the best strategies for selecting the appropriate batch size?

    A three-panel question card shows an image-classification training job, a single 16 GB GPU, and an unset batch_size setting with five candidate values from 8 to 2048.

    The Problem: You are about to train a ResNet-18 from scratch on 50,000 images using one 16 GB GPU. The only setting left open is batch_size, with candidates from 8 to 2048. Which value would you choose, and how would you decide?

    Answer

    Selecting an appropriate batch size is a crucial hyperparameter choice that trades training efficiency against optimization behavior. The practical strategy: start with a moderate value (16, 32, or 64) and adjust based on memory, gradient stability, and validation performance. Three factors drive the choice: memory constraints (larger batches need more GPU memory), dataset size (large datasets can sustain large batches; small datasets often benefit from the extra variability of small batches), and learning rate interaction (large batches usually allow (or require) a proportionally higher learning rate). Large batches train faster per epoch with stabler gradient estimates and higher memory cost, but can converge to sharp minima that generalize worse; small batches update more often with noisier gradients, which can explore flatter minima and generalize better at lower memory cost.

    (1) Trade-Off Summary: Large batch = fast and stable but possibly sharp minima; small batch = slow and noisy but often better generalization.
    (2) Practical Starting Points: Try 16/32/64 first, then scale with memory and dataset size.
    (3) Interaction With LR: Scale the learning rate roughly proportionally when you change the batch size.

    Optimization trajectories of small versus large batch size on a loss surface

    Figure 1: Same loss surface, two batch sizes: the small-batch path is noisy but wanders into a wider basin, while the large-batch path is smooth but direct.

    Mathematical Formulation:
    \hat{g} = \frac{1}{B}\sum_{i=1}^{B}\nabla_\theta \mathcal{L}_i
    \mathrm{Var}[\hat{g}] \propto \frac{\sigma^2}{B}

    Where:

    • \hat{g} is the gradient estimate computed from one mini-batch.
    • B is the batch size, and i\in\{1,\ldots,B\} indexes the samples in the batch.
    • \nabla_\theta \mathcal{L}_i is the per-sample loss gradient.
    • \sigma^2 is the per-sample gradient variance; doubling B halves the gradient noise, which is why large batches give stable estimates and small batches give noisy ones.

    Login to view more content
  • ML0006 Cross-Validation

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

  • ML0005 Discriminative and Generative

    What are the differences between discriminative and generative models?

    A three-panel question card. The first panel shows a small labeled spam-email table. The second shows Model A and Model B trained on that same table, both at 94 percent test accuracy, each marked with a question mark for what it learned. The third lists four product requests with an unanswered question mark under each model.

    The Problem: Two models are trained on the same labeled spam dataset and reach the same test accuracy. The product team then brings four new requests, and the question is what each model actually learned and which requests each one can handle.

    Answer

    Discriminative models learn to draw a boundary between classes: they model the conditional probability P(y \mid x) directly, mapping features x to labels y without modeling how the data was generated. Examples include logistic regression, support vector machines, and neural network classifiers. Generative models instead estimate the joint probability P(x, y) (via P(x \mid y) and P(y)), capturing how the data itself is generated, and then use Bayes’ theorem to derive P(y \mid x) for classification. Examples include Naive Bayes, hidden Markov models, VAEs, and GANs. Because generative models learn the data distribution, they can also sample new data; discriminative models can only separate existing classes.

    (1) Modeling Target: Discriminative models learn P(y \mid x) directly; generative models learn P(x, y) or P(x \mid y) P(y).
    (2) Decision Mechanism: Discriminative models find a decision boundary; generative models compare class-conditional densities through Bayes’ rule.
    (3) Capabilities: Discriminative models only classify; generative models can also generate samples, handle missing features, and score outliers.

    Discriminative model separates classes with a boundary; generative model fits a distribution per class

    Figure 1: Left: a discriminative model cares only about the boundary between classes. Right: a generative model fits a distribution to each class, capturing how the data itself looks.

    Mathematical Formulation:
    \text{discriminative:} \quad \hat{y} = \arg\max_y \, P(y \mid x)
    \text{generative:} \quad P(y \mid x) = \frac{P(x \mid y)\, P(y)}{P(x)}

    Where:

    • \hat{y} is the predicted label and y ranges over the class set for input x.
    • P(y \mid x) is the posterior, the quantity a discriminative model learns directly.
    • P(x \mid y) is the class-conditional likelihood (how data of class y looks) and P(y) the class prior; together they define the joint P(x, y) a generative model learns.
    • P(x) is the evidence normalizer, computable as \sum_y P(x \mid y) P(y) over all classes.

    Login to view more content
  • ML0002 Machine Learning Type

    What is the difference between supervised learning and unsupervised learning?

    Two request cards from the same company. The first is a support inbox table of past emails with subject, sender and a reported-spam column, plus a newly arrived email. The second is a table of shopper records with visit counts, basket sizes and top categories.

    The Problem: The same data team receives two requests. One is to flag spam in incoming support email using an archive of past messages. The other is to find out what kinds of shoppers the store has from purchase records. How do the learning setups for these two requests differ?

    Answer

    Supervised learning trains on labeled data (every example comes with a target output) and learns a mapping that predicts the label of new, unseen inputs. Unsupervised learning works on unlabeled data and instead discovers hidden structure in the inputs themselves, such as clusters or low-dimensional representations. The practical difference is the supervision signal: supervised models are corrected against known answers during training, while unsupervised models optimize an intrinsic objective like reconstruction error or cluster compactness. Supervised learning covers classification and regression; unsupervised learning covers clustering and dimensionality reduction.

    (1) Data Requirement: Supervised needs input–label pairs (x_i, y_i); unsupervised needs only inputs x_i, which are far cheaper to collect.
    (2) Learning Objective: Supervised minimizes prediction error against the labels; unsupervised optimizes structure objectives such as cluster compactness or reconstruction loss.
    (3) Typical Tasks: Classification and regression for supervised; clustering, dimensionality reduction, and density estimation for unsupervised.

    Supervised learning pipeline with labels versus unsupervised pipeline without labels

    Figure 1: The supervision signal is the dividing line: supervised training compares predictions with labels, unsupervised training exploits structure in the inputs alone.

    Mathematical Formulation:
    \hat{y} = f(x;\theta)
    \min_\theta \frac{1}{N}\sum_{i=1}^{N}\ell(f(x_i;\theta), y_i)
    \min_{C_1,\ldots,C_K}\sum_{k=1}^{K}\sum_{x_i \in C_k}\lVert x_i - \mu_k \rVert^2

    Where:

    • f(x;\theta) is the supervised model with parameters \theta, mapping input x to a predicted label \hat{y}.
    • \ell(\cdot) is the per-example supervised loss (e.g., cross-entropy or squared error), and i\in\{1,\ldots,N\} indexes the N labeled examples.
    • C_k is the k-th cluster of a K-means objective and \mu_k its centroid; there are no labels y_i anywhere in the unsupervised objective.
    Labeled data with a decision boundary versus unlabeled data grouped into clusters

    Figure 2: Left: labeled points let a supervised model fit a decision boundary. Right: without labels, an unsupervised model can only group points by similarity.

    AspectSupervised LearningUnsupervised Learning
    Training dataLabeled pairs (x_i, y_i)Unlabeled inputs x_i
    GoalPredict outputs for new inputsDiscover hidden patterns or structure
    Typical tasksClassification, regressionClustering, dimensionality reduction
    Feedback signalDirect error against known labelsIntrinsic objective (compactness, reconstruction)

    Login to view more content