Tag: Data Eng

  • ML0036 Confusion Matrix

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

  • DL0006 Layer Freeze in TL

    What are the common strategies for layer freezing in transfer learning?

    Whiteboard-style question card: one ResNet-50 pretrained on ImageNet feeds three new projects (a dog-breed app with 1,200 photos, a shelf classifier with 15,000 images, and a chest X-ray model with 200,000 scans), each with a dataset-size bar, a task-similarity rating, and the open question of which layers to freeze.

    The Problem: A vision team has one ResNet-50 pretrained on ImageNet and three projects due this quarter: a dog-breed app with 1,200 labeled photos (very similar to ImageNet), a retail shelf classifier with 15,000 images (moderately similar), and a chest X-ray model with 200,000 scans (a very different domain). For each project they must decide which pretrained layers to freeze and which to train.

    Answer

    Layer freezing controls which pre-trained weights are updated during fine-tuning. Frozen layers keep their learned representations intact, while trainable layers adapt to the target task. The right choice balances leveraging general features against adapting higher-level representations, and depends mainly on target dataset size and task similarity.

    (1) Freeze All but the Output Layer(s): Train only the final classification/regression layers; a good starting point for similar tasks and small datasets.
    (2) Freeze Early Layers: Early layers capture general features (edges, textures), so train only the later, task-specific layers; effective for moderately similar tasks.
    (3) Fine-Tune All Layers with a Low Learning Rate: Adapt all weights slowly; use with caution on small datasets to avoid catastrophic forgetting.
    (4) Gradual Unfreezing: Start with frozen layers and progressively unfreeze during training, avoiding large early updates that can destroy learned features.
    (5) Backbone-Freeze, Then Low-LR Fine-Tune: Freeze the backbone until the new head converges, then unfreeze it and continue with a reduced learning rate.

    Four layer-freezing strategies on a five-block backbone plus head, showing which blocks are frozen versus trainable for each strategy.

    Figure 1: The four common strategies differ in how many blocks stay frozen; freeze more when data is scarce and tasks are similar.

    Mathematical Formulation:
    \theta = \theta_{frozen} \cup \theta_{trainable}
    \Delta\theta_{frozen} = 0
    \theta_{trainable} \leftarrow \theta_{trainable} - \eta\,\nabla_{\theta_{trainable}}\mathcal{L}

    Where:

    • \theta_{frozen} is the parameter subset kept fixed at its pre-trained values; only \theta_{trainable} receives gradient updates.
    • \eta is the learning rate; strategies (3) and (5) use a reduced \eta (e.g., 0.1×) to protect pre-trained features.
    Step chart showing the percentage of trainable layers increasing from head-only to all layers across training epochs during gradual unfreezing.

    Figure 2: Gradual unfreezing starts with the head and unfreezes deeper blocks step by step with a reduced learning rate.


    Login to view more content
  • DL0005 Transfer Learning

    Why use transfer learning in deep learning instead of training from scratch?

    A three-panel whiteboard card shows a small grid of labeled circuit-board photos marked 1,500 photos in 4 defect classes, a budget of 1 GPU and 14 days, and a choice between Option A (train from random weights) and Option B (start from a pre-trained checkpoint), with the question of which to pick and why.

    The Problem: A factory QA team has only 1,500 labeled circuit-board defect photos, a single GPU, and a two-week deadline. They must choose between training a ResNet-50 from random weights and starting from a checkpoint pre-trained on a large image dataset.

    Answer

    Transfer learning reuses knowledge from a pre-trained model to improve performance, reduce training time and data requirements, and lower computational cost on a new but related task. Instead of learning low-level features from random weights, the model starts from representations that already capture generalizable patterns such as edges, textures, and shapes, so far less target data is needed to reach strong accuracy.

    (1) Leverages Existing Knowledge & Reduced Data Requirements: Pre-trained weights encode useful representations learned from large datasets, so good performance is possible with significantly less task-specific data.
    (2) Faster Convergence & Training Time: Starting from pre-trained weights is a much better initialization than random weights, leading to faster convergence and often better local optima.
    (3) Improved Performance on Limited-Data Tasks: When data is scarce, transfer learning typically yields higher accuracy and better generalization than training from scratch.

    Transfer learning pipeline showing a backbone pre-trained on a large source dataset being copied to a target task where the backbone is frozen or fine-tuned with a low learning rate and a new head is trained.

    Figure 1: The backbone’s weights are copied from pre-training; only the new head (and optionally upper layers) must be learned from limited target data.

    Mathematical Formulation:
    \theta^* = \arg\min_{\theta}\ \mathcal{L}_{target}(\theta;\ \theta_{init} = \theta_{pretrained})
    \eta_l = \eta_{base} \cdot \gamma^{\,L-l}

    Where:

    • \theta_{pretrained} is the weight set learned on the source task; fine-tuning minimizes the target loss starting from this initialization.
    • \eta_l is the learning rate of layer l out of L; a decay factor \gamma below 1 gives earlier (more general) layers smaller updates than later (task-specific) layers.
    Log-scale chart showing transfer learning achieving high validation accuracy with little target data while training from scratch needs much more data to catch up.

    Figure 2: Transfer learning dominates in the low-data regime; the advantage shrinks as the target dataset grows.

    Faster Convergence: Because pre-trained weights are already a strong initialization, the model reaches its accuracy plateau in far fewer epochs than training from random weights.

    Accuracy versus epoch chart showing transfer learning converging quickly to a high plateau while training from scratch improves slowly over many more epochs.

    Figure 3: Transfer learning converges faster and plateaus higher; training from scratch improves slowly over many epochs.


    Login to view more content
  • ML0022 Cross Entropy Loss

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

  • ML0020 Data Split

    How to split the dataset?

    Question card with three panels: a single unsplit bar of 50,000 labeled emails, a first attempt that fits a model on all rows and scores it on those same rows for 98 percent accuracy, and a list of open choices about how to divide the data.

    The Problem: A team has 50,000 labeled emails and a first model that was fit and scored on the very same rows, reporting 98% accuracy. Before building anything else, they need to decide how to split the dataset: how many pieces, how large each should be, and whether to shuffle.

    Answer

    A dataset is typically split into three parts. The training set is used to fit the model: it learns the patterns and relationships from this data. The validation set is used during development to tune hyperparameters and compare model configurations, which prevents overfitting the training data. The test set is touched only once, for a final unbiased evaluation on completely unseen data: an estimate of real-world generalization. Typical ratios scale with dataset size: for small datasets (fewer than ~1,000 samples), 60–70% training / 10–15% validation / 15–25% test, with k-fold cross-validation strongly recommended because small validation estimates are noisy; for medium datasets (1,000–100,000), a common starting point is 70–80% / 10–15% / 10–15%; for large datasets (over ~100,000), even 98% / 1% / 1% leaves plenty of validation and test samples. For imbalanced data, use stratified splits so every part keeps the original class proportions. On whether to shuffle: shuffle rows before splitting when they are exchangeable (independent samples like these emails), but never shuffle time-ordered or grouped data: temporal data needs chronological splits and grouped data needs group-aware splits such as GroupKFold, otherwise future or same-group rows leak into training.

    (1) Three Roles: Train fits, validation tunes, test judges; each set answers a different question.
    (2) Size-Dependent Ratios: Small data needs more training share plus cross-validation; big data can spare 1–2% for evaluation.
    (3) Stratification: Preserve class ratios in every split when classes are imbalanced.

    Train validation test split ratios for small, medium, and large datasets

    Figure 1: Split ratios by dataset size: the smaller the data, the larger the training share (and the more you need cross-validation); big data can evaluate on 1–2%.

    Mathematical Formulation:
    D = D_{\mathrm{train}} \cup D_{\mathrm{val}} \cup D_{\mathrm{test}}
    D_{\mathrm{train}} \cap D_{\mathrm{val}} = D_{\mathrm{train}} \cap D_{\mathrm{test}} = D_{\mathrm{val}} \cap D_{\mathrm{test}} = \emptyset

    Where:

    • D is the full dataset, partitioned into three disjoint subsets: no sample may appear in two roles.
    • D_{\mathrm{train}} is the training set used to fit the model parameters.
    • D_{\mathrm{val}} is the validation set used to tune hyperparameters and trigger early stopping.
    • D_{\mathrm{test}} is the test set, used exactly once for the final unbiased estimate; reusing it for tuning silently turns it into validation data.

    Login to view more content
  • ML0019 Imbalanced Data

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

  • ML0018 Data Normalization

    Why is data normalization used in Machine Learning?

    A raw training table with income in tens of thousands of dollars, age in years, and credit utilization between 0 and 1 feeds an undecided rescale step that leads to a k-NN classifier, a logistic regression trained with gradient descent, and a small neural network.

    The Problem: A raw loan-applicant table mixes income in dollars, age in years, and utilization as a fraction, and the same table will feed a k-NN classifier, a gradient-descent logistic regression, and a small neural network. Before training, should a rescaling step be added, and why would it matter for these models?

    Answer

    Data normalization scales features into a specific range or distribution: typically [0, 1] with min-max scaling, or mean 0 and standard deviation 1 with standardization, so that every feature contributes comparably to learning. It is used for three reasons. First, better model performance: algorithms built on distance metrics, such as k-nearest neighbors and SVMs, are skewed when one feature spans thousands and another spans decimals, normalization puts them on the same scale. Second, training stability and speed: normalized inputs keep neural network gradients well-conditioned, so training converges faster and more smoothly. Third, fair feature contribution: without scaling, large-magnitude features dominate the objective while small-magnitude ones are ignored, regardless of how informative they actually are.

    (1) What It Does: Rescales each feature to a common range (min-max) or distribution (z-score standardization).
    (2) Who Needs It: Distance-based models (kNN, SVM), gradient-based learners (neural networks, linear/logistic regression); tree ensembles largely do not.
    (3) The Payoff: Faster convergence, stabler training, and features competing on information rather than magnitude.

    Two-feature scatter before and after normalization

    Figure 1: Before: one axis spans hundreds while the other spans decimals, so distance is decided by the big axis alone. After standardization, both features contribute equally.

    Mathematical Formulation:
    x' = \frac{x - x_{\min}}{x_{\max} - x_{\min}}
    z = \frac{x - \mu}{\sigma}

    Where:

    • x' is the min-max normalized value of feature value x, squashed into [0, 1].
    • x_{\min} and x_{\max} are the feature’s minimum and maximum computed on the training set only.
    • z is the standardized (z-score) value with mean 0 and standard deviation 1.
    • \mu and \sigma are the feature’s training-set mean and standard deviation; fitting them on all data would leak test information.

    Login to view more content
  • ML0017 Data Augmentation

    What are the common data augmentation techniques?

    Three-panel sketch: a tiny grid of eight labeled cat and dog photos standing in for a 240-image dataset, a labeling-cost box showing 1.50 dollars per image with no budget for more, and two bars showing 99 percent train accuracy against 64 percent validation accuracy.

    The Problem: A team has only 240 labeled photos and no budget to label more. Their classifier scores 99% on training data but only 64% on validation. How can they get more training variety from the data they already have?

    Answer

    Data augmentation increases the diversity and effective size of a training set by creating modified versions of the existing data, especially valuable in computer vision and NLP, where collecting and labeling new data is expensive. In computer vision, common techniques are geometric transformations (rotate, flip, crop, scale), color adjustments (brightness, contrast, saturation, color jitter), and noise injection (random noise or blur). In NLP: synonym replacement, back translation (translate to another language and back), and random insertion or deletion of words. For tabular data: SMOTE-style synthetic sample generation and small random noise on numeric features. The benefits: better robustness and generalization, less overfitting (the model cannot memorize a moving target), relief for class imbalance, and lower data-collection cost.

    (1) Core Idea: Apply label-preserving transformations so one sample teaches many variations of the same concept.
    (2) By Data Type: Geometric/color/noise for images, synonym/back-translation/edit for text, SMOTE/noise for tables.
    (3) Benefits: Robustness, regularization against overfitting, imbalance relief, and cost savings, all from data you already have.

    One original image and five augmented variants: flip, rotate, crop, brightness, noise

    Figure 1: One sample, five augmented views. The label never changes (only the appearance does), so the model learns invariance instead of memorizing pixels.

    Mathematical Formulation:
    \tilde{x} = T(x; \phi), \quad \tilde{y} = y
    \min_\theta \; \mathbb{E}_{(x,y)} \, \mathbb{E}_{\phi} \, \ell\big(f(T(x;\phi);\theta), y\big)

    Where:

    • T(x;\phi) is the augmentation transform applied to sample x with random parameters \phi (e.g., rotation angle, crop offset).
    • \tilde{x} is the augmented sample and \tilde{y} its label, unchanged because the transforms are label-preserving.
    • f(\cdot;\theta) is the model with parameters \theta, and \ell is the training loss.
    • \mathbb{E}_{\phi} is the expectation over random augmentations: training minimizes loss over infinitely many variants, which is what regularizes the model.

    Login to view more content
  • ML0015 ROC Curve

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

  • ML0014 Confusion Matrix

    What is the confusion matrix?

    A three-panel question card about a spam filter: a log of individual emails with their actual and predicted labels marked right or wrong, a dashboard showing one accuracy score of 95 percent on a test set that is 95 percent not spam, and two kinds of failure the team worries about.

    The Problem: A spam filter reports a single 95% accuracy on a test set where 950 of 1000 emails are not spam. The team needs to know whether spam is slipping into the inbox or real emails are being sent to junk. What tool shows which kinds of errors hide behind that one number?

    Answer

    A confusion matrix is a table that summarizes the performance of a classification model by comparing its predicted labels against the actual labels. For binary classification it is a 2×2 table with four cells: true positives (correctly predicted positive), false positives (negative predicted as positive), false negatives (positive predicted as negative), and true negatives (correctly predicted negative). Unlike a single scalar metric, it shows not only how many predictions were wrong but which kinds of errors were made. For multi-class problems, the matrix expands into a larger square table where cell (i, j) counts the instances of actual class i predicted as class j; off-diagonal clusters reveal which specific classes the model systematically confuses, guiding model refinement or relabeling.

    (1) Structure: Rows are actual classes, columns are predicted classes; the diagonal holds all correct predictions.
    (2) Binary Case: The four cells TP/FP/FN/TN feed every classification metric: accuracy, precision, recall, F1.
    (3) Multi-Class Case: An n \times n matrix whose off-diagonal hotspots expose systematic class confusions.

    Actual \ PredictedPredicted PositivePredicted Negative
    Actual PositiveTrue Positives (TP): correct positiveFalse Negatives (FN): missed positive
    Actual NegativeFalse Positives (FP): false alarmTrue Negatives (TN): correct negative

    Mathematical Formulation:
    M_{ij} = \sum_{k=1}^{N} \mathbb{1}\big(y_k = i,\; \hat{y}_k = j\big)
    \text{row-normalized:} \quad \tilde{M}_{ij} = \frac{M_{ij}}{\sum_j M_{ij}}

    Where:

    • M_{ij} is the count in row i, column j of the confusion matrix.
    • y_k is the true label of sample k, \hat{y}_k its predicted label, and k\in\{1,\ldots,N\} indexes the N samples.
    • \mathbb{1}(\cdot) is the indicator function: 1 when the condition holds, 0 otherwise.
    • \tilde{M}_{ij} is the row-normalized version: row i then shows the per-class recall distribution, which reads better under class imbalance.
    Three class confusion matrix heatmap with off-diagonal confusions

    Figure 1: A 3-class example: strong diagonal means healthy classification; the bright off-diagonal cell shows the model systematically confuses class 1 with class 2.


    Login to view more content