Tag: Data Eng

  • ML0071 Covariance vs Correlation

    What is the difference between covariance and correlation?

    A whiteboard-style question card with two small data tables, one for ad spend versus weekly sales in dollars and one for temperature in Celsius versus ice cream cones sold in thousands; each table has a computed covariance (342,500 for the first and 2.16 for the second), and a side panel asks whether the first pair really moves together more strongly.

    The Problem: Two small datasets each come with their sample covariance: ad spend versus weekly sales gives 342,500, and temperature versus ice cream cones gives 2.16. Does the much larger number mean the first pair has the stronger relationship, and what would you compute to compare them fairly?

    Answer

    Both measure how two variables move together. Covariance is the raw co-movement, expressed in the product of the two variables’ units: positive when the variables tend to sit above their means together, negative when one runs high while the other runs low. Correlation (Pearson’s \rho) is covariance divided by both standard deviations, which strips the units and bounds the result to [-1, 1], so strengths become comparable across datasets. Neither proves causation, and both capture only linear association: a perfect parabola scores zero correlation despite being fully determined.

    (1) Units: covariance keeps the product of the units (dollars times kilograms); correlation is unitless and bounded, so rescaling a variable changes the covariance but leaves the correlation untouched.
    (2) Sign vs Strength: covariance tells you the direction of co-movement; only correlation tells you a comparable strength, since 0.9 vs 0.2 means the same thing for any pair of variables.
    (3) Linear Only: both are second-moment statistics of linear association. Zero correlation does not imply independence: Y = X^2 on symmetric data has \rho = 0 while X fully determines Y.

    Four scatter panels: positive correlation, negative correlation, zero correlation with independent points, and a parabola with zero correlation but full dependence

    Figure 1: Correlation reads linear co-movement: positive (top left), negative (top right), zero with independence (bottom left), and the trap case, zero correlation with complete dependence on a parabola (bottom right). The first three have matching covariance signs; the fourth shows why a second-moment statistic can miss structure.

    Mathematical Formulation:
    \mathrm{Cov}(X, Y) = \mathbb{E}\big[(X - \mu_X)(Y - \mu_Y)\big]
    \rho_{XY} = \frac{\mathrm{Cov}(X, Y)}{\sigma_X \, \sigma_Y}

    Where:

    • X, Y are random variables with means \mu_X, \mu_Y and standard deviations \sigma_X, \sigma_Y.
    • \mathbb{E}[\cdot] is expectation over the joint distribution; in practice both quantities are estimated by sample averages.
    • \rho_{XY} lies in [-1, 1] by the Cauchy-Schwarz inequality, with \pm 1 meaning an exact linear relationship.
    FeatureCovarianceCorrelation
    DefinitionMean product of centered valuesCovariance divided by both \sigma
    UnitsProduct of the variables’ unitsUnitless
    RangeUnbounded[-1, 1]
    Scale InvarianceNo: rescaling a variable rescales itYes: unchanged by a positive affine rescaling (a negative scale flips the sign)
    Typical UsePortfolio variance, covariance matrices, PCAComparing association strength, feature screening

    Login to view more content
  • MSD0008 Cancer Cell Segmentation for Digital Pathology

    

    A digital pathology lab scans tissue biopsies into gigapixel whole-slide images (WSI). Pathologists currently hunt for tumor regions by panning and zooming across each slide by eye, which is slow and error-prone, and the lab wants software that highlights regions containing cancer cells for priority review.

    How would you design an image segmentation model that detects cancer cells in these slides? Outline the candidate approaches, and explain how you would choose between them.

    Line-art scene: a microscope slide with a tissue region flows into a question mark, a magnifier circle shows hundreds of regular round cells with a few large irregular cancer cells among them, annotated with 100000 by 100000 pixels and about 1 percent cancer pixels

    The Problem: a 100,000 × 100,000-pixel slide, and the cancer signal hides in a tiny fraction of its pixels. Design the segmentation model that fills the question mark.

    Answer

    The task is pixel-level binary segmentation on gigapixel slides: the model labels every pixel as cancer or non-cancer, and the slide is processed as a grid of patches because no GPU holds 1010 pixels at once. Three architecture families cover the realistic design space: the U-Net family (encoder-decoder with skip connections), the DeepLab family (atrous convolutions for wide context at full resolution), and Transformer segmenters (SegFormer-style global context). The choice turns on annotation budget, the spatial context the diagnosis needs, and per-slide compute; a strong default is a U-Net variant trained with an overlap-aware loss under heavy stain augmentation.

    (1) U-Net Family: an encoder compresses each patch, a decoder upsamples back to full resolution, and skip connections re-inject fine detail so cell boundaries stay sharp; the data-efficient default.
    (2) DeepLab / Atrous Family: atrous (dilated) convolutions and ASPP widen the receptive field without shrinking resolution, trading compute for gland-level context.
    (3) Transformer Segmenters: self-attention (SegFormer, TransUNet) models long-range tissue architecture, at the price of a much larger appetite for labeled data or pretraining.

    Encoder-decoder segmentation mechanism: a 256 by 256 tissue patch enters a downsampling encoder staircase and an upsampling decoder staircase with dashed skip connections carrying detail across, producing a same-size cancer mask

    Figure 1: The U-Net mechanism on one patch: the encoder gathers context as it downsamples, the decoder rebuilds the full-resolution mask, and skip connections carry boundary detail straight across. Every 256 × 256 patch yields a same-size cancer mask.

    Clarify Before Designing:
    (1) Imaging Spec: magnification (20× or 40×), typical slide dimensions, and which scanner models feed the pipeline?
    (2) Labels: how many slides carry pixel-level pathologist annotations, and are they full masks, outlines, or only slide-level diagnoses?
    (3) Domain Spread: how many labs, staining protocols, and organ types must one model cover?
    (4) Turnaround Budget: how many minutes per slide may inference take, and on what hardware?
    (5) Cost Asymmetry: a missed tumor region versus a false highlight: which error angers pathologists more?


    Login to view more content
  • DL0066 BERT

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

  • DL0064 CNNs Object Detection and Segmentation

    What is the role of CNNs in object detection and segmentation?

    Question card with three dashed panels: a trained CNN that gives one label per shelf photo, a shelf photo of three parcels with question marks over each, and a close-up of a parcel with torn tape asking which pixels are torn.

    The Problem: A warehouse vision team has a CNN classifier trained on 50,000 shelf photos that outputs only one label per photo. Two new requests arrive: put a box and class on every parcel on the shelf camera, and label every pixel of torn tape on close-up inspection shots. What part does their CNN play in each job?

    Answer

    In object detection and segmentation, a CNN commonly acts as a spatial feature extractor that converts pixels into a hierarchy of increasingly semantic feature maps. Detection heads use those features to classify objects and localize bounding boxes, while segmentation heads upsample and fuse spatial detail to predict per-pixel classes or instance-specific masks. Multiscale features are important because small objects need high-resolution maps and large objects benefit from deeper receptive fields. CNNs are therefore the backbone and often part of the head, but proposal logic, feature pyramids, decoders, and task losses complete the system; modern vision Transformers can also replace or complement the CNN backbone.

    (1) Shared Backbone: Convolutions provide translation-equivariant local processing and reusable feature maps at several strides.
    (2) Detection Role: One-stage or region-based heads turn features into class scores and box coordinates, often using multiscale pyramids.
    (3) Segmentation Role: Dense decoders combine semantic context with fine spatial detail for semantic labels, instance masks, or panoptic outputs.

    CNN multiscale backbone branching into object detection and image segmentation heads.

    Figure 1: A shared convolutional feature hierarchy supports two different outputs: sparse boxes and classes versus dense semantic or instance masks.

    Mathematical Formulation:
    F_l=\mathrm{CNN}_l(I)
    (\hat b,\hat p)=H_{\mathrm{det}}(\{F_l\})
    \hat M=H_{\mathrm{seg}}(\{F_l\})
    \hat M\in\mathbb{R}^{H\times W\times K}

    Where:

    • I is the input image and F_l is the backbone feature map produced by stage l.
    • \{F_l\} is the multiscale feature set supplied to task heads.
    • H_{\mathrm{det}} is the detection head, with \hat b denoting predicted boxes and \hat p predicted class probabilities.
    • H_{\mathrm{seg}} is the segmentation head and \hat M is its dense output mask or logit tensor.
    • H and W are output height and width, while K is the number of semantic classes or mask channels.
    Flowchart comparing CNN processing for detection, semantic segmentation, and instance segmentation.

    Figure 2: Task-specific paths after the backbone show what each head must predict and how its output aligns with the input image.


    Login to view more content
  • DL0050 Knowledge Distillation

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

  • DL0047 Focal Loss II

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

  • DL0046 Focal Loss

    What is focal loss, and why does it help with class imbalance?

    Three-panel whiteboard sketch: an image with about 100,000 gray candidate boxes and one blue pedestrian box, a training dashboard where loss falls but pedestrian recall stays flat, and a teammate's proposal to replace plain cross-entropy with focal loss.

    The Problem: A team training a pedestrian detector scores about 100,000 candidate boxes per image, but usually only one of them contains a pedestrian. Under plain cross-entropy the training loss keeps falling while pedestrian recall stays flat, so a teammate proposes switching to focal loss.

    Answer

    Focal loss augments cross-entropy with a modulating factor (1 - p_t)^\gamma that shrinks the loss of easy, well-classified examples toward zero, so the vast number of easy negatives in imbalanced data stops dominating the gradient. Training then concentrates on hard, misclassified, or minority-class examples, which is where the useful learning signal actually lives.

    (1) Modulating Factor: (1 - p_t)^\gamma is near 0 when the model is confident and correct, and near 1 when it is wrong, so easy examples are automatically down-weighted.
    (2) Class Imbalance Effect: In detection-style problems with ~100k easy negatives per positive, plain cross-entropy is swamped by their accumulated gradient; focal loss suppresses it.
    (3) Optional Balancing: A per-class weight \alpha_t can additionally correct the base-rate skew of the classes themselves.

    Mathematical Formulation:
    \mathrm{FL}(p_t) = -\alpha_t\, (1 - p_t)^\gamma \log(p_t)

    Where:

    • p_t is the model’s predicted probability for the ground-truth class.
    • \gamma \geq 0 is the focusing parameter: larger values suppress easy examples harder; \gamma = 0 with \alpha_t = 1 recovers plain cross-entropy.
    • \alpha_t \in (0,1) is an optional per-class balancing weight for class t.
    Loss versus true-class probability curves for cross-entropy and focal loss at several gamma values, showing larger gamma suppressing the loss of confident correct predictions toward zero.

    Figure 1: Focal loss curves for several \gamma: as \gamma grows, the loss of confident correct predictions (high p_t) collapses toward zero while hard examples keep full weight.

    Scenariop_t (True-Class Prob)Factor (1-p_t)^\gammaEffect on Loss
    Easy exampleHighLow → 0Down-weighted to near zero
    Hard exampleLowHigh → 1Keeps full learning signal

    Table 1: How the modulating factor behaves: easy examples fade out, hard examples dominate the gradient.

    Typical Settings: The RetinaNet paper found \gamma = 2 with \alpha = 0.25 (for the positive class) works well; the useful range is usually \gamma \in [1, 3]; too large over-focuses on noisy or mislabeled outliers.


    Login to view more content
  • DL0040 Attention Mask

    What is the role of masking in attention?

    Question card with three panels: a training loss curve falling to 0.02 while sampled text repeats the same word; the sentence the cat sat scoring 0.81 alone but 0.64 when three PAD tokens are appended; and a row of seven tokens where the middle token may only use two neighbors on each side.

    The Problem: A team training a small text decoder hits three puzzles at once. Training loss drops to 0.02 by step 2k, yet sampled text is useless; the sentence the cat sat scores 0.81 alone but 0.64 in a padded batch; and a new task allows each token to read only two neighbors on each side. Their lead says one attention mechanism handles all three.

    Answer

    Masking controls which positions attention is allowed to see. Before softmax, disallowed score entries are set to -\infty (a very large negative number), so their attention weights become exactly zero. This one mechanism serves three jobs: preventing future leakage in autoregressive decoding, ignoring padding tokens in batched inputs, and enforcing task structure such as local neighborhoods or blocked spans.

    (1) Causal Mask (Leakage Prevention): Blocks every position j > i so token i cannot read the future, which is mandatory for autoregressive training and decoding.
    (2) Padding Mask: Blocks pad positions so they neither absorb probability mass nor inject meaningless context into real tokens.
    (3) Structured Mask: Encodes task rules (local windows, graph neighborhoods, span blocking) by zeroing arbitrary score entries.

    Mathematical Formulation:
    \mathrm{Attn}(Q, K, V, M) = \mathrm{softmax}\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V

    Where:

    • M is the mask matrix: 0 for allowed positions, -\infty for blocked ones; adding it before softmax drives blocked weights to zero.
    • Q, K, V are the query/key/value matrices and d_k the key dimension used for scaling.
    Three attention score grids side by side showing a padding mask with right columns blocked, a causal mask with the upper triangle blocked, and a structured local mask with only a diagonal band allowed.

    Figure 1: Three mask patterns (rows = queries, columns = keys): padding blocks trailing columns, causal blocks the upper triangle, structured keeps only a local band.

    Why -\infty and Not Zero: Adding zero changes nothing, and deleting columns would break shapes; adding -\infty makes e^{-\infty} = 0 inside softmax, so blocked positions get exactly zero weight while allowed positions renormalize cleanly among themselves.

    Flowchart of masked attention computing raw scores, adding the mask matrix, applying softmax so blocked entries become zero, and multiplying by values.

    Figure 2: Masking in the pipeline: scores are computed, the mask is added, softmax zeroes blocked entries, and only allowed values are mixed.

    Combining Masks: In decoder training the causal and padding masks are summed (broadcast over queries) so a position is blocked if either rule forbids it; a fully masked row would produce NaNs, so real tokens always keep at least their own position unmasked.


    Login to view more content
  • ML0064 Random Forest II

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

  • ML0062 Decision Tree

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