Skip to content

Cookies on Jobverse

We use cookies that are needed to sign you in and keep the site working. With your permission we’d also use an analytics cookie to count job views, and Google advertising cookies to show ads. The site works the same whatever you choose. Read the Cookie Policy.

Jobverse
Sign in

AI/ML Engineer Top 100 Interview Questions

100 AI/ML engineer interview questions with structured answers, comparison tables, flow diagrams, worked calculations and runnable code. Covers problem framing, classical algorithms, clustering, recommender systems, forecasting, text, evaluation, applied deep learning and MLOps, from fundamentals to system design.

100 questions

Questions 41-60 of 100

  1. Q41.How do you measure forecast accuracy, and why can percentage errors mislead?

    Choose an error measure that matches how the forecast is used, and check how it behaves on small and zero values. Percentage errors are easy to explain but explode when actual values are small.

    Mean absolute errorRoot mean squared errorMean absolute percentage error
    Average of absolute errorsSquare root of the average squared errorAverage of absolute error divided by the actual
    In the data's own unitsPunishes large missesScale-free and intuitive
    Hard to compare across series of different scaleSensitive to outliersUndefined at zero, explodes for small actuals
    Weighted absolute percentage errorScaled error
    Total absolute error divided by total actualsError relative to a naive forecast's error
    Scale-free and robust to small itemsComparable across series
    Large series dominateLess intuitive to explain

    When to use which:

    • Inventory and planning across many products: weighted percentage error, so big sellers count more.
    • Comparing models across very different series: scaled errors.
    • When large misses are costly: root mean squared error, or a cost-weighted measure.

    Also check bias, meaning whether forecasts run consistently high or low, because a small average error can hide systematic overstocking.

    Example

    Four products with actual sales of 100, 50, 2 and 80 against forecasts of 90, 55, 6 and 80:

    1. Absolute errors: 10, 5, 4 and 0, so mean absolute error is 4.75 units.
    2. Percentage errors: 10%, 10%, 200% and 0%, so the mean absolute percentage error is 55%.
    3. Weighted: total error 19 divided by total sales 232 is about 8.2%.
    4. A miss of 4 units on a product that sold 2 makes the plain percentage error look disastrous, while the weighted measure correctly shows the forecast was good overall.
  2. Q42.How does TF-IDF weight the words in a document?

    TF-IDF scores a word in a document by how often it appears there (term frequency), discounted by how common it is across all documents (inverse document frequency). Words that are frequent in one document but rare overall get the highest weights.

    • tf(word, doc) = count of word in doc / words in doc
    • idf(word) = log(number of documents / documents containing word)
    • tf_idf = tf × idf

    What it achieves:

    • Words in every document, such as "the", get an IDF of zero, so they carry no weight.
    • Distinctive words, such as "screen" in a review about displays, stand out.

    Practical points:

    • Implementations vary: smoothed IDF, logarithmic term frequency and row normalization are common, so scores differ slightly between tools.
    • Combine it with stop word removal and n-grams, such as "not good", which carry meaning single words miss.
    • The resulting sparse vectors work very well with linear classifiers and for keyword search.
    • It ignores word order and meaning, so "cheap" and "inexpensive" are unrelated, which embeddings fix.

    Example

    Scoring the words of one product review against a collection of three:

    import math
    from collections import Counter
    from operator import itemgetter
    
    docs = [
        "the battery lasts all day",
        "the screen is bright and the battery is weak",
        "the camera is sharp",
    ]
    tokenized = [doc.split() for doc in docs]
    doc_freq = Counter(word for words in tokenized for word in set(words))
    
    
    def tf_idf(words: list[str]) -> dict:
        counts = Counter(words)
        return {w: round((c / len(words)) * math.log(len(tokenized) / doc_freq[w]), 3) for w, c in counts.items()}
    
    
    for word, score in sorted(tf_idf(tokenized[1]).items(), key=itemgetter(1), reverse=True):
        print(f"{word:8} {score}")
    # Output:
    # screen   0.122
    # bright   0.122
    # and      0.122
    # weak     0.122
    # is       0.09
    # battery  0.045
    # the      0.0

    "The" appears in every review, so it scores zero even though it is the most frequent word. "And" scores as high as "screen" only because no other review contains it, which is why stop word lists are still used.

  3. Q43.How do word embeddings differ from bag-of-words features?

    Bag-of-words features represent a document by counting which words it contains, with one dimension per vocabulary word. Word embeddings represent each word as a dense vector learned from context, so words used in similar ways get similar vectors.

    Bag-of-words or TF-IDFWord embeddings
    As long as the vocabulary, often tens of thousands of values, mostly zerosFixed size, often 100 to 1,000 dense values
    "Cheap" and "inexpensive" are unrelatedSimilar meanings sit close together
    Ignores word order, except through n-gramsStatic vectors ignore order; contextual models capture it
    Needs no training data beyond the documentsNeeds large text collections, or pretrained vectors
    Each feature is a wordDimensions have no direct meaning
    Used with linear classifiers and keyword searchUsed with neural networks and semantic search

    When to use which:

    • Bag-of-words for strong, fast baselines, small datasets, keyword-heavy tasks and when explanations by word are needed.
    • Embeddings when meaning matters more than exact words, such as semantic search, short texts and multilingual data.

    Static word embeddings give "bank" one vector whether it means a river bank or a money bank. Contextual models produce a different vector for each occurrence, which resolves such ambiguity.

  4. Q44.How would you build a text classification pipeline?

    Build it in stages, from clear labels to a strong simple baseline, then improve with richer representations only where the baseline falls short, and evaluate each stage on a held-out set that reflects real traffic.

    flowchart LR
      A["Define labels and collect data"] --> B["Clean and split"]
      B --> C["Baseline: TF-IDF and linear model"]
      C --> D["Evaluate per class"]
      D --> E{"Good enough?"}
      E -->|no| F["Embeddings or fine-tuned model"]
      F --> D
      E -->|yes| G["Deploy with threshold and monitoring"]
    1. Define labels precisely, with written guidelines and examples, and measure agreement between labelers.
    2. Clean carefully: normalize whitespace and encoding, but keep signals such as negations, emoji or capitalization if they matter.
    3. Split by time or source to avoid near-duplicates leaking between training and test sets.
    4. Baseline: TF-IDF features with a regularized linear classifier, which is often surprisingly strong.
    5. Evaluate per class, with precision, recall and a confusion matrix, since rare classes hide in averages.
    6. Improve: pretrained embeddings or fine-tuning a pretrained language model, if the gain justifies the cost.
    7. Deploy with thresholds per class, a route for low-confidence cases, and monitoring for new topics.

    Error analysis drives most improvements. Read misclassified examples; they often reveal labeling problems rather than model problems.

  5. Q45.How is named entity recognition framed as a sequence labeling problem?

    Named entity recognition finds spans of text that refer to things such as people, organizations, places or dates. It is framed as labeling each token with a tag that says whether it begins an entity, is inside one, or is outside any entity, together with the entity type.

    The tagging scheme:

    • B-TYPE marks the first token of an entity, such as B-LOC.
    • I-TYPE marks the following tokens of the same entity.
    • O marks tokens outside any entity.
    • The B tag lets the model separate two adjacent entities of the same type.

    How models handle it:

    • A model reads the whole sentence and predicts a tag per token, using context on both sides.
    • A structured output layer can forbid invalid sequences, such as I-LOC directly after O.
    • Subword tokenizers split words into pieces, so labels must be aligned, usually by tagging the first piece of each word.

    Evaluation: score at the entity level, where an entity counts only if both its boundaries and its type are exactly right. Token accuracy looks high simply because most tokens are O.

    Example

    Tags for one sentence, with a two-token place name and a two-token date:

    Flights  from  New    York   to  Lisbon  were  delayed  on  3       March
    O        O     B-LOC  I-LOC  O   B-LOC   O     O        O   B-DATE  I-DATE

    Decoding the tags gives three entities: "New York" as a place, "Lisbon" as a place and "3 March" as a date. If the model tagged "York" as B-LOC, entity-level scoring would count two wrong entities, "New" and "York", even though 10 of the 11 token tags are right.

  6. Q46.How do you calculate the area under the ROC curve from ranked predictions?

    The area under the ROC curve equals the probability that a randomly chosen positive example is scored higher than a randomly chosen negative one. You can compute it directly from ranks, without drawing the curve.

    • AUC = (sum of the positives' ranks − n_pos × (n_pos + 1) / 2) / (n_pos × n_neg)

    What each term means:

    • Ranks: sort all scores in ascending order and number them from 1; tied scores get the average of their ranks.
    • n_pos and n_neg: the number of positive and negative examples.
    • The subtracted term removes the rank sum the positives would have if they were all ranked lowest.

    How to read it:

    • 0.5 is random ordering; 1.0 means every positive outranks every negative.
    • It depends only on the order of scores, so it ignores calibration and is unchanged by any monotonic rescaling.
    • With heavy class imbalance, a high value can coexist with poor precision, so also check precision-recall measures.

    When to use it: to compare how well models rank cases, independent of any threshold. Choose the operating threshold separately, from business costs.

    Example

    Computing AUC from ranks, with average ranks for tied scores:

    def auc(labels: list[int], scores: list[float]) -> float:
        order = sorted(range(len(scores)), key=scores.__getitem__)
        ranks = [0.0] * len(scores)
        i = 0
        while i < len(order):
            j = i
            while j + 1 < len(order) and scores[order[j + 1]] == scores[order[i]]:
                j += 1
            for m in range(i, j + 1):
                ranks[order[m]] = (i + j) / 2 + 1  # average rank for ties
            i = j + 1
        n_pos = sum(labels)
        n_neg = len(labels) - n_pos
        rank_sum = sum(rank for rank, label in zip(ranks, labels) if label == 1)
        return (rank_sum - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg)
    
    
    labels = [1, 1, 0, 1, 0, 0, 1, 0]
    print(auc(labels, [0.9, 0.8, 0.7, 0.6, 0.55, 0.4, 0.35, 0.1]))  # 0.75
    print(auc(labels, [0.9, 0.8, 0.7, 0.6, 0.6, 0.4, 0.35, 0.1]))  # 0.71875

    In the first case the positives hold ranks 8, 7, 5 and 2, so (22 − 10) / 16 = 0.75: 12 of the 16 positive-negative pairs are ordered correctly. In the second, a tie between a positive and a negative counts as half a correct pair.

  7. Q47.How do you tell whether a small improvement in a model metric is real?

    Compare the two models on the same test examples and estimate how much the difference could vary by chance, using a paired bootstrap or a paired statistical test. A difference that is smaller than its own uncertainty is not evidence of improvement.

    How to do it:

    1. Score both models on identical test rows, so the comparison is paired and noise from different samples cancels out.
    2. Bootstrap the difference: resample the test rows with replacement thousands of times, recompute the metric difference each time, and take the 2.5th and 97.5th percentiles as a 95% interval.
    3. Read the interval: if it includes zero, the improvement is not established.
    4. Repeat across random seeds for models whose training is random, since seed-to-seed variation can be as large as the gain.
    5. Correct for many comparisons: testing 20 variants will produce a "significant" winner by chance alone.

    Beyond significance: ask whether the gain is practically meaningful, whether it holds across important subgroups, and whether it survives an online experiment, where the real effect is measured.

    Example

    Two classifiers on the same 400 test examples: model A is right on 340, model B on 348. They agree on 372 examples; A alone is right on 10 and B alone on 18:

    import random
    
    a = [1] * 330 + [1] * 10 + [0] * 18 + [0] * 42  # 1 = correct
    b = [1] * 330 + [0] * 10 + [1] * 18 + [0] * 42
    print(sum(a) / 400, sum(b) / 400)  # 0.85 0.87
    
    rng = random.Random(0)
    diffs = []
    for _ in range(2000):
        rows = [rng.randrange(400) for _ in range(400)]
        diffs.append(sum(b[i] - a[i] for i in rows) / 400)
    diffs.sort()
    print(round(diffs[49], 4), round(diffs[1949], 4))  # -0.005 0.0475
    print(sum(d <= 0 for d in diffs) / 2000)  # 0.0695

    The 2-point gain has a 95% interval from about −0.5 to +4.75 points, and about 7% of resamples show no gain at all. B may well be better, but this test set cannot show it convincingly; more test data or an online experiment is needed.

  8. Q48.How do you calculate expected cost from a confusion matrix and a cost matrix?

    Multiply the number of cases in each cell of the confusion matrix by the cost of that outcome, add them up, and divide by the number of cases. This turns model evaluation into the business terms that actually drive decisions.

    • expected cost per case = (TP × c_TP + FP × c_FP + FN × c_FN + TN × c_TN) / N

    What each term means:

    • TP, FP, FN, TN: counts of true positives, false positives, false negatives and true negatives.
    • c_...: the cost of each outcome, such as the loss from a missed fraud case or the review cost of a flagged transaction. Benefits can be entered as negative costs.
    • N: the total number of cases.

    When to use it:

    • To choose between models whose standard metrics point in different directions.
    • To pick a decision threshold: compute expected cost at many thresholds and take the lowest.
    • To compare against not using a model at all, which is the real baseline.

    Get the costs from the business, and test how sensitive the decision is to them. If the best threshold changes a lot when one cost moves by 20%, say so.

    Example

    A fraud model on 10,000 transactions containing 100 frauds. A missed fraud costs 200, and each flagged transaction costs 5 to review:

    1. Threshold A: 80 frauds caught, 20 missed, 400 false alarms. Cost: 20 × 200 + 400 × 5 + 80 × 5 = 6,400, or 0.64 per transaction.
    2. Threshold B, more sensitive: 90 caught, 10 missed, 1,200 false alarms. Cost: 10 × 200 + 1,200 × 5 + 90 × 5 = 8,450, or 0.845 per transaction.
    3. No model: all 100 frauds missed, 100 × 200 = 20,000.

    Threshold B catches more fraud but costs more overall, because review costs for false alarms outweigh the extra savings. Threshold A wins.

  9. Q49.How do you size an online A/B test for a new model?

    Decide the smallest effect worth detecting, then calculate how many users each group needs so that a real effect of that size is very likely to show up as statistically significant. Running a test with too few users wastes it: it can only find huge effects.

    • n per group ≈ (z_α/2 + z_β)² × [p1 × (1 − p1) + p2 × (1 − p2)] / (p1 − p2)²

    What each term means:

    • p1: the current conversion rate; p2: the rate you hope the new model achieves.
    • z_α/2: 1.96 for a 5% significance level, two-sided.
    • z_β: 0.84 for 80% power, the chance of detecting a real effect of this size.

    Practical points:

    • Smaller effects need far more users: halving the detectable difference roughly quadruples the sample.
    • Fix the duration in advance and run whole weeks to cover weekly patterns. Stopping early when results look good inflates false positives.
    • Randomize by user, not by request, so one person sees one experience.
    • Pick one primary metric plus guardrail metrics, and decide them before starting.

    Example

    Sizing a test for a recommendation model on a page with 5% conversion, aiming to detect an increase to 5.5%, a 10% relative lift:

    1. (1.96 + 0.84)² = 7.84.
    2. Variance term: 0.05 × 0.95 + 0.055 × 0.945 = 0.0475 + 0.0520 = 0.0995.
    3. Squared difference: (0.055 − 0.05)² = 0.000025.
    4. n ≈ 7.84 × 0.0995 / 0.000025 ≈ 31,200 users per group, about 62,400 in total.
    5. With 10,000 eligible users a day split between the groups, the test needs about a week, so it runs for one full week.
  10. Q50.Why can an overall metric hide problems in subgroups of the data?

    An overall metric is a weighted average across subgroups, so a small group can perform badly without moving it, and a change in the mix of groups can move it even when every group stays the same or improves.

    A small group performs badlyThe mix of groups shiftsTwo errors cancel outA new segment appears
    The overall metric barely changesThe overall metric drops or risesThe overall metric looks stableThe overall metric shows small drift
    One segment, such as a language or device, gets poor predictionsEach group is unchanged or even improvedOne group improves while another degradesThe model has never seen this kind of user

    How to guard against it:

    1. Define important slices in advance: customer type, region, device, language, new versus returning, and protected groups where fairness matters.
    2. Report metrics per slice with sample sizes and confidence intervals, not just one number.
    3. Set slice-level release criteria, such as "no slice may get more than 2 points worse".
    4. Track the mix of slices over time, to separate real degradation from population change.

    Example

    A model's monthly accuracy drops from 88% to 81.5%, yet nothing is wrong with it:

    1. Last month: 9,000 returning users at 90% accuracy and 1,000 new users at 70%, so (8,100 + 700) / 10,000 = 88%.
    2. This month, after a big marketing campaign: 5,000 returning users at 91% and 5,000 new users at 72%, so (4,550 + 3,600) / 10,000 = 81.5%.
    3. Accuracy improved in both groups, but the mix shifted toward new users, who are harder to predict.
    4. The useful actions are improving predictions for new users and reporting accuracy per group, not rolling back the model.
  11. Q51.How do momentum-based and adaptive optimizers differ?

    Momentum optimizers keep a running average of past gradients, so updates build speed along consistent directions and damp oscillations. Adaptive optimizers also scale each parameter's step by the history of its own gradient sizes, so rarely updated or noisy parameters get suitably sized steps automatically.

    Plain stochastic gradient descentWith momentumRoot-mean-square scaling
    Steps against the current gradientSteps along a decaying average of gradientsDivides steps by a running average of squared gradients
    Simple, often generalizes wellFaster, smoother progressHandles very different gradient scales
    Slow in narrow valleys, sensitive to the learning rateOne more hyperparameterNeeds tuning of the decay rate
    AdamAdam with decoupled weight decay
    Momentum plus per-parameter scaling, with bias correctionApplies weight decay separately from the gradient step
    Fast, robust defaultsThe usual default for large networks
    Can generalize slightly worse; weight decay interacts badlyMore memory: two extra values per parameter

    When to use which:

    • Adaptive optimizers for fast, reliable progress on most deep learning tasks, especially attention-based models.
    • Momentum with a tuned schedule is still competitive for image models, and sometimes generalizes better.
    • Whatever the optimizer, the learning rate and its schedule matter more than the choice between close alternatives.

    Adaptive methods store two running averages per parameter, roughly tripling optimizer memory over plain gradient descent. That matters for very large models.

  12. Q52.What do learning rate warmup and decay schedules do?

    A learning rate schedule changes the step size during training. Warmup starts small and ramps up, which keeps early updates stable while statistics and weights are still poorly set. Decay lowers the rate later, so training can settle into a good minimum instead of bouncing around it.

    • Linear warmup: lr = peak × step / warmup_steps for the first steps.
    • Cosine decay: lr = floor + 0.5 × (peak − floor) × (1 + cos(π × progress)), where progress runs from 0 to 1 after warmup.

    Common schedules:

    • Step decay: cut the rate by a factor, such as 10, at set epochs.
    • Cosine decay: a smooth fall from the peak to near zero; a popular default.
    • Reduce on plateau: lower the rate when the validation metric stops improving.
    • One-cycle: rise then fall within a single run, which often trains quickly.

    Why warmup helps: large models and large batches can diverge in the first few hundred steps. Adaptive optimizers start with unreliable gradient statistics, and a small initial rate protects against both problems.

    Use a learning rate range test to pick the peak: increase the rate steadily over a short run and choose a value somewhat below where the loss starts to blow up.

    Example

    A 10,000-step run with a peak rate of 0.001, 1,000 warmup steps and cosine decay to zero:

    1. Step 500: halfway through warmup, 0.001 × 500 / 1,000 = 0.0005.
    2. Step 1,000: the peak, 0.001.
    3. Step 3,250: a quarter of the way through the decay, 0.5 × 0.001 × (1 + cos(π/4)) ≈ 0.000854.
    4. Step 5,500: halfway through the decay, cos(π/2) = 0, so 0.0005.
    5. Step 7,750: about 0.000146; step 10,000: 0.

    The rate stays high for most of the early decay, then falls quickly near the end, which is when fine adjustments pay off.

  13. Q53.Why does weight initialization matter in a neural network?

    Initialization sets the starting point of training. Weights that are too small make signals and gradients shrink layer after layer until they vanish; weights that are too large make them grow until they explode. Good initialization keeps the scale of activations and gradients roughly constant through the depth of the network.

    Key ideas:

    • Break symmetry: if all weights start equal, every neuron in a layer computes the same thing and receives the same update, so they never differentiate. Random initialization fixes this.
    • Variance scaling: draw weights with a variance based on the number of inputs to each neuron, the fan-in, so that summing many inputs does not change the overall scale.
    • Match the activation: rectified activations zero out half their inputs, so they need about twice the variance of tanh-like activations, commonly 2 / fan_in versus about 1 / fan_in.
    • Biases usually start at zero. For a rare positive class, starting the output bias at the log-odds of the base rate speeds up early training.

    How modern architectures reduce the risk: normalization layers and residual connections make training much less sensitive to initialization, and pretrained weights replace random starts entirely in transfer learning.

    If a deep network's loss does not move at all from the first step, check the scale of activations at each layer. Initialization or a missing normalization is a common cause.

  14. Q54.How do early stopping and checkpointing work together?

    Early stopping ends training when the validation metric stops improving for a set number of evaluations, the patience. Checkpointing saves the model during training. Together they stop wasted training and let you restore the best model rather than the last one.

    flowchart TD
      A["Train one epoch"] --> B["Evaluate on validation set"]
      B --> C{"Better than best so far?"}
      C -->|yes| D["Save best checkpoint, reset patience"]
      C -->|no| E["Reduce remaining patience"]
      D --> A
      E --> F{"Patience used up?"}
      F -->|no| A
      F -->|yes| G["Stop and restore best checkpoint"]

    Practical points:

    • Monitor the metric you care about, not just validation loss, if they disagree.
    • Use a minimum improvement so tiny random gains do not reset patience forever.
    • Set patience to match noise: noisy validation scores need more patience, or smoothing.
    • Save full training state in periodic checkpoints, including optimizer state, learning rate schedule and random seeds, so an interrupted run can resume exactly.
    • Keep the best and the latest checkpoints, and delete the rest to save storage.

    The validation set used for early stopping has influenced the model, so report the final result on a separate test set.

  15. Q55.How do you calculate the output size of a convolutional layer?

    Each output position needs the whole kernel to fit inside the padded input, and positions are spaced by the stride. That gives one formula per spatial dimension.

    • output = floor((input + 2 × padding − dilation × (kernel − 1) − 1) / stride) + 1

    What each term means:

    • input: the height or width of the input feature map.
    • kernel: the kernel size along that dimension, such as 3.
    • padding: zeros added on each side; "same" padding with stride 1 uses (kernel − 1) / 2 so the size is unchanged.
    • stride: how far the kernel moves between output positions; a stride of 2 roughly halves the size.
    • dilation: spacing between kernel elements; 1 means a normal, dense kernel.

    Related numbers worth knowing:

    • Output channels equal the number of filters, independent of the formula above.
    • Parameters: kernel_h × kernel_w × input_channels × output_channels, plus one bias per output channel.

    When to use it: designing architectures, debugging shape mismatches, and checking memory use, since activation memory scales with output height × width × channels.

    Example

    Checking sizes through the first layers of a typical image network, and one layer's parameter count:

    def conv_output_size(size: int, kernel: int, stride: int = 1, padding: int = 0, dilation: int = 1) -> int:
        effective = dilation * (kernel - 1) + 1
        return (size + 2 * padding - effective) // stride + 1
    
    
    print(conv_output_size(224, kernel=7, stride=2, padding=3))  # 112
    print(conv_output_size(112, kernel=3, stride=2, padding=1))  # 56
    print(conv_output_size(56, kernel=3, stride=1, padding=1))  # 56
    print(conv_output_size(32, kernel=5))  # 28
    print(conv_output_size(32, kernel=3, dilation=2))  # 28
    print(3 * 3 * 64 * 128 + 128)  # 73856

    The third line is "same" padding, which keeps the size. The last two show that a dilated 3×3 kernel covers the same span as a 5×5 one. A 3×3 convolution from 64 to 128 channels has 73,856 parameters.

  16. Q56.What do pooling and stride do in a convolutional network?

    Both reduce the spatial size of feature maps. That lowers compute and memory, widens what each later neuron can see, and makes the network less sensitive to small shifts in the input.

    Max poolingAverage poolingGlobal average poolingStrided convolution
    Keeps the strongest activation in each windowAverages each windowAverages each channel over the whole mapA convolution that skips positions while learning its filters
    Classic downsampling in image classifiersSmoother downsamplingReplaces large dense layers before the classifierLearned downsampling in most modern networks

    Effects on the network:

    • Fewer computations: halving height and width cuts the work of the next layer by about four.
    • Larger receptive fields: each later neuron covers more of the original image.
    • Some translation tolerance: a feature that moves by a pixel often produces the same pooled output.
    • Lost precise location: a problem for tasks such as segmentation or keypoint detection, which add skip connections or upsampling to recover detail.

    Global average pooling also lets one network accept different input sizes, because it always produces one value per channel.

  17. Q57.What is a receptive field, and how does it grow with depth?

    A neuron's receptive field is the region of the original input that can influence its value. Early layers see small patches; deeper layers see larger regions, which is how a network combines edges into textures, parts and whole objects.

    • r_l = r_(l−1) + (kernel_l − 1) × jump_(l−1)
    • jump_l = jump_(l−1) × stride_l, starting from r_0 = 1 and jump_0 = 1

    What each term means:

    • r_l: the receptive field size after layer l, in input pixels.
    • jump: how many input pixels one step in the current feature map corresponds to; every stride multiplies it.

    Why it matters:

    • An object larger than the receptive field cannot be recognized as a whole by any single neuron.
    • Strides and pooling grow the field fastest, because they multiply the jump for every later layer.
    • Stacked small kernels give large fields with fewer parameters than one big kernel.
    • The effective receptive field is smaller than the theoretical one, since central pixels influence a neuron much more than those at the edges.

    Example

    Receptive field growth through four 3×3 convolutions:

    1. All stride 1: each layer adds 2 pixels, so the fields are 3, 5, 7 and 9.
    2. Second layer with stride 2: layer 1 gives 3, with a jump of 1. Layer 2 gives 3 + 2 × 1 = 5, and its stride makes the jump 2. Layer 3 gives 5 + 2 × 2 = 9, and layer 4 gives 9 + 2 × 2 = 13.
    3. Parameters: three stacked 3×3 layers see a 7×7 region with 3 × 9 = 27 weights per channel pair, against 49 for a single 7×7 kernel, and add two extra non-linearities.
  18. Q58.Why do residual connections make very deep networks trainable?

    A residual connection adds a block's input directly to its output, output = x + F(x), so the block only has to learn a correction to its input rather than a whole new transformation. Very deep networks with these connections train reliably, where plain networks of the same depth train worse than shallower ones.

    flowchart LR
      A["Input x"] --> B["Layers compute F of x"]
      A -->|identity shortcut| C["Add"]
      B --> C
      C --> D["Output x plus F of x"]

    Why it works:

    • Gradient flow: the identity path carries gradients straight back to early layers, so they do not vanish through dozens of multiplications.
    • Easy identity: if a block is not useful, its weights can go to near zero and the block passes its input through. Extra depth then cannot make the network worse.
    • Smoother optimization: the loss surface becomes easier to descend, so standard optimizers converge.

    Where they appear: deep image networks, attention-based language models, where every attention and feed-forward block is wrapped in a residual connection, and many generative models.

    Shapes must match to add. When a block changes the number of channels or the resolution, the shortcut uses a small projection, such as a 1×1 convolution.

  19. Q59.How does data augmentation help, and when can it hurt?

    Data augmentation creates modified copies of training examples that keep their labels, teaching the model which variations do not matter. It acts as regularization and is often the cheapest way to improve a model trained on limited data.

    ImagesTextAudio
    Flips, crops, small rotations, color and brightness changes, blurringSynonym replacement, back-translation, random word droppingAdded noise, time shifts, speed changes, masking frequency bands
    Time seriesTabular
    Jitter, scaling, window croppingSmall noise on numeric features, mixing examples, used cautiously

    When it hurts:

    • The transformation changes the label: flipping a "6" into a "9", mirroring text, or flipping a medical scan where left and right matter.
    • Unrealistic variations: heavy distortions the model will never see in production waste capacity.
    • Augmenting the validation or test set, which inflates scores.
    • Leakage between splits: augmented copies of one original landing in both training and test data.
    • Imbalanced effects: augmentations that suit one class but distort another.

    Choose augmentations from how real inputs vary, such as lighting and camera angles in a warehouse. Then confirm the benefit on an untouched validation set.

  20. Q60.How do the gates in a long short-term memory network control information flow?

    A long short-term memory cell keeps a cell state that runs through time with only small, controlled changes, and uses gates, which are small learned layers with outputs between 0 and 1, to decide what to forget, what to add and what to output at each step.

    Forget gateInput gateCandidate update
    Asks how much of the old cell state to keepAsks how much new information to writeAsks what new information could be written
    Values near 0 erase, near 1 keepScales the candidate updateProposes values from the current input and previous output
    Cell stateOutput gate
    The long-term memoryAsks how much of the memory to expose now
    Updated as old state times forget gate plus candidate times input gateProduces the hidden state passed to the next step

    Why it matters:

    • The cell state is updated additively, so gradients can flow across many time steps without vanishing as quickly as in simple recurrent networks.
    • The gates learn when to hold information, such as remembering an opening quote until the closing one.

    In practice, gated recurrent networks are still used for small, streaming or on-device sequence tasks. Attention-based models have replaced them for most large-scale language work, because they process sequences in parallel and handle long contexts better.