Skip to content

Data Science Interview Questions & Answers (2026)

Practice interview questions and answers organized by company, salary package, topic and difficulty. Mark questions as solved to keep track of your preparation.

Questions solvedStart practicing
3 QUESTIONS FREESign up or log in to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
02

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
03

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
04

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
05

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
06

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
07

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
08

What is the difference between an epoch, a batch and an iteration?

Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
09

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
10

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
11

What is calibration of a classifier?

Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
12

Why do we use activation functions? Why is ReLU popular?

Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
13

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
14

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
15

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
16

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
17

What is feature scaling and which models need it?

Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
18

Explain the Law of Large Numbers.

Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
19

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
20

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
21

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
22

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
23

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
24

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
25

What is an autoencoder and what is it used for?

Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
26

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
27

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
28

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
29

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
30

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
31

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
32

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
33

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
34

How does K-means clustering work and how do you choose k?

Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
35

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
36

Explain ROC curve and AUC.

Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
37

How do you pivot data in Pandas?

Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
38

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
39

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
40

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
41

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
42

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
43

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
44

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
45

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
46

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
47

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
48

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
49

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
50

Pandas: find the top 3 products by revenue in each region.

Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
51

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
52

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
53

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
54

Explain the KNN algorithm and its drawbacks.

Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
55

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
56

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
57

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
58

Pandas: find the top 3 products by revenue in each region.

Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
59

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
60

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
61

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
62

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
63

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
64

Explain ROC curve and AUC.

Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
65

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
66

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
67

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
68

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
69

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
70

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
71

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
72

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
73

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
74

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
75

Pandas: find the top 3 products by revenue in each region.

Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
76

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
77

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
78

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
79

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
80

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
81

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
82

Explain logistic regression.

Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
83

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
84

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
85

What is TF-IDF?

Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
86

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
87

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
88

What is an autoencoder and what is it used for?

Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
89

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
90

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
91

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
92

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
93

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
94

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
95

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
96

Explain the Law of Large Numbers.

Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
97

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
98

What is the difference between an epoch, a batch and an iteration?

Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
99

What is backpropagation?

Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
100

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
101

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
102

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
103

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
104

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
105

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
106

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
107

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
108

What is transfer learning?

Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
109

How do you profile and speed up slow Python code?

Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
110

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
111

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
112

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
113

Pandas: find the top 3 products by revenue in each region.

Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
114

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
115

How does a CNN work?

Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
116

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
117

What is feature scaling and which models need it?

Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
118

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
119

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
120

What is the bias–variance trade-off?

Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
121

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
122

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
123

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
124

What is calibration of a classifier?

Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
125

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
126

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
127

What is a generator and when would you use one?

Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
128

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
129

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
130

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
131

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
132

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
133

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
134

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
135

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
136

How does K-means clustering work and how do you choose k?

Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
137

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
138

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
139

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
140

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
141

How do you deal with high-cardinality categorical features?

Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
142

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
143

What is PCA and when do you use it?

Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
144

Explain ROC curve and AUC.

Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
145

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
146

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
147

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
148

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
149

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
150

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
151

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
152

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
153

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
154

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
155

What is calibration of a classifier?

Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
156

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
157

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
158

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
159

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
160

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
161

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
162

What is the bias–variance trade-off?

Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
163

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
164

What is the difference between iterators and iterables in Python?

Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
165

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
166

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
167

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
168

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
169

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
170

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
171

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
172

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
173

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
174

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
175

Random forest vs a single decision tree?

Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
176

What is an autoencoder and what is it used for?

Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
177

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
178

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
179

Pandas: find the top 3 products by revenue in each region.

Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
180

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
181

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
182

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
183

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
184

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
185

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
186

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
187

What is feature scaling and which models need it?

Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
188

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
189

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
190

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
191

How do you pivot data in Pandas?

Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
192

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
193

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
194

What is TF-IDF?

Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
195

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
196

What is the bias–variance trade-off?

Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
197

How do you profile and speed up slow Python code?

Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
198

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
199

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
200

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
201

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
202

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
203

What is the difference between an epoch, a batch and an iteration?

Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
204

What is a generator and when would you use one?

Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
205

Why is XGBoost so popular?

Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
206

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
207

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
208

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
209

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
210

How does K-means clustering work and how do you choose k?

Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
211

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
212

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
213

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
214

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
215

What is the difference between apply, map and applymap in Pandas?

Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
216

What is sampling bias and how can you reduce it?

Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
217

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
218

What is the difference between iterators and iterables in Python?

Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
219

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
220

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
221

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
222

How do you deal with high-cardinality categorical features?

Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
223

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
224

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
225

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
226

What is the bias–variance trade-off?

Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
227

What is the difference between an epoch, a batch and an iteration?

Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
228

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
229

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
230

Explain ROC curve and AUC.

Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
231

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
232

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
233

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
234

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
235

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
236

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
237

What is PCA and when do you use it?

Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
238

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
239

Why do we use activation functions? Why is ReLU popular?

Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
240

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
241

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
242

How do you detect and treat concept drift?

Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
243

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
244

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
245

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
246

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
247

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
248

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
249

How does a CNN work?

Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
250

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
251

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
252

Random forest vs a single decision tree?

Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
253

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
254

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
255

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
256

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
257

What is the attention mechanism?

Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
258

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
259

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
260

What is backpropagation?

Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
261

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
262

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
263

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
264

What is the difference between apply, map and applymap in Pandas?

Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
265

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
266

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
267

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
268

What is SVM and the kernel trick?

Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
269

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
270

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
271

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
272

Explain the chi-square test.

Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
273

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
274

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
275

What is the difference between iterators and iterables in Python?

Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
276

What is TF-IDF?

Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
277

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
278

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
279

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
280

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
281

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
282

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
283

What is sampling bias and how can you reduce it?

Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
284

What is a generator and when would you use one?

Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
285

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
286

What is transfer learning?

Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
287

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
288

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
289

Explain Bayes' theorem with an example.

Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
290

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
291

How does K-means clustering work and how do you choose k?

Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
292

What is calibration of a classifier?

Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
293

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
294

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
295

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
296

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
297

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
298

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
299

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
300

What is a generator and when would you use one?

Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
301

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
302

What is the difference between apply, map and applymap in Pandas?

Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
303

What is the difference between an epoch, a batch and an iteration?

Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
304

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
305

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
306

What is backpropagation?

Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
307

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
308

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
309

Explain Bayes' theorem with an example.

Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
310

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
311

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
312

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
313

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
314

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
315

Why do we use activation functions? Why is ReLU popular?

Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
316

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
317

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
318

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
319

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
320

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
321

How does K-means clustering work and how do you choose k?

Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
322

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
323

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
324

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
325

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
326

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
327

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
328

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
329

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
330

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
331

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
332

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
333

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
334

What is the attention mechanism?

Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
335

Random forest vs a single decision tree?

Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
336

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
337

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
338

What are precision and recall trade-offs in practice?

Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
339

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
340

What is the difference between iterators and iterables in Python?

Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
341

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
342

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
343

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
344

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
345

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
346

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
347

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
348

What is the Central Limit Theorem?

Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
349

Explain the Law of Large Numbers.

Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
350

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
351

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
352

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
353

What is an autoencoder and what is it used for?

Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
354

What is the difference between iterators and iterables in Python?

Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
355

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
356

Pandas: find the top 3 products by revenue in each region.

Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
357

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
358

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
359

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
360

What is SVM and the kernel trick?

Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
361

How do you choose a learning rate for a neural network?

Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
362

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
363

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
364

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
365

What is the Central Limit Theorem?

Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
366

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
367

Explain ROC curve and AUC.

Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
368

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
369

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
370

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
371

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
372

What is backpropagation?

Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
373

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
374

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
375

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
376

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
377

Explain logistic regression.

Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
378

How do you profile and speed up slow Python code?

Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
379

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
380

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
381

What is sampling bias and how can you reduce it?

Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
382

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
383

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
384

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
385

What is a generator and when would you use one?

Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
386

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
387

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
388

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
389

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
390

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
391

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
392

What is PCA and when do you use it?

Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
393

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
394

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
395

Random forest vs a single decision tree?

Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
396

How does a CNN work?

Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
397

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
398

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
399

How do you pivot data in Pandas?

Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
400

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
401

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
402

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
403

Why do we use activation functions? Why is ReLU popular?

Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
404

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
405

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
406

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
407

What is backpropagation?

Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
408

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
409

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
410

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
411

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
412

How do you detect and treat concept drift?

Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
413

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
414

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
415

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
416

What is the bias–variance trade-off?

Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
417

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
418

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
419

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
420

What is SVM and the kernel trick?

Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
421

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
422

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
423

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
424

Why is XGBoost so popular?

Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
425

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
426

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
427

Explain the chi-square test.

Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
428

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
429

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
430

What is feature scaling and which models need it?

Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
431

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
432

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
433

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
434

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
435

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
436

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
437

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
438

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
439

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
440

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
441

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
442

What is the difference between apply, map and applymap in Pandas?

Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
443

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
444

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
445

What is calibration of a classifier?

Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
446

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
447

What is the difference between iterators and iterables in Python?

Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
448

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
449

How do you detect and treat concept drift?

Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
450

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
451

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
452

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
453

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
454

What is transfer learning?

Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
455

What is sampling bias and how can you reduce it?

Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
456

What is a generator and when would you use one?

Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
457

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
458

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
459

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
460

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
461

What is an autoencoder and what is it used for?

Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
462

Explain the Law of Large Numbers.

Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
463

How does K-means clustering work and how do you choose k?

Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
464

What is the difference between iterators and iterables in Python?

Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
465

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
466

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
467

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
468

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
469

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
470

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
471

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
472

What is the difference between apply, map and applymap in Pandas?

Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
473

What is SVM and the kernel trick?

Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
474

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
475

What is backpropagation?

Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
476

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
477

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
478

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
479

What are precision and recall trade-offs in practice?

Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
480

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
481

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
482

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
483

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
484

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
485

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
486

What is sampling bias and how can you reduce it?

Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
487

How do you profile and speed up slow Python code?

Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
488

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
489

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
490

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
491

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
492

What is the bias–variance trade-off?

Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
493

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
494

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
495

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
496

What is calibration of a classifier?

Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
497

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
498

What are precision and recall trade-offs in practice?

Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
499

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
500

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
501

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
502

What is the bias–variance trade-off?

Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
503

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
504

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
505

Explain the KNN algorithm and its drawbacks.

Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
506

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
507

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
508

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
509

Explain the chi-square test.

Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
510

What is transfer learning?

DeloitteMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
511

How do you handle imbalanced classes?

DeloitteMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
512

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
513

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
514

Why do we use activation functions? Why is ReLU popular?

DeloitteMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
515

What is feature scaling and which models need it?

DeloitteMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
516

What is a generator and when would you use one?

DeloitteMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
517

What is batch normalisation?

DeloitteMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
518

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
519

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
520

Explain Bayes' theorem with an example.

DeloitteMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
521

What is TF-IDF?

AmazonMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
522

What is the difference between parametric and non-parametric tests?

AmazonMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
523

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
524

Why do we use activation functions? Why is ReLU popular?

AmazonMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
525

How does a decision tree decide where to split?

AmazonMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
526

How do you handle imbalanced classes?

AmazonMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
527

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
528

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
529

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
530

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
531

Random forest vs a single decision tree?

AmazonMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
532

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
533

Difference between a shallow copy and a deep copy?

AmazonMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
534

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
535

Why are NumPy arrays faster than Python lists?

AmazonMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
536

What are precision and recall trade-offs in practice?

AmazonMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
537

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
538

Which activation functions do you know and when to use them?

AmazonMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
539

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
540

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
541

What is PCA and when do you use it?

AmazonMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
542

What is the difference between an epoch, a batch and an iteration?

AmazonMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
543

What is the attention mechanism?

AmazonMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
544

What is feature scaling and which models need it?

AmazonMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
545

How do you choose a learning rate for a neural network?

AmazonMedium
Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
546

How do you tune hyperparameters?

AmazonMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
547

What is a generator and when would you use one?

AmazonMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
548

What is a p-value?

AmazonMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
549

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
550

What is statistical power and how can you increase it?

AmazonMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
551

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
552

Your dataset is highly imbalanced (2% positives). How do you handle it?

GoogleMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
553

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
554

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
555

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
556

What is statistical power and how can you increase it?

GoogleMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
557

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
558

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
559

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
560

Explain the chi-square test.

GoogleMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
561

What is the difference between iterators and iterables in Python?

GoogleMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
562

How do you profile and speed up slow Python code?

GoogleMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
563

What is correlation and why does it not imply causation?

GoogleMedium
Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
564

What is PCA and when do you use it?

GoogleMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
565

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
566

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
567

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
568

What is sampling bias and how can you reduce it?

MetaMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
569

What is a p-value?

MetaMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
570

What is batch normalisation?

MetaMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
571

How would you fine-tune a pretrained language model for classification?

MetaHard
Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
572

Pearson vs Spearman correlation?

MetaEasy
Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
573

Pandas: merge vs join vs concat?

MetaMedium
Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
574

Explain the KNN algorithm and its drawbacks.

MetaMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
575

Train accuracy is 95% but test accuracy is 70%. What do you do?

MetaHard
Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
576

CNN vs RNN vs Transformer — what is the difference?

MetaHard
Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
577

What is skewness?

MetaEasy
Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
578

Why is XGBoost so popular?

MetaMedium
Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
579

Explain train, validation and test sets.

MetaEasy
Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
580

What are lambda functions and where are they useful?

MetaMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
581

What are RNNs and why did LSTMs improve them?

MetaMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
582

How would you fine-tune a pretrained language model for classification?

UberHard
Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
583

What are precision and recall trade-offs in practice?

UberMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
584

What is the difference between regression and classification?

UberEasy
Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
585

What is a p-value?

UberMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
586

What is the difference between parametric and non-parametric tests?

UberMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
587

Explain precision vs recall. When would you prefer recall?

UberEasy
Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
588

Type I vs Type II error?

UberEasy
Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
589

What is the difference between bagging and boosting?

UberEasy
Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
590

What is calibration of a classifier?

UberMedium
Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
591

Explain the chi-square test.

UberMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
592

What are *args and **kwargs?

UberEasy
Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
593

Why is XGBoost so popular?

UberMedium
Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
594

How does the Gini impurity differ from entropy?

UberMedium
Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
595

How do you evaluate and explain a model to business stakeholders?

UberHard
Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
596

What is data leakage?

UberEasy
Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
597

How do you tune hyperparameters?

UberMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
598

How do you deploy and monitor a machine learning model?

UberHard
Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
599

Explain the KNN algorithm and its drawbacks.

UberMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
600

How does a CNN work?

UberMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
601

Why do we use activation functions? Why is ReLU popular?

UberMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
602

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
603

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
604

Pandas: find the top 3 products by revenue in each region.

Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
605

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
606

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
607

How do you use groupby with multiple aggregations?

StripeMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
608

Which activation functions do you know and when to use them?

StripeMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
609

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
610

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
611

How do you deal with high-cardinality categorical features?

StripeMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
612

Difference between a shallow copy and a deep copy?

StripeMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
613

Explain logistic regression.

StripeMedium
Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
614

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
615

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
616

What is SVM and the kernel trick?

StripeMedium
Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
617

How does K-means clustering work and how do you choose k?

StripeMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
618

Why do we use activation functions? Why is ReLU popular?

StripeMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
619

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
620

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
621

What are decorators in Python?

StripeMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
622

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
623

What is TF-IDF?

StripeMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
624

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
625

Random forest vs a single decision tree?

PayPalMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
626

What is TF-IDF?

PayPalMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
627

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
628

Why is XGBoost so popular?

PayPalMedium
Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
629

What is an autoencoder and what is it used for?

PayPalMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
630

What is regularization? Explain L1 vs L2.

PayPalMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
631

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
632

What is the difference between an epoch, a batch and an iteration?

PayPalMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
633

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
634

What is gradient descent and what does the learning rate do?

PayPalMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
635

L1 vs L2 regularisation?

PayPalMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
636

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
637

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
638

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
639

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
640

What is calibration of a classifier?

PayPalMedium
Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
641

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
642

What is statistical power and how can you increase it?

RazorpayMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
643

What is feature scaling and which models need it?

RazorpayMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
644

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
645

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
646

L1 vs L2 regularisation?

ZomatoMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
647

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
648

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
649

How does the Gini impurity differ from entropy?

ZomatoMedium
Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
650

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
651

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
652

What are RNNs and why did LSTMs improve them?

ZomatoMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
653

What is transfer learning?

ZomatoMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
654

What is TF-IDF?

ZomatoMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
655

Why do we use activation functions? Why is ReLU popular?

ZomatoMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
656

Explain ROC curve and AUC.

ZomatoMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
657

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
658

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
659

How do you pivot data in Pandas?

ZomatoMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
660

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
661

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
662

What is sampling bias and how can you reduce it?

ZomatoMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
663

Your dataset is highly imbalanced (2% positives). How do you handle it?

ZomatoMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
664

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
665

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
666

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
667

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
668

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
669

Difference between a shallow copy and a deep copy?

ZomatoMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
670

What is the bias–variance trade-off?

ZomatoMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
671

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
672

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
673

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
674

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
675

Your dataset is highly imbalanced (2% positives). How do you handle it?

SwiggyMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
676

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
677

Random forest vs a single decision tree?

SwiggyMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
678

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
679

What is Naive Bayes and why is it called naive?

SwiggyMedium
Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
680

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
681

How does K-means clustering work and how do you choose k?

ZeptoMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
682

Explain train, validation and test sets.

ZeptoEasy
Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
683

How do you detect and treat concept drift?

ZeptoMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
684

Pandas: find the top 3 products by revenue in each region.

ZeptoMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
685

Explain precision vs recall. When would you prefer recall?

ZeptoEasy
Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
686

What is the difference between a function and a method?

ZeptoEasy
Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
687

How would you optimise a slow Pandas pipeline on a 5 GB file?

ZeptoHard
Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
688

How do you evaluate and explain a model to business stakeholders?

ZeptoHard
Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
689

Explain the chi-square test.

ZeptoMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
690

How does linear regression work and what are its assumptions?

ZeptoMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
691

How do you handle missing values?

ZeptoEasy
Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
692

What is the vanishing gradient problem?

ZeptoMedium
Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
693

What is stacking in ensemble learning?

ZeptoMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
694

What is a p-value?

ZeptoMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
695

What is the difference between supervised and unsupervised learning?

ZeptoEasy
Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
696

What is the difference between iterators and iterables in Python?

ZeptoMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
697

Correlation vs covariance?

ZeptoEasy
Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
698

How does a CNN work?

ZeptoMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
699

How would you fine-tune a pretrained language model for classification?

ZeptoHard
Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
700

CNN vs RNN vs Transformer — what is the difference?

ZeptoHard
Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
701

Difference between loc and iloc in Pandas?

ZeptoEasy
Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
702

How does a decision tree decide where to split?

ZeptoMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
703

How would you optimise a slow Pandas pipeline on a 5 GB file?

PaytmHard
Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
704

What is statistical power and how can you increase it?

PaytmMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
705

What is TF-IDF?

PaytmMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
706

What is the difference between Bayesian and frequentist approaches?

PaytmHard
Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
707

Explain ROC curve and AUC.

PaytmMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
708

Explain Bayes' theorem with an example.

PaytmMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
709

L1 vs L2 regularisation?

PaytmMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
710

What is the Central Limit Theorem?

PaytmMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
711

What is data leakage?

PaytmEasy
Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
712

What is the difference between a function and a method?

PaytmEasy
Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
713

What is the difference between == and is?

PaytmEasy
Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
714

What is overfitting and how do you prevent it?

PaytmEasy
Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
715

Explain p-value in simple words.

PaytmEasy
Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
716

Which activation functions do you know and when to use them?

PaytmMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
717

Write a function to calculate RMSE without any library.

PaytmEasy
Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
718

Difference between loc and iloc in Pandas?

PaytmEasy
Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
719

What are decorators in Python?

PaytmMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
720

What is a RAG system and why use it?

PaytmHard
Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
721

What is a p-value?

PaytmMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
722

What is standard deviation and what does it tell you?

PaytmEasy
Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
723

What is the bias–variance trade-off?

PaytmMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
724

What is gradient descent and what does the learning rate do?

PaytmMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
725

What is transfer learning?

PaytmMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
726

How do you deal with high-cardinality categorical features?

PaytmMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
727

What is a normal distribution?

PaytmEasy
Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
728

Explain precision vs recall. When would you prefer recall?

PaytmEasy
Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
729

Explain logistic regression.

PaytmMedium
Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
730

How do you deploy and monitor a machine learning model?

PaytmHard
Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
731

What is an autoencoder and what is it used for?

PaytmMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
732

How does linear regression work and what are its assumptions?

PaytmMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
733

How do you detect and treat concept drift?

PaytmMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
734

How do you pivot data in Pandas?

PaytmMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
735

How do you perform feature selection?

PaytmMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
736

Difference between a shallow copy and a deep copy?

PaytmMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
737

Design an end-to-end churn prediction system.

PaytmHard
Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
738

What is the difference between apply, map and applymap in Pandas?

PaytmMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
739

Explain the KNN algorithm and its drawbacks.

PaytmMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
740

What is the difference between mean, median and mode?

PaytmEasy
Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
741

What is a neural network?

PaytmEasy
Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
742

What are RNNs and why did LSTMs improve them?

PaytmMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
743

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
744

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
745

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
746

What is SVM and the kernel trick?

Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
747

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
748

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
749

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
750

What is the difference between iterators and iterables in Python?

Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
751

What is feature scaling and which models need it?

Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
752

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
753

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
754

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
755

Pandas: find the top 3 products by revenue in each region.

Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
756

What is calibration of a classifier?

Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
757

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
758

Explain logistic regression.

Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
759

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
760

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
761

How do you pivot data in Pandas?

Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
762

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
763

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
764

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
765

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
766

How does dropout work?

Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
767

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
768

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
769

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
770

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
771

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
772

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
773

Why do we use activation functions? Why is ReLU popular?

Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
774

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
775

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
776

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
777

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
778

How do you choose a learning rate for a neural network?

Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
779

What are common ways to evaluate NLP models?

IntuitMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
780

How does dropout work?

IntuitMedium
Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
781

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
782

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
783

How do you handle imbalanced classes?

IntuitMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
784

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
785

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
786

What is calibration of a classifier?

IntuitMedium
Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
787

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
788

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
789

What is a p-value?

IntuitMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
790

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
791

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
792

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
793

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
794

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
795

What is backpropagation?

IntuitMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
796

What is PCA and when do you use it?

IntuitMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
797

Why are NumPy arrays faster than Python lists?

IntuitMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
798

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
799

Pandas: find the top 3 products by revenue in each region.

IntuitMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
800

What is Naive Bayes and why is it called naive?

IntuitMedium
Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
801

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
802

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
803

How do you tune hyperparameters?

IntuitMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
804

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
805

What is a generator and when would you use one?

IntuitMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
806

How do you choose a learning rate for a neural network?

IntuitMedium
Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
807

How does the Gini impurity differ from entropy?

IntuitMedium
Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
808

Your dataset is highly imbalanced (2% positives). How do you handle it?

IntuitMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
809

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
810

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
811

What is feature scaling and which models need it?

WalmartMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
812

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
813

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
814

L1 vs L2 regularisation?

WalmartMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
815

Pandas: find the top 3 products by revenue in each region.

WalmartMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
816

Explain logistic regression.

WalmartMedium
Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
817

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
818

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
819

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
820

What is stacking in ensemble learning?

WalmartMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
821

Why is XGBoost so popular?

WalmartMedium
Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
822

Why do we use activation functions? Why is ReLU popular?

Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
823

How do you choose a learning rate for a neural network?

Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
824

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
825

What is backpropagation?

Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
826

Random forest vs a single decision tree?

Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
827

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
828

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
829

What is the difference between an epoch, a batch and an iteration?

Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
830

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
831

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
832

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
833

Explain the chi-square test.

Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
834

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
835

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
836

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
837

What is the difference between iterators and iterables in Python?

Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
838

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
839

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
840

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
841

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
842

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
843

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
844

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
845

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
846

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
847

Explain the Law of Large Numbers.

Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
848

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
849

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
850

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
851

How do you profile and speed up slow Python code?

Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
852

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
853

How do you choose a learning rate for a neural network?

Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
854

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
855

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
856

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
857

What is sampling bias and how can you reduce it?

Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
858

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
859

What are precision and recall trade-offs in practice?

Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
860

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
861

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
862

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
863

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
864

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
865

Pearson vs Spearman correlation?

CiscoEasy
Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
866

What is cross-validation and why use it?

VisaEasy
Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
867

What are *args and **kwargs?

VisaEasy
Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
868

What is NumPy broadcasting?

VisaEasy
Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
869

What are lambda functions and where are they useful?

VisaMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
870

How do you pivot data in Pandas?

HCLTechMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
871

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
872

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
873

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
874

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
875

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
876

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
877

What is transfer learning?

Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
878

How do you deal with high-cardinality categorical features?

Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
879

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
880

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
881

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
882

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
883

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
884

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
885

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
886

What is the Central Limit Theorem?

Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
887

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
888

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
889

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
890

Explain the Law of Large Numbers.

Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
891

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
892

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
893

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
894

What is the difference between an epoch, a batch and an iteration?

Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
895

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
896

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
897

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
898

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
899

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
900

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
901

What is SVM and the kernel trick?

Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
902

What is the bias–variance trade-off?

Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
903

Explain Bayes' theorem with an example.

Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
904

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
905

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
906

What is calibration of a classifier?

Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
907

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
908

How does a CNN work?

Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
909

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
910

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
911

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
912

What is backpropagation?

Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
913

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
914

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
915

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
916

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
917

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
918

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
919

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
920

What is the bias–variance trade-off?

Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
921

Explain the KNN algorithm and its drawbacks.

Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
922

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
923

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
924

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
925

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
926

Explain the Law of Large Numbers.

Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
927

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
928

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
929

What are precision and recall trade-offs in practice?

Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
930

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
931

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
932

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
933

How does K-means clustering work and how do you choose k?

Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
934

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
935

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
936

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
937

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
938

How do you profile and speed up slow Python code?

Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
939

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
940

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
941

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
942

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
943

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
944

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
945

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
946

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
947

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
948

What is feature scaling and which models need it?

Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
949

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
950

What is TF-IDF?

Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
951

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
952

Why is XGBoost so popular?

Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
953

How do you deal with high-cardinality categorical features?

Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
954

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
955

What is SVM and the kernel trick?

Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
956

Explain the chi-square test.

Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
957

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
958

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
959

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
960

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
961

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
962

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
963

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
964

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
965

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
966

Explain the chi-square test.

Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
967

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
968

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
969

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
970

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
971

Why is XGBoost so popular?

Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
972

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
973

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
974

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
975

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
976

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
977

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
978

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
979

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
980

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
981

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
982

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
983

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
984

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
985

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
986

What is PCA and when do you use it?

Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
987

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
988

What is the bias–variance trade-off?

Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
989

What is the attention mechanism?

Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
990

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
991

Random forest vs a single decision tree?

Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
992

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
993

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
994

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
995

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
996

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
997

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
998

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
999

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
1000

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
1001

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
1002

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
1003

Explain logistic regression.

Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
1004

What is SVM and the kernel trick?

Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
1005

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
1006

What is calibration of a classifier?

Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
1007

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
1008

What are precision and recall trade-offs in practice?

Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
1009

Explain the KNN algorithm and its drawbacks.

Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
1010

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
1011

What is a generator and when would you use one?

Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
1012

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
1013

What is the difference between apply, map and applymap in Pandas?

Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
1014

How do you deal with high-cardinality categorical features?

Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
1015

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
1016

What is an autoencoder and what is it used for?

Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
1017

How do you choose a learning rate for a neural network?

Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
1018

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
1019

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
1020

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
1021

How do you detect and treat concept drift?

Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
1022

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
1023

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
1024

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
1025

What is feature scaling and which models need it?

Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
1026

What is TF-IDF?

Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
1027

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
1028

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
1029

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
1030

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
1031

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
1032

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
1033

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
1034

How does K-means clustering work and how do you choose k?

Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
1035

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
1036

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
1037

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
1038

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
1039

How do you detect and treat concept drift?

Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
1040

What is the difference between apply, map and applymap in Pandas?

Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
1041

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
1042

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
1043

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
1044

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
1045

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
1046

Explain the KNN algorithm and its drawbacks.

Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
1047

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
1048

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
1049

What is an autoencoder and what is it used for?

Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
1050

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
1051

Random forest vs a single decision tree?

Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
1052

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
1053

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
1054

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
1055

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
1056

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
1057

What is PCA and when do you use it?

Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
1058

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
1059

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
1060

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
1061

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
1062

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
1063

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
1064

What is the Central Limit Theorem?

Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
1065

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
1066

How do you pivot data in Pandas?

Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
1067

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
1068

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
1069

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
1070

What is the attention mechanism?

Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
1071

Explain ROC curve and AUC.

Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
1072

How does a CNN work?

Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
1073

Why do we use activation functions? Why is ReLU popular?

Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
1074

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
1075

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
1076

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
1077

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
1078

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
1079

How do you choose a learning rate for a neural network?

Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
1080

What is TF-IDF?

Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
1081

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
1082

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
1083

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
1084

Why is XGBoost so popular?

Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
1085

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
1086

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
1087

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
1088

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
1089

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
1090

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
1091

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
1092

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
1093

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
1094

What is a generator and when would you use one?

Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
1095

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
1096

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
1097

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
1098

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
1099

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
1100

What is SVM and the kernel trick?

Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
1101

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
1102

What is the difference between apply, map and applymap in Pandas?

Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
1103

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
1104

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
1105

How do you profile and speed up slow Python code?

Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
1106

How do you detect and treat concept drift?

Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
1107

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
1108

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
1109

What is sampling bias and how can you reduce it?

Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
1110

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
1111

Pandas: find the top 3 products by revenue in each region.

Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
1112

What is backpropagation?

Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
1113

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
1114

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
1115

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
1116

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
1117

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
1118

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
1119

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
1120

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
1121

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
1122

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
1123

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
1124

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
1125

What is the Central Limit Theorem?

Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
1126

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
1127

What is the attention mechanism?

Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
1128

How do you pivot data in Pandas?

Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
1129

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
1130

What is SVM and the kernel trick?

Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
1131

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
1132

Why do we use activation functions? Why is ReLU popular?

Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
1133

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
1134

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
1135

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
1136

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
1137

What is calibration of a classifier?

Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
1138

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
1139

What is TF-IDF?

Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
1140

Explain logistic regression.

Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
1141

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
1142

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
1143

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
1144

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
1145

Explain Bayes' theorem with an example.

Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
1146

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
1147

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
1148

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
1149

What is the difference between apply, map and applymap in Pandas?

Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
1150

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
1151

What is transfer learning?

Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
1152

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
1153

What is an autoencoder and what is it used for?

Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
1154

What are precision and recall trade-offs in practice?

Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
1155

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
1156

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
1157

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
1158

What is SVM and the kernel trick?

Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
1159

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
1160

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
1161

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
1162

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
1163

Why do we use activation functions? Why is ReLU popular?

Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
1164

How do you choose a learning rate for a neural network?

Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
1165

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
1166

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
1167

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
1168

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
1169

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
1170

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
1171

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
1172

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
1173

What is transfer learning?

Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
1174

How does a CNN work?

Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
1175

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
1176

Explain the KNN algorithm and its drawbacks.

Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
1177

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
1178

What is calibration of a classifier?

Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
1179

Explain ROC curve and AUC.

Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
1180

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
1181

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
1182

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
1183

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
1184

Explain Bayes' theorem with an example.

Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
1185

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
1186

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
1187

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
1188

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
1189

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
1190

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
1191

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
1192

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
1193

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
1194

Explain logistic regression.

Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
1195

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
1196

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
1197

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
1198

How do you detect and treat concept drift?

Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
1199

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
1200

How do you deal with high-cardinality categorical features?

Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
1201

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
1202

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
1203

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
1204

How does a CNN work?

Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
1205

Explain the KNN algorithm and its drawbacks.

Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
1206

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
1207

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
1208

What is PCA and when do you use it?

Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
1209

How do you profile and speed up slow Python code?

Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
1210

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
1211

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
1212

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
1213

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
1214

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
1215

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
1216

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
1217

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
1218

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
1219

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
1220

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
1221

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
1222

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
1223

Why is XGBoost so popular?

Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
1224

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
1225

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
1226

What is the attention mechanism?

Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
1227

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
1228

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
1229

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
1230

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
1231

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
1232

What is the difference between an epoch, a batch and an iteration?

Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
1233

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
1234

What is PCA and when do you use it?

Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
1235

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
1236

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
1237

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
1238

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
1239

Difference between a shallow copy and a deep copy?

TCSMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
1240

Explain the KNN algorithm and its drawbacks.

TCSMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
1241

What is the difference between iterators and iterables in Python?

TCSMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
1242

Explain logistic regression.

TCSMedium
Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
1243

What is multicollinearity and how do you handle it?

TCSHard
Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
1244

Pearson vs Spearman correlation?

TCSEasy
Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
1245

What are precision and recall trade-offs in practice?

TCSMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
1246

What is tokenisation in NLP?

TCSEasy
Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
1247

Explain Bayes' theorem with an example.

TCSMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
1248

What is backpropagation?

TCSMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
1249

How does the Gini impurity differ from entropy?

TCSMedium
Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
1250

Explain p-value in simple words.

TCSEasy
Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
1251

What is the difference between bagging and boosting?

TCSEasy
Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
1252

How does linear regression work and what are its assumptions?

TCSMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
1253

L1 vs L2 regularisation?

TCSMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
1254

What is overfitting and how do you prevent it?

TCSEasy
Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
1255

How do you design an A/B test?

TCSHard
Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
1256

Design an end-to-end churn prediction system.

TCSHard
Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
1257

What is a neural network?

TCSEasy
Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
1258

What is the bias–variance trade-off?

TCSMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
1259

What is a Poisson distribution used for?

TCSEasy
Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
1260

What is regularization? Explain L1 vs L2.

TCSMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
1261

What is the difference between a set and a dictionary?

TCSEasy
Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
1262

How do you profile and speed up slow Python code?

TCSMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
1263

What is transfer learning?

TCSMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
1264

What is the Central Limit Theorem?

TCSMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
1265

How do you pivot data in Pandas?

TCSMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
1266

What is the difference between apply, map and applymap in Pandas?

TCSMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
1267

What is the difference between == and is?

TCSEasy
Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
1268

What is the difference between parametric and non-parametric tests?

TCSMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
1269

How do you handle imbalanced classes?

TCSMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
1270

Correlation vs covariance?

TCSEasy
Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
1271

What is standard deviation and what does it tell you?

TCSEasy
Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
1272

How does a decision tree decide where to split?

TCSMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
1273

Write a function to calculate RMSE without any library.

TCSEasy
Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
1274

Which activation functions do you know and when to use them?

TCSMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
1275

Your dataset is highly imbalanced (2% positives). How do you handle it?

TCSMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
1276

What is the difference between generative and discriminative models?

TCSHard
Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
1277

What is skewness?

TCSEasy
Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
1278

What are Python's main built-in data types?

TCSEasy
Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
1279

What is NumPy broadcasting?

TCSEasy
Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
1280

How do list comprehensions work and why use them?

TCSEasy
Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
1281

How would you build a churn prediction model end to end?

TCSHard
Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
1282

What is SVM and the kernel trick?

TCSMedium
Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
1283

What is a RAG system and why use it?

TCSHard
Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
1284

What is feature scaling and which models need it?

TCSMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
1285

How would you fine-tune a pretrained language model for classification?

TCSHard
Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
1286

What is stacking in ensemble learning?

TCSMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
1287

What are common ways to evaluate NLP models?

TCSMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
1288

What is the difference between list, tuple, set and dict in Python?

TCSEasy
Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
1289

Explain ROC curve and AUC.

TCSMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
1290

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
1291

What is feature scaling and which models need it?

InfosysMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
1292

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
1293

What is calibration of a classifier?

InfosysMedium
Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
1294

Difference between a shallow copy and a deep copy?

InfosysMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
1295

Explain the KNN algorithm and its drawbacks.

InfosysMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
1296

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
1297

What is the difference between parametric and non-parametric tests?

InfosysMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
1298

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
1299

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
1300

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
1301

Why do we use activation functions? Why is ReLU popular?

InfosysMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
1302

What are precision and recall trade-offs in practice?

InfosysMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
1303

How does linear regression work and what are its assumptions?

InfosysMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
1304

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
1305

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
1306

Which activation functions do you know and when to use them?

InfosysMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
1307

Why is XGBoost so popular?

InfosysMedium
Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
1308

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
1309

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
1310

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
1311

Pandas: find the top 3 products by revenue in each region.

InfosysMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
1312

What is the Central Limit Theorem?

InfosysMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
1313

Explain the Law of Large Numbers.

InfosysMedium
Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
1314

How do you profile and speed up slow Python code?

InfosysMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
1315

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
1316

What is transfer learning?

InfosysMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
1317

What is statistical power and how can you increase it?

InfosysMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
1318

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
1319

Why are NumPy arrays faster than Python lists?

InfosysMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
1320

What is a confidence interval?

InfosysMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
1321

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
1322

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
1323

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
1324

Explain logistic regression.

InfosysMedium
Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
1325

What are decorators in Python?

InfosysMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
1326

What is the difference between an epoch, a batch and an iteration?

InfosysMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
1327

How does a CNN work?

InfosysMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
1328

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
1329

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
1330

What are common ways to evaluate NLP models?

InfosysMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
1331

What is backpropagation?

InfosysMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
1332

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
1333

How do you detect outliers?

InfosysMedium
Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
1334

How do you use groupby with multiple aggregations?

InfosysMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
1335

Pandas: merge vs join vs concat?

InfosysMedium
Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
1336

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
1337

Your dataset is highly imbalanced (2% positives). How do you handle it?

InfosysMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
1338

How do you detect and treat concept drift?

InfosysMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
1339

What is a generator and when would you use one?

InfosysMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
1340

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
1341

Explain the chi-square test.

InfosysMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
1342

What are lambda functions and where are they useful?

InfosysMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
1343

What is batch normalisation?

InfosysMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
1344

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
1345

How do you deal with high-cardinality categorical features?

InfosysMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
1346

What is the bias–variance trade-off?

InfosysMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
1347

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
1348

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
1349

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
1350

What is the attention mechanism?

InfosysMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
1351

What is stacking in ensemble learning?

InfosysMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
1352

How do you perform feature selection?

InfosysMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
1353

What is TF-IDF?

InfosysMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
1354

What is the difference between list, tuple, set and dict in Python?

WiproEasy
Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
1355

What is calibration of a classifier?

WiproMedium
Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
1356

What is the difference between supervised and unsupervised learning?

WiproEasy
Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
1357

How do you detect outliers?

WiproMedium
Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
1358

How do you choose a learning rate for a neural network?

WiproMedium
Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
1359

How do you use groupby with multiple aggregations?

WiproMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
1360

What is a Poisson distribution used for?

WiproEasy
Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
1361

Your dataset is highly imbalanced (2% positives). How do you handle it?

WiproMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
1362

What are *args and **kwargs?

WiproEasy
Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
1363

How do you design an A/B test?

WiproHard
Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
1364

Design an end-to-end churn prediction system.

WiproHard
Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
1365

What is PCA and when do you use it?

WiproMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
1366

Why are NumPy arrays faster than Python lists?

WiproMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
1367

What is the difference between iterators and iterables in Python?

WiproMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
1368

What is the Central Limit Theorem?

WiproMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
1369

What is the difference between == and is?

WiproEasy
Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
1370

What is skewness?

WiproEasy
Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
1371

What is feature scaling and which models need it?

WiproMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
1372

How do you handle missing values?

WiproEasy
Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
1373

Which activation functions do you know and when to use them?

WiproMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
1374

Why is XGBoost so popular?

WiproMedium
Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
1375

What is the difference between Bayesian and frequentist approaches?

WiproHard
Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
1376

What are precision and recall trade-offs in practice?

WiproMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
1377

Pandas: find the top 3 products by revenue in each region.

WiproMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
1378

Explain p-value in simple words.

WiproEasy
Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
1379

What are common ways to evaluate NLP models?

WiproMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
1380

How do you pivot data in Pandas?

WiproMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
1381

Train accuracy is 95% but test accuracy is 70%. What do you do?

WiproHard
Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
1382

Explain logistic regression.

WiproMedium
Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
1383

What is a RAG system and why use it?

WiproHard
Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
1384

How does dropout work?

WiproMedium
Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
1385

How do you detect and treat concept drift?

WiproMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
1386

What is the difference between a function and a method?

WiproEasy
Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
1387

What is gradient descent and what does the learning rate do?

WiproMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
1388

What is the attention mechanism?

WiproMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
1389

What are decorators in Python?

WiproMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
1390

How does linear regression work and what are its assumptions?

WiproMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
1391

What is statistical power and how can you increase it?

WiproMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
1392

How do you remove duplicates from a DataFrame?

WiproEasy
Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
1393

How does a decision tree decide where to split?

WiproMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
1394

How would you fine-tune a pretrained language model for classification?

WiproHard
Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
1395

What is a generator and when would you use one?

WiproMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
1396

What is sampling bias and how can you reduce it?

WiproMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
1397

L1 vs L2 regularisation?

WiproMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
1398

How do you profile and speed up slow Python code?

WiproMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
1399

What are lambda functions and where are they useful?

WiproMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
1400

Explain the chi-square test.

WiproMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
1401

Explain train, validation and test sets.

WiproEasy
Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
1402

How do list comprehensions work and why use them?

WiproEasy
Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
1403

Pearson vs Spearman correlation?

WiproEasy
Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
1404

How do you deal with high-cardinality categorical features?

WiproMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
1405

How do you tune hyperparameters?

WiproMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
1406

Why do we use activation functions? Why is ReLU popular?

WiproMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
1407

What is standard deviation and what does it tell you?

WiproEasy
Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
1408

Correlation vs covariance?

WiproEasy
Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
1409

Difference between a shallow copy and a deep copy?

WiproMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
1410

What is the difference between bagging and boosting?

WiproEasy
Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
1411

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
1412

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
1413

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
1414

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
1415

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
1416

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
1417

What is PCA and when do you use it?

Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
1418

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
1419

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
1420

What is backpropagation?

Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
1421

Explain Bayes' theorem with an example.

Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
1422

What is feature scaling and which models need it?

Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
1423

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
1424

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
1425

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
1426

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
1427

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
1428

How do you profile and speed up slow Python code?

Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
1429

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
1430

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
1431

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
1432

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
1433

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
1434

What is TF-IDF?

Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
1435

Explain logistic regression.

Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
1436

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
1437

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
1438

Why is XGBoost so popular?

Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
1439

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
1440

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
1441

How do you deal with high-cardinality categorical features?

Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
1442

Explain the Law of Large Numbers.

Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
1443

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
1444

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
1445

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
1446

How does a CNN work?

Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
1447

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
1448

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
1449

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
1450

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
1451

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
1452

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
1453

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
1454

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
1455

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
1456

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
1457

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
1458

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
1459

What is an autoencoder and what is it used for?

Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
1460

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
1461

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
1462

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
1463

Pandas: find the top 3 products by revenue in each region.

Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
1464

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
1465

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
1466

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
1467

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
1468

What is calibration of a classifier?

Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
1469

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
1470

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
1471

Explain the chi-square test.

Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
1472

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
1473

How do you detect and treat concept drift?

Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
1474

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
1475

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
1476

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
1477

Why do we use activation functions? Why is ReLU popular?

Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
1478

What is a generator and when would you use one?

Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
1479

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
1480

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
1481

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
1482

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
1483

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
1484

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
1485

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
1486

What is the difference between iterators and iterables in Python?

Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
1487

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
1488

What is the Central Limit Theorem?

Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
1489

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
1490

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
1491

Explain Bayes' theorem with an example.

Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
1492

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
1493

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
1494

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
1495

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
1496

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
1497

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
1498

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
1499

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
1500

Why is XGBoost so popular?

Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
1501

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
1502

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
1503

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
1504

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
1505

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
1506

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
1507

How does dropout work?

Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
1508

Pandas: find the top 3 products by revenue in each region.

Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
1509

What is the attention mechanism?

Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
1510

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
1511

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
1512

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
1513

How do you detect and treat concept drift?

Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
1514

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
1515

How do you pivot data in Pandas?

Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
1516

How do you choose a learning rate for a neural network?

Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
1517

What is SVM and the kernel trick?

Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
1518

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
1519

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
1520

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
1521

What is the difference between an epoch, a batch and an iteration?

Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
1522

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
1523

How do you profile and speed up slow Python code?

Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
1524

What is TF-IDF?

Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
1525

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
1526

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
1527

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
1528

How do you deal with high-cardinality categorical features?

Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
1529

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
1530

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
1531

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
1532

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
1533

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
1534

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
1535

How does K-means clustering work and how do you choose k?

Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
1536

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
1537

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
1538

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
1539

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
1540

What is SVM and the kernel trick?

DeloitteMedium
Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
1541

What is backpropagation?

DeloitteMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
1542

What is Naive Bayes and why is it called naive?

DeloitteMedium
Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
1543

Pandas: find the top 3 products by revenue in each region.

DeloitteMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
1544

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
1545

How does a decision tree decide where to split?

DeloitteMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
1546

What is the attention mechanism?

DeloitteMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
1547

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
1548

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
1549

L1 vs L2 regularisation?

DeloitteMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
1550

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
1551

Explain ROC curve and AUC.

DeloitteMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
1552

What is stacking in ensemble learning?

DeloitteMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
1553

What are common ways to evaluate NLP models?

DeloitteMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
1554

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
1555

What are lambda functions and where are they useful?

DeloitteMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
1556

What is the vanishing gradient problem?

DeloitteMedium
Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
1557

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
1558

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
1559

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
1560

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
1561

Explain the chi-square test.

DeloitteMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
1562

How do you detect and treat concept drift?

DeloitteMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
1563

What is an autoencoder and what is it used for?

DeloitteMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
1564

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
1565

What are decorators in Python?

DeloitteMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
1566

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
1567

What are precision and recall trade-offs in practice?

DeloitteMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
1568

Difference between a shallow copy and a deep copy?

DeloitteMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
1569

What are RNNs and why did LSTMs improve them?

DeloitteMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
1570

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
1571

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
1572

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
1573

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
1574

How do you tune hyperparameters?

DeloitteMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
1575

How do you choose a learning rate for a neural network?

DeloitteMedium
Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
1576

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
1577

What is TF-IDF?

DeloitteMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
1578

What is the difference between an epoch, a batch and an iteration?

DeloitteMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
1579

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
1580

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
1581

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
1582

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
1583

What is a p-value?

DeloitteMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
1584

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
1585

How do you perform feature selection?

DeloitteMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
1586

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
1587

Why are NumPy arrays faster than Python lists?

DeloitteMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
1588

What is the difference between parametric and non-parametric tests?

DeloitteMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
1589

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
1590

How does linear regression work and what are its assumptions?

DeloitteMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
1591

What is regularization? Explain L1 vs L2.

DeloitteMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
1592

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
1593

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
1594

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
1595

How do you deal with high-cardinality categorical features?

DeloitteMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
1596

How does dropout work?

DeloitteMedium
Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
1597

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
1598

What is a confidence interval?

DeloitteMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
1599

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
1600

Which activation functions do you know and when to use them?

DeloitteMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
1601

Your dataset is highly imbalanced (2% positives). How do you handle it?

DeloitteMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
1602

How do you pivot data in Pandas?

DeloitteMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
1603

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
1604

Explain the KNN algorithm and its drawbacks.

DeloitteMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
1605

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
1606

What is sampling bias and how can you reduce it?

AmazonMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
1607

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
1608

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
1609

How does the Gini impurity differ from entropy?

AmazonMedium
Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
1610

How do you deal with high-cardinality categorical features?

AmazonMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
1611

What is stacking in ensemble learning?

AmazonMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
1612

How do you perform feature selection?

AmazonMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
1613

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
1614

Explain ROC curve and AUC.

AmazonMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
1615

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
1616

L1 vs L2 regularisation?

AmazonMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
1617

What is the difference between apply, map and applymap in Pandas?

AmazonMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
1618

What are lambda functions and where are they useful?

AmazonMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
1619

What is an autoencoder and what is it used for?

AmazonMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
1620

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
1621

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
1622

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
1623

Why is XGBoost so popular?

AmazonMedium
Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
1624

Explain Bayes' theorem with an example.

AmazonMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
1625

Pandas: merge vs join vs concat?

AmazonMedium
Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
1626

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
1627

What are common ways to evaluate NLP models?

AmazonMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
1628

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
1629

What is the Central Limit Theorem?

AmazonMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
1630

How does dropout work?

AmazonMedium
Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
1631

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
1632

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
1633

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
1634

Explain the KNN algorithm and its drawbacks.

AmazonMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
1635

Explain the chi-square test.

AmazonMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
1636

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
1637

How does K-means clustering work and how do you choose k?

AmazonMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
1638

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
1639

Your dataset is highly imbalanced (2% positives). How do you handle it?

AmazonMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
1640

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
1641

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
1642

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
1643

Explain ROC curve and AUC.

GoogleMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
1644

Which activation functions do you know and when to use them?

GoogleMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
1645

How does linear regression work and what are its assumptions?

GoogleMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
1646

What is transfer learning?

GoogleMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
1647

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
1648

What is the Global Interpreter Lock (GIL)?

GoogleMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
1649

What is the difference between apply, map and applymap in Pandas?

GoogleMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
1650

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
1651

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
1652

What are precision and recall trade-offs in practice?

GoogleMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
1653

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
1654

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
1655

Explain Bayes' theorem with an example.

GoogleMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
1656

How do you tune hyperparameters?

GoogleMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
1657

What is the difference between parametric and non-parametric tests?

GoogleMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
1658

How do you perform feature selection?

GoogleMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
1659

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
1660

What are common ways to evaluate NLP models?

GoogleMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
1661

How do you use groupby with multiple aggregations?

GoogleMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
1662

L1 vs L2 regularisation?

GoogleMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
1663

What is a p-value?

GoogleMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
1664

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
1665

Pandas: find the top 3 products by revenue in each region.

GoogleMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
1666

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
1667

What are RNNs and why did LSTMs improve them?

GoogleMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
1668

Pandas: merge vs join vs concat?

GoogleMedium
Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
1669

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
1670

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
1671

What is the Central Limit Theorem?

GoogleMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
1672

What is gradient descent and what does the learning rate do?

GoogleMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
1673

What is the difference between an epoch, a batch and an iteration?

GoogleMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
1674

How does dropout work?

GoogleMedium
Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
1675

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
1676

How do you choose a learning rate for a neural network?

GoogleMedium
Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
1677

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
1678

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
1679

What is feature scaling and which models need it?

GoogleMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
1680

Why is XGBoost so popular?

GoogleMedium
Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
1681

How do you tune hyperparameters?

MetaMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
1682

How do you detect and treat concept drift?

MetaMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
1683

How do you deploy and monitor a machine learning model?

MetaHard
Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
1684

How do list comprehensions work and why use them?

MetaEasy
Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
1685

What are precision and recall trade-offs in practice?

MetaMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
1686

What is feature scaling and which models need it?

MetaMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
1687

Explain Bayes' theorem with an example.

MetaMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
1688

How do you profile and speed up slow Python code?

MetaMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
1689

How does K-means clustering work and how do you choose k?

MetaMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
1690

Explain the chi-square test.

MetaMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
1691

What is the difference between Bayesian and frequentist approaches?

MetaHard
Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
1692

What is data leakage?

MetaEasy
Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
1693

What is transfer learning?

MetaMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
1694

What are *args and **kwargs?

MetaEasy
Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
1695

What is the difference between list, tuple, set and dict in Python?

MetaEasy
Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
1696

How do you evaluate and explain a model to business stakeholders?

MetaHard
Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
1697

How do you handle imbalanced classes?

MetaMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
1698

What is SVM and the kernel trick?

MetaMedium
Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
1699

Difference between a shallow copy and a deep copy?

MetaMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
1700

What is a RAG system and why use it?

MetaHard
Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
1701

What is a Poisson distribution used for?

MetaEasy
Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
1702

What is cross-validation and why use it?

MetaEasy
Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
1703

How do you perform feature selection?

MetaMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
1704

What is the difference between regression and classification?

MetaEasy
Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
1705

Explain p-value in simple words.

MetaEasy
Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
1706

How do you use groupby with multiple aggregations?

MetaMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
1707

What is the vanishing gradient problem?

MetaMedium
Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
1708

How do transformers differ from RNNs?

MetaHard
Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
1709

Type I vs Type II error?

MetaEasy
Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
1710

What is PCA and when do you use it?

MetaMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
1711

What is a confidence interval?

MetaMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
1712

How do you remove duplicates from a DataFrame?

MetaEasy
Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
1713

How do you handle missing values?

MetaEasy
Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
1714

What is stacking in ensemble learning?

MetaMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
1715

What is the difference between == and is?

MetaEasy
Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
1716

How does a CNN work?

MetaMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
1717

Explain logistic regression.

MetaMedium
Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
1718

What is the bias–variance trade-off?

Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
1719

How does a CNN work?

Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
1720

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
1721

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
1722

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
1723

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
1724

What is TF-IDF?

Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
1725

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
1726

Explain ROC curve and AUC.

Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
1727

Explain the Law of Large Numbers.

Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
1728

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
1729

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
1730

How does K-means clustering work and how do you choose k?

Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
1731

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
1732

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
1733

How do you profile and speed up slow Python code?

Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
1734

Explain the chi-square test.

Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
1735

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
1736

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
1737

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
1738

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
1739

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
1740

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
1741

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
1742

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
1743

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
1744

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
1745

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
1746

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
1747

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
1748

Explain Bayes' theorem with an example.

Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
1749

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
1750

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
1751

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
1752

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
1753

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
1754

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
1755

What is PCA and when do you use it?

Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
1756

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
1757

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
1758

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
1759

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
1760

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
1761

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
1762

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
1763

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
1764

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
1765

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
1766

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
1767

Pandas: find the top 3 products by revenue in each region.

Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
1768

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
1769

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
1770

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
1771

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
1772

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
1773

What is cross-validation and why use it?

AppleEasy
Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
1774

What are *args and **kwargs?

AppleEasy
Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
1775

CNN vs RNN vs Transformer — what is the difference?

AppleHard
Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
1776

Why is XGBoost so popular?

AppleMedium
Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
1777

What is a RAG system and why use it?

AppleHard
Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
1778

What is batch normalisation?

AppleMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
1779

What is the Central Limit Theorem?

AppleMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
1780

What are precision and recall trade-offs in practice?

AppleMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
1781

What is the vanishing gradient problem?

AppleMedium
Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
1782

What is a confidence interval?

AppleMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
1783

How does a CNN work?

AppleMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
1784

What is sampling bias and how can you reduce it?

AppleMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
1785

Type I vs Type II error?

AppleEasy
Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
1786

How do you design an A/B test?

AppleHard
Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
1787

Random forest vs a single decision tree?

AppleMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
1788

What is standard deviation and what does it tell you?

AppleEasy
Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
1789

L1 vs L2 regularisation?

AppleMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
1790

What is gradient descent and what does the learning rate do?

AppleMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
1791

Explain the KNN algorithm and its drawbacks.

AppleMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
1792

How does the Gini impurity differ from entropy?

AppleMedium
Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
1793

What is the attention mechanism?

AppleMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
1794

How do you deal with high-cardinality categorical features?

AppleMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
1795

What is a generator and when would you use one?

AppleMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
1796

What is PCA and when do you use it?

AppleMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
1797

What is data leakage?

AppleEasy
Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
1798

What is a p-value?

AppleMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
1799

How does K-means clustering work and how do you choose k?

AppleMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
1800

Explain train, validation and test sets.

AppleEasy
Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
1801

How do you choose a learning rate for a neural network?

AppleMedium
Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
1802

How would you optimise a slow Pandas pipeline on a 5 GB file?

AppleHard
Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
1803

What is NumPy broadcasting?

AppleEasy
Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
1804

Design an end-to-end churn prediction system.

AppleHard
Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
1805

Pandas: find the top 3 products by revenue in each region.

AppleMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
1806

How do you handle imbalanced classes?

AppleMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
1807

What is the difference between bagging and boosting?

AppleEasy
Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
1808

What is the bias–variance trade-off?

AppleMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
1809

What is the difference between an epoch, a batch and an iteration?

AppleMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
1810

Explain ROC curve and AUC.

AppleMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
1811

What is TF-IDF?

AppleMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
1812

How do you detect outliers?

AppleMedium
Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
1813

What is regularization? Explain L1 vs L2.

AppleMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
1814

Explain Bayes' theorem with an example.

AppleMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
1815

How do you perform feature selection?

AppleMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
1816

Correlation vs covariance?

AppleEasy
Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
1817

What is the difference between parametric and non-parametric tests?

AppleMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
1818

Explain the chi-square test.

AppleMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
1819

Your dataset is highly imbalanced (2% positives). How do you handle it?

AppleMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
1820

What is tokenisation in NLP?

AppleEasy
Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
1821

What are common ways to evaluate NLP models?

AppleMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
1822

What are decorators in Python?

AppleMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
1823

How do you profile and speed up slow Python code?

AppleMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
1824

What is the difference between a set and a dictionary?

AppleEasy
Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
1825

What is the difference between apply, map and applymap in Pandas?

AppleMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
1826

Pandas: merge vs join vs concat?

AppleMedium
Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
1827

What is a confusion matrix?

AppleEasy
Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
1828

How do you tune hyperparameters?

AppleMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
1829

Explain the Law of Large Numbers.

AppleMedium
Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
1830

What are Python's main built-in data types?

AppleEasy
Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
1831

What is the difference between a function and a method?

AppleEasy
Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
1832

What is the Central Limit Theorem?

LinkedInMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
1833

What is correlation and why does it not imply causation?

LinkedInMedium
Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
1834

What is statistical power and how can you increase it?

LinkedInMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
1835

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
1836

How does dropout work?

LinkedInMedium
Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
1837

How does a decision tree decide where to split?

LinkedInMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
1838

Explain Bayes' theorem with an example.

LinkedInMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
1839

Explain ROC curve and AUC.

LinkedInMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
1840

Your dataset is highly imbalanced (2% positives). How do you handle it?

LinkedInMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
1841

What are precision and recall trade-offs in practice?

LinkedInMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
1842

Difference between a shallow copy and a deep copy?

LinkedInMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
1843

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
1844

What is the vanishing gradient problem?

LinkedInMedium
Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
1845

L1 vs L2 regularisation?

LinkedInMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
1846

What is the difference between iterators and iterables in Python?

LinkedInMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
1847

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
1848

What is the bias–variance trade-off?

LinkedInMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
1849

What is transfer learning?

LinkedInMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
1850

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
1851

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
1852

How do you handle imbalanced classes?

LinkedInMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
1853

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
1854

How do you deal with high-cardinality categorical features?

LinkedInMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
1855

Pandas: find the top 3 products by revenue in each region.

LinkedInMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
1856

How do you perform feature selection?

LinkedInMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
1857

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
1858

What is regularization? Explain L1 vs L2.

LinkedInMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
1859

What is the difference between apply, map and applymap in Pandas?

LinkedInMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
1860

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
1861

How does K-means clustering work and how do you choose k?

LinkedInMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
1862

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
1863

Random forest vs a single decision tree?

LinkedInMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
1864

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
1865

How do you tune hyperparameters?

LinkedInMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
1866

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
1867

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
1868

What is gradient descent and what does the learning rate do?

LinkedInMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
1869

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
1870

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
1871

What is a generator and when would you use one?

LinkedInMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
1872

What is PCA and when do you use it?

LinkedInMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
1873

What are decorators in Python?

LinkedInMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
1874

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
1875

How does linear regression work and what are its assumptions?

LinkedInMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
1876

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
1877

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
1878

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
1879

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
1880

What are lambda functions and where are they useful?

LinkedInMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
1881

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
1882

What is the Global Interpreter Lock (GIL)?

LinkedInMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
1883

What is sampling bias and how can you reduce it?

LinkedInMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
1884

How do you detect and treat concept drift?

LinkedInMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
1885

What are RNNs and why did LSTMs improve them?

LinkedInMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
1886

How do you detect outliers?

LinkedInMedium
Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
1887

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
1888

What is the difference between parametric and non-parametric tests?

LinkedInMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
1889

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
1890

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
1891

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
1892

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
1893

Why are NumPy arrays faster than Python lists?

LinkedInMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
1894

Explain logistic regression.

LinkedInMedium
Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
1895

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
1896

Random forest vs a single decision tree?

Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
1897

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
1898

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
1899

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
1900

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
1901

What is the difference between apply, map and applymap in Pandas?

Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
1902

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
1903

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
1904

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
1905

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
1906

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
1907

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
1908

Explain logistic regression.

Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
1909

Explain Bayes' theorem with an example.

Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
1910

What is feature scaling and which models need it?

Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
1911

What is a generator and when would you use one?

Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
1912

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
1913

What is backpropagation?

Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
1914

What are precision and recall trade-offs in practice?

Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
1915

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
1916

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
1917

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
1918

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
1919

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
1920

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
1921

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
1922

What is TF-IDF?

Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
1923

What is PCA and when do you use it?

Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
1924

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
1925

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
1926

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
1927

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
1928

How do you choose a learning rate for a neural network?

Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
1929

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
1930

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
1931

How does dropout work?

Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
1932

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
1933

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
1934

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
1935

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
1936

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
1937

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
1938

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
1939

What is the Central Limit Theorem?

Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
1940

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
1941

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
1942

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
1943

Why do we use activation functions? Why is ReLU popular?

Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
1944

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
1945

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
1946

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
1947

Explain ROC curve and AUC.

Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
1948

Explain ROC curve and AUC.

UberMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
1949

How do you detect outliers?

UberMedium
Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
1950

What is a generator and when would you use one?

UberMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
1951

What is a neural network?

UberEasy
Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
1952

What is the bias–variance trade-off?

UberMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
1953

What is a confusion matrix?

UberEasy
Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
1954

Explain p-value in simple words.

UberEasy
Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
1955

What is a Poisson distribution used for?

UberEasy
Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
1956

What are lambda functions and where are they useful?

UberMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
1957

What is the difference between a set and a dictionary?

UberEasy
Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
1958

Why are NumPy arrays faster than Python lists?

UberMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
1959

What is overfitting and how do you prevent it?

UberEasy
Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
1960

Write a function to calculate RMSE without any library.

UberEasy
Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
1961

What are Python's main built-in data types?

UberEasy
Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
1962

How do you handle missing values?

UberEasy
Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
1963

What is cross-validation and why use it?

UberEasy
Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
1964

What is PCA and when do you use it?

UberMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
1965

What is the difference between apply, map and applymap in Pandas?

UberMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
1966

What is feature scaling and which models need it?

UberMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
1967

Pearson vs Spearman correlation?

UberEasy
Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
1968

Which activation functions do you know and when to use them?

UberMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
1969

What is transfer learning?

UberMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
1970

How do you remove duplicates from a DataFrame?

UberEasy
Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
1971

How do you choose a learning rate for a neural network?

UberMedium
Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
1972

How does K-means clustering work and how do you choose k?

UberMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
1973

What is the Global Interpreter Lock (GIL)?

UberMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
1974

Random forest vs a single decision tree?

UberMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
1975

How do transformers differ from RNNs?

UberHard
Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
1976

What is TF-IDF?

UberMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
1977

How does linear regression work and what are its assumptions?

UberMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
1978

How do list comprehensions work and why use them?

UberEasy
Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
1979

What is regularization? Explain L1 vs L2.

UberMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
1980

How do you design an A/B test?

UberHard
Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
1981

How do you deal with high-cardinality categorical features?

UberMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
1982

How would you build a churn prediction model end to end?

UberHard
Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
1983

Design an end-to-end churn prediction system.

UberHard
Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
1984

What is the difference between iterators and iterables in Python?

UberMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
1985

What is gradient descent and what does the learning rate do?

UberMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
1986

What is statistical power and how can you increase it?

UberMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
1987

How does a CNN work?

Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
1988

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
1989

What is the Central Limit Theorem?

Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
1990

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
1991

How does dropout work?

Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
1992

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
1993

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
1994

What is PCA and when do you use it?

Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
1995

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
1996

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
1997

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
1998

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
1999

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
2000

Explain ROC curve and AUC.

Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
2001

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
2002

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
2003

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
2004

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
2005

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2006

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
2007

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
2008

What is feature scaling and which models need it?

Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
2009

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
2010

What is an autoencoder and what is it used for?

Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
2011

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
2012

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
2013

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
2014

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
2015

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
2016

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
2017

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
2018

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
2019

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
2020

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
2021

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
2022

What is sampling bias and how can you reduce it?

Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
2023

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
2024

Why do we use activation functions? Why is ReLU popular?

Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
2025

Explain the Law of Large Numbers.

Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
2026

How do you pivot data in Pandas?

Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
2027

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
2028

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
2029

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
2030

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
2031

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
2032

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
2033

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
2034

How does K-means clustering work and how do you choose k?

Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
2035

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
2036

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
2037

What is TF-IDF?

Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
2038

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
2039

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
2040

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
2041

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
2042

Explain the chi-square test.

Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
2043

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
2044

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
2045

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
2046

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
2047

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
2048

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
2049

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
2050

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2051

What is the bias–variance trade-off?

Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
2052

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
2053

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
2054

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
2055

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
2056

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
2057

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
2058

Explain the KNN algorithm and its drawbacks.

Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
2059

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
2060

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
2061

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
2062

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
2063

How does dropout work?

Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
2064

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
2065

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
2066

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
2067

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
2068

Explain logistic regression.

Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
2069

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
2070

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
2071

Explain the chi-square test.

Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
2072

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
2073

What is feature scaling and which models need it?

Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
2074

How does K-means clustering work and how do you choose k?

Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
2075

What is the difference between iterators and iterables in Python?

Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
2076

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
2077

Explain Bayes' theorem with an example.

Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
2078

How do you choose a learning rate for a neural network?

Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
2079

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
2080

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
2081

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
2082

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
2083

What is the difference between apply, map and applymap in Pandas?

Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
2084

How do you detect and treat concept drift?

Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
2085

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
2086

Explain the Law of Large Numbers.

Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
2087

Explain ROC curve and AUC.

Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
2088

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
2089

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
2090

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
2091

What is an autoencoder and what is it used for?

Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
2092

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
2093

Random forest vs a single decision tree?

Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
2094

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
2095

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
2096

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
2097

What is PCA and when do you use it?

Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
2098

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
2099

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
2100

How do you choose a learning rate for a neural network?

Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
2101

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
2102

What is the difference between apply, map and applymap in Pandas?

Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
2103

What is TF-IDF?

Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
2104

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
2105

How does a CNN work?

Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
2106

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
2107

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
2108

Explain the chi-square test.

Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
2109

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
2110

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
2111

What is transfer learning?

Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
2112

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
2113

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
2114

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
2115

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
2116

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
2117

What is feature scaling and which models need it?

Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
2118

Explain the Law of Large Numbers.

Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
2119

Why do we use activation functions? Why is ReLU popular?

Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
2120

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
2121

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
2122

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
2123

Explain Bayes' theorem with an example.

Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
2124

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
2125

What is the Central Limit Theorem?

Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
2126

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
2127

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
2128

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
2129

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
2130

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
2131

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
2132

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
2133

How do you pivot data in Pandas?

Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
2134

How do you detect and treat concept drift?

Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
2135

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
2136

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
2137

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
2138

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
2139

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
2140

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
2141

Explain logistic regression.

Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
2142

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
2143

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2144

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
2145

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
2146

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
2147

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
2148

What are precision and recall trade-offs in practice?

Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
2149

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
2150

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
2151

How does dropout work?

Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
2152

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
2153

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
2154

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
2155

What is the attention mechanism?

Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
2156

What is gradient descent and what does the learning rate do?

StripeMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
2157

What is backpropagation?

StripeMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
2158

How does a CNN work?

StripeMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
2159

What is feature scaling and which models need it?

StripeMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
2160

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
2161

What is regularization? Explain L1 vs L2.

StripeMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
2162

What is PCA and when do you use it?

StripeMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
2163

What is a confidence interval?

StripeMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
2164

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
2165

How do you perform feature selection?

StripeMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
2166

Explain the KNN algorithm and its drawbacks.

StripeMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
2167

How do you pivot data in Pandas?

StripeMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
2168

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
2169

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
2170

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
2171

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
2172

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
2173

Pandas: find the top 3 products by revenue in each region.

StripeMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
2174

How do you detect and treat concept drift?

StripeMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
2175

What is statistical power and how can you increase it?

StripeMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
2176

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
2177

What is an autoencoder and what is it used for?

StripeMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
2178

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
2179

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
2180

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
2181

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
2182

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
2183

What is a generator and when would you use one?

StripeMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
2184

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
2185

Why are NumPy arrays faster than Python lists?

StripeMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
2186

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
2187

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
2188

How do you handle imbalanced classes?

StripeMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
2189

What is the difference between iterators and iterables in Python?

StripeMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
2190

Explain Bayes' theorem with an example.

StripeMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
2191

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
2192

How do you tune hyperparameters?

StripeMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
2193

Random forest vs a single decision tree?

StripeMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
2194

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
2195

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
2196

What is batch normalisation?

StripeMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
2197

What is calibration of a classifier?

StripeMedium
Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
2198

What is a p-value?

StripeMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
2199

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
2200

How do you choose a learning rate for a neural network?

StripeMedium
Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
2201

Explain ROC curve and AUC.

PayPalMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
2202

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
2203

How do you pivot data in Pandas?

PayPalMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
2204

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
2205

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
2206

What are decorators in Python?

PayPalMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
2207

Pandas: find the top 3 products by revenue in each region.

PayPalMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
2208

How do you handle imbalanced classes?

PayPalMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
2209

Why are NumPy arrays faster than Python lists?

PayPalMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
2210

Which activation functions do you know and when to use them?

PayPalMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2211

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
2212

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
2213

What are common ways to evaluate NLP models?

PayPalMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
2214

What is backpropagation?

PayPalMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
2215

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
2216

Explain the Law of Large Numbers.

PayPalMedium
Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
2217

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
2218

Explain Bayes' theorem with an example.

PayPalMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
2219

What is batch normalisation?

PayPalMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
2220

What is transfer learning?

PayPalMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
2221

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
2222

What is Naive Bayes and why is it called naive?

PayPalMedium
Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
2223

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
2224

What is the attention mechanism?

PayPalMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
2225

How do you detect and treat concept drift?

PayPalMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
2226

What is the Global Interpreter Lock (GIL)?

PayPalMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
2227

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
2228

What is the vanishing gradient problem?

PayPalMedium
Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
2229

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
2230

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
2231

What is feature scaling and which models need it?

PayPalMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
2232

How does a decision tree decide where to split?

PayPalMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
2233

What is stacking in ensemble learning?

PayPalMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
2234

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
2235

Difference between a shallow copy and a deep copy?

PayPalMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
2236

How do you use groupby with multiple aggregations?

PayPalMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
2237

Explain the KNN algorithm and its drawbacks.

PayPalMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
2238

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
2239

How do you tune hyperparameters?

PayPalMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
2240

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2241

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
2242

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
2243

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
2244

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
2245

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
2246

How do you detect and treat concept drift?

Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
2247

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
2248

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
2249

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
2250

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
2251

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
2252

What is TF-IDF?

Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
2253

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
2254

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
2255

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
2256

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
2257

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
2258

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
2259

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
2260

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
2261

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
2262

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
2263

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
2264

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
2265

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
2266

What is sampling bias and how can you reduce it?

Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
2267

How does dropout work?

Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
2268

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
2269

How do you deal with high-cardinality categorical features?

Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
2270

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
2271

What is PCA and when do you use it?

Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
2272

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
2273

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
2274

What is the bias–variance trade-off?

Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
2275

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
2276

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
2277

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
2278

Random forest vs a single decision tree?

Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
2279

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
2280

What is an autoencoder and what is it used for?

Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
2281

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
2282

What is feature scaling and which models need it?

Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
2283

How do you pivot data in Pandas?

Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
2284

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
2285

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
2286

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
2287

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
2288

Explain ROC curve and AUC.

Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
2289

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
2290

What is the difference between apply, map and applymap in Pandas?

Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
2291

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
2292

What is a generator and when would you use one?

Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
2293

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
2294

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
2295

What is backpropagation?

Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
2296

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
2297

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
2298

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
2299

Explain the chi-square test.

Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
2300

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
2301

Why is XGBoost so popular?

Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
2302

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
2303

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
2304

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
2305

What is a RAG system and why use it?

AdobeHard
Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
2306

Your dataset is highly imbalanced (2% positives). How do you handle it?

AdobeMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
2307

Pandas: find the top 3 products by revenue in each region.

AdobeMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
2308

What is multicollinearity and how do you handle it?

AdobeHard
Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
2309

How do you deploy and monitor a machine learning model?

AdobeHard
Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
2310

What are common ways to evaluate NLP models?

AdobeMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
2311

What is the difference between iterators and iterables in Python?

AdobeMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
2312

How do you handle missing values?

AdobeEasy
Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
2313

What is the difference between apply, map and applymap in Pandas?

AdobeMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
2314

How do you perform feature selection?

AdobeMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
2315

How do list comprehensions work and why use them?

AdobeEasy
Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
2316

What is tokenisation in NLP?

AdobeEasy
Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
2317

How would you fine-tune a pretrained language model for classification?

AdobeHard
Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
2318

What is NumPy broadcasting?

AdobeEasy
Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
2319

How does linear regression work and what are its assumptions?

AdobeMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
2320

What is the difference between == and is?

AdobeEasy
Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
2321

What is stacking in ensemble learning?

AdobeMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
2322

What is sampling bias and how can you reduce it?

AdobeMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
2323

What is skewness?

AdobeEasy
Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
2324

What is an autoencoder and what is it used for?

AdobeMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
2325

How do you deal with high-cardinality categorical features?

AdobeMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
2326

Explain ROC curve and AUC.

AdobeMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
2327

Why is XGBoost so popular?

AdobeMedium
Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
2328

What is a generator and when would you use one?

AdobeMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
2329

What is a normal distribution?

AdobeEasy
Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
2330

How do you pivot data in Pandas?

AdobeMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
2331

What is the bias–variance trade-off?

AdobeMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
2332

Difference between loc and iloc in Pandas?

AdobeEasy
Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
2333

What is overfitting and how do you prevent it?

AdobeEasy
Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
2334

What are lambda functions and where are they useful?

AdobeMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
2335

How do you use groupby with multiple aggregations?

AdobeMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
2336

What is the Global Interpreter Lock (GIL)?

AdobeMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
2337

What is regularization? Explain L1 vs L2.

AdobeMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
2338

Pearson vs Spearman correlation?

AdobeEasy
Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
2339

Which activation functions do you know and when to use them?

AdobeMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2340

What is the difference between generative and discriminative models?

AdobeHard
Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
2341

What is the attention mechanism?

AdobeMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
2342

CNN vs RNN vs Transformer — what is the difference?

AdobeHard
Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
2343

What is backpropagation?

AdobeMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
2344

What are Python's main built-in data types?

AdobeEasy
Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
2345

What are RNNs and why did LSTMs improve them?

AdobeMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
2346

What is the difference between mean, median and mode?

AdobeEasy
Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
2347

How does a CNN work?

AdobeMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
2348

How do you tune hyperparameters?

AdobeMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
2349

What is cross-validation and why use it?

AdobeEasy
Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
2350

How do you design an A/B test?

AdobeHard
Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
2351

What is data leakage?

AdobeEasy
Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
2352

What is the difference between Bayesian and frequentist approaches?

AdobeHard
Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
2353

What is correlation and why does it not imply causation?

AdobeMedium
Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
2354

Train accuracy is 95% but test accuracy is 70%. What do you do?

AdobeHard
Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
2355

How does K-means clustering work and how do you choose k?

AdobeMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
2356

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
2357

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
2358

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
2359

How does dropout work?

FlipkartMedium
Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
2360

Random forest vs a single decision tree?

FlipkartMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
2361

Explain the chi-square test.

FlipkartMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
2362

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
2363

What is transfer learning?

FlipkartMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
2364

L1 vs L2 regularisation?

FlipkartMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
2365

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
2366

What is the vanishing gradient problem?

FlipkartMedium
Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
2367

What is stacking in ensemble learning?

FlipkartMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
2368

What is the Central Limit Theorem?

FlipkartMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
2369

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
2370

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
2371

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
2372

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
2373

What is statistical power and how can you increase it?

FlipkartMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
2374

What is gradient descent and what does the learning rate do?

FlipkartMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
2375

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
2376

What is feature scaling and which models need it?

FlipkartMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
2377

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
2378

What is backpropagation?

FlipkartMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
2379

How does linear regression work and what are its assumptions?

FlipkartMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
2380

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
2381

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
2382

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
2383

Explain the KNN algorithm and its drawbacks.

FlipkartMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
2384

Pandas: merge vs join vs concat?

FlipkartMedium
Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
2385

What is the Global Interpreter Lock (GIL)?

FlipkartMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
2386

What is the attention mechanism?

FlipkartMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
2387

What is Naive Bayes and why is it called naive?

FlipkartMedium
Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
2388

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
2389

What is a confidence interval?

FlipkartMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
2390

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
2391

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
2392

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
2393

What is the difference between an epoch, a batch and an iteration?

FlipkartMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
2394

Explain ROC curve and AUC.

FlipkartMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
2395

How do you tune hyperparameters?

FlipkartMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
2396

How do you perform feature selection?

FlipkartMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
2397

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
2398

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
2399

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
2400

What is a p-value?

FlipkartMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
2401

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
2402

What is calibration of a classifier?

FlipkartMedium
Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
2403

What is the difference between parametric and non-parametric tests?

FlipkartMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
2404

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
2405

Explain logistic regression.

FlipkartMedium
Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
2406

Your dataset is highly imbalanced (2% positives). How do you handle it?

FlipkartMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
2407

Why do we use activation functions? Why is ReLU popular?

FlipkartMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
2408

How does a decision tree decide where to split?

FlipkartMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
2409

How does K-means clustering work and how do you choose k?

FlipkartMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
2410

What are precision and recall trade-offs in practice?

FlipkartMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
2411

What is the difference between apply, map and applymap in Pandas?

FlipkartMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
2412

Why are NumPy arrays faster than Python lists?

FlipkartMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
2413

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
2414

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
2415

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
2416

What is correlation and why does it not imply causation?

FlipkartMedium
Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
2417

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
2418

How do you pivot data in Pandas?

FlipkartMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
2419

How do you profile and speed up slow Python code?

FlipkartMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
2420

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
2421

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
2422

What is the difference between iterators and iterables in Python?

FlipkartMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
2423

What are RNNs and why did LSTMs improve them?

FlipkartMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
2424

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
2425

What is sampling bias and how can you reduce it?

FlipkartMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
2426

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
2427

Difference between a shallow copy and a deep copy?

FlipkartMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
2428

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
2429

What are decorators in Python?

FlipkartMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
2430

What is regularization? Explain L1 vs L2.

FlipkartMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
2431

What is an autoencoder and what is it used for?

FlipkartMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
2432

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
2433

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
2434

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
2435

How do you handle imbalanced classes?

FlipkartMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
2436

How do you tune hyperparameters?

PhonePeMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
2437

What is an autoencoder and what is it used for?

PhonePeMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
2438

How do you handle imbalanced classes?

PhonePeMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
2439

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
2440

What is the bias–variance trade-off?

PhonePeMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
2441

How do you profile and speed up slow Python code?

PhonePeMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
2442

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
2443

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
2444

What is feature scaling and which models need it?

PhonePeMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
2445

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
2446

What is stacking in ensemble learning?

PhonePeMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
2447

Explain Bayes' theorem with an example.

PhonePeMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
2448

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
2449

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
2450

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
2451

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
2452

How does linear regression work and what are its assumptions?

PhonePeMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
2453

What is SVM and the kernel trick?

PhonePeMedium
Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
2454

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
2455

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
2456

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
2457

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
2458

What is a generator and when would you use one?

PhonePeMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
2459

Why do we use activation functions? Why is ReLU popular?

PhonePeMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
2460

Your dataset is highly imbalanced (2% positives). How do you handle it?

PhonePeMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
2461

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
2462

How do you pivot data in Pandas?

PhonePeMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
2463

Explain the KNN algorithm and its drawbacks.

PhonePeMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
2464

What is regularization? Explain L1 vs L2.

PhonePeMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
2465

Why are NumPy arrays faster than Python lists?

PhonePeMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
2466

Explain the Law of Large Numbers.

PhonePeMedium
Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
2467

What is transfer learning?

PhonePeMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
2468

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
2469

What are RNNs and why did LSTMs improve them?

PhonePeMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
2470

Which activation functions do you know and when to use them?

PhonePeMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2471

How does K-means clustering work and how do you choose k?

PhonePeMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
2472

What are precision and recall trade-offs in practice?

PhonePeMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
2473

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
2474

What is the difference between an epoch, a batch and an iteration?

PhonePeMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
2475

How do you use groupby with multiple aggregations?

PhonePeMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
2476

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
2477

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
2478

What is backpropagation?

PhonePeMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
2479

Pandas: find the top 3 products by revenue in each region.

PhonePeMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
2480

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
2481

How does a CNN work?

PhonePeMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
2482

What is Naive Bayes and why is it called naive?

PhonePeMedium
Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
2483

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
2484

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
2485

What is the Global Interpreter Lock (GIL)?

PhonePeMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
2486

What is the Central Limit Theorem?

PhonePeMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
2487

Explain ROC curve and AUC.

PhonePeMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
2488

Difference between a shallow copy and a deep copy?

PhonePeMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
2489

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
2490

What is statistical power and how can you increase it?

PhonePeMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
2491

What is the attention mechanism?

PhonePeMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
2492

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
2493

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
2494

What is gradient descent and what does the learning rate do?

MeeshoMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
2495

What is the difference between an epoch, a batch and an iteration?

MeeshoMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
2496

How do you profile and speed up slow Python code?

MeeshoMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
2497

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
2498

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
2499

What is the difference between parametric and non-parametric tests?

MeeshoMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
2500

What is sampling bias and how can you reduce it?

MeeshoMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
2501

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
2502

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
2503

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
2504

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
2505

What is backpropagation?

MeeshoMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
2506

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
2507

How does a decision tree decide where to split?

MeeshoMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
2508

Explain the KNN algorithm and its drawbacks.

MeeshoMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
2509

What is regularization? Explain L1 vs L2.

MeeshoMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
2510

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
2511

Explain logistic regression.

MeeshoMedium
Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
2512

Difference between a shallow copy and a deep copy?

MeeshoMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
2513

What is PCA and when do you use it?

MeeshoMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
2514

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
2515

How do you detect outliers?

MeeshoMedium
Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
2516

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
2517

What is the attention mechanism?

MeeshoMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
2518

Why are NumPy arrays faster than Python lists?

MeeshoMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
2519

What is TF-IDF?

MeeshoMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
2520

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
2521

What is a confidence interval?

MeeshoMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
2522

What are common ways to evaluate NLP models?

MeeshoMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
2523

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
2524

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
2525

How do you use groupby with multiple aggregations?

MeeshoMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
2526

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
2527

What is batch normalisation?

MeeshoMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
2528

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
2529

How do you deal with high-cardinality categorical features?

MeeshoMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
2530

What is transfer learning?

MeeshoMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
2531

What are lambda functions and where are they useful?

MeeshoMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
2532

How does the Gini impurity differ from entropy?

MeeshoMedium
Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
2533

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
2534

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
2535

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
2536

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
2537

What is the Global Interpreter Lock (GIL)?

MeeshoMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
2538

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
2539

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
2540

Explain ROC curve and AUC.

MeeshoMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
2541

What are RNNs and why did LSTMs improve them?

MeeshoMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
2542

Pandas: merge vs join vs concat?

MeeshoMedium
Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
2543

What is the difference between apply, map and applymap in Pandas?

MeeshoMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
2544

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
2545

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
2546

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
2547

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
2548

What is SVM and the kernel trick?

MeeshoMedium
Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
2549

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
2550

What is feature scaling and which models need it?

MeeshoMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
2551

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
2552

Explain the chi-square test.

MeeshoMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
2553

How does dropout work?

MeeshoMedium
Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
2554

How does a CNN work?

MeeshoMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
2555

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
2556

L1 vs L2 regularisation?

MeeshoMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
2557

Your dataset is highly imbalanced (2% positives). How do you handle it?

MeeshoMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
2558

How do you handle imbalanced classes?

MeeshoMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
2559

How do you pivot data in Pandas?

MeeshoMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
2560

Which activation functions do you know and when to use them?

MeeshoMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2561

How do you choose a learning rate for a neural network?

MeeshoMedium
Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
2562

What is the Central Limit Theorem?

MeeshoMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
2563

What is an autoencoder and what is it used for?

MeeshoMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
2564

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
2565

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
2566

How do you tune hyperparameters?

MeeshoMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
2567

What is TF-IDF?

CREDMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
2568

What are Python's main built-in data types?

CREDEasy
Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
2569

What is the difference between a set and a dictionary?

CREDEasy
Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
2570

Explain Bayes' theorem with an example.

CREDMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
2571

What is the Central Limit Theorem?

CREDMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
2572

Pandas: merge vs join vs concat?

CREDMedium
Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
2573

What is the difference between mean, median and mode?

CREDEasy
Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
2574

What are RNNs and why did LSTMs improve them?

CREDMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
2575

What is SVM and the kernel trick?

CREDMedium
Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
2576

What is a confidence interval?

CREDMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
2577

What is overfitting and how do you prevent it?

CREDEasy
Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
2578

What is gradient descent and what does the learning rate do?

CREDMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
2579

What is the difference between iterators and iterables in Python?

CREDMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
2580

What is tokenisation in NLP?

CREDEasy
Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
2581

What is the difference between Bayesian and frequentist approaches?

CREDHard
Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
2582

How do you evaluate and explain a model to business stakeholders?

CREDHard
Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
2583

Why do we use activation functions? Why is ReLU popular?

CREDMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
2584

What is an autoencoder and what is it used for?

CREDMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
2585

What is the difference between a function and a method?

CREDEasy
Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
2586

What are precision and recall trade-offs in practice?

CREDMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
2587

What is standard deviation and what does it tell you?

CREDEasy
Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
2588

Difference between loc and iloc in Pandas?

CREDEasy
Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
2589

Design an end-to-end churn prediction system.

CREDHard
Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
2590

What is the attention mechanism?

CREDMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
2591

What are common ways to evaluate NLP models?

CREDMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
2592

How do you handle missing values?

CREDEasy
Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
2593

Which activation functions do you know and when to use them?

CREDMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2594

What is a normal distribution?

CREDEasy
Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
2595

What is skewness?

CREDEasy
Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
2596

What is backpropagation?

CREDMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
2597

How do you design an A/B test?

CREDHard
Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
2598

What is PCA and when do you use it?

CREDMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
2599

What is sampling bias and how can you reduce it?

CREDMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
2600

How do you use groupby with multiple aggregations?

CREDMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
2601

What is statistical power and how can you increase it?

CREDMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
2602

How do you handle imbalanced classes?

CREDMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
2603

What is transfer learning?

CREDMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
2604

What is the difference between regression and classification?

CREDEasy
Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
2605

CNN vs RNN vs Transformer — what is the difference?

CREDHard
Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
2606

What is calibration of a classifier?

CREDMedium
Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
2607

How do you deal with high-cardinality categorical features?

CREDMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
2608

What is NumPy broadcasting?

CREDEasy
Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
2609

Pearson vs Spearman correlation?

CREDEasy
Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
2610

Pandas: find the top 3 products by revenue in each region.

CREDMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
2611

Why are NumPy arrays faster than Python lists?

CREDMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
2612

Random forest vs a single decision tree?

CREDMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
2613

Correlation vs covariance?

CREDEasy
Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
2614

What is correlation and why does it not imply causation?

CREDMedium
Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
2615

Type I vs Type II error?

CREDEasy
Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
2616

What is a RAG system and why use it?

CREDHard
Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
2617

What is the difference between parametric and non-parametric tests?

CREDMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
2618

Explain the Law of Large Numbers.

CREDMedium
Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
2619

What is batch normalisation?

CREDMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
2620

Explain p-value in simple words.

CREDEasy
Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
2621

Why are NumPy arrays faster than Python lists?

RazorpayMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
2622

What is TF-IDF?

RazorpayMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
2623

Difference between a shallow copy and a deep copy?

RazorpayMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
2624

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
2625

What is a confidence interval?

RazorpayMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
2626

What is Naive Bayes and why is it called naive?

RazorpayMedium
Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
2627

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
2628

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
2629

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
2630

How do you use groupby with multiple aggregations?

RazorpayMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
2631

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
2632

How does dropout work?

RazorpayMedium
Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
2633

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
2634

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
2635

What are lambda functions and where are they useful?

RazorpayMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
2636

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
2637

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
2638

What is SVM and the kernel trick?

RazorpayMedium
Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
2639

How do you detect and treat concept drift?

RazorpayMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
2640

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
2641

How does the Gini impurity differ from entropy?

RazorpayMedium
Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
2642

How do you pivot data in Pandas?

RazorpayMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
2643

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
2644

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
2645

How does a CNN work?

RazorpayMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
2646

Explain Bayes' theorem with an example.

RazorpayMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
2647

What are RNNs and why did LSTMs improve them?

RazorpayMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
2648

How do you handle imbalanced classes?

RazorpayMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
2649

Your dataset is highly imbalanced (2% positives). How do you handle it?

RazorpayMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
2650

What is the Central Limit Theorem?

RazorpayMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
2651

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
2652

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
2653

What is the vanishing gradient problem?

RazorpayMedium
Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
2654

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
2655

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
2656

What is the bias–variance trade-off?

RazorpayMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
2657

What is the Global Interpreter Lock (GIL)?

RazorpayMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
2658

What is batch normalisation?

RazorpayMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
2659

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
2660

What is the difference between apply, map and applymap in Pandas?

RazorpayMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
2661

What is the difference between parametric and non-parametric tests?

RazorpayMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
2662

What is the difference between an epoch, a batch and an iteration?

RazorpayMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
2663

What is gradient descent and what does the learning rate do?

RazorpayMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
2664

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
2665

What is an autoencoder and what is it used for?

RazorpayMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
2666

How do you perform feature selection?

RazorpayMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
2667

How do you choose a learning rate for a neural network?

RazorpayMedium
Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
2668

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
2669

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
2670

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
2671

Which activation functions do you know and when to use them?

RazorpayMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2672

How do you deal with high-cardinality categorical features?

ZomatoMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
2673

What is the Global Interpreter Lock (GIL)?

ZomatoMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
2674

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
2675

What are lambda functions and where are they useful?

ZomatoMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
2676

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
2677

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
2678

How do you perform feature selection?

ZomatoMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
2679

How does a CNN work?

ZomatoMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
2680

Explain Bayes' theorem with an example.

ZomatoMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
2681

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
2682

Random forest vs a single decision tree?

ZomatoMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
2683

Which activation functions do you know and when to use them?

ZomatoMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2684

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
2685

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
2686

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
2687

How do you tune hyperparameters?

ZomatoMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
2688

How does a decision tree decide where to split?

ZomatoMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
2689

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
2690

What is the difference between iterators and iterables in Python?

ZomatoMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
2691

Why are NumPy arrays faster than Python lists?

ZomatoMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
2692

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
2693

Explain the Law of Large Numbers.

ZomatoMedium
Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
2694

What is correlation and why does it not imply causation?

ZomatoMedium
Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
2695

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
2696

What is batch normalisation?

ZomatoMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
2697

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
2698

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
2699

Explain logistic regression.

ZomatoMedium
Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
2700

What is the difference between an epoch, a batch and an iteration?

ZomatoMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
2701

What are precision and recall trade-offs in practice?

ZomatoMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
2702

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
2703

How do you handle imbalanced classes?

ZomatoMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
2704

How does K-means clustering work and how do you choose k?

ZomatoMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
2705

What is an autoencoder and what is it used for?

ZomatoMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
2706

Pandas: find the top 3 products by revenue in each region.

ZomatoMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
2707

What is backpropagation?

ZomatoMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
2708

What is a p-value?

ZomatoMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
2709

Explain the KNN algorithm and its drawbacks.

ZomatoMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
2710

Explain the chi-square test.

ZomatoMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
2711

What is the vanishing gradient problem?

ZomatoMedium
Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
2712

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
2713

What is stacking in ensemble learning?

ZomatoMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
2714

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
2715

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
2716

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
2717

Pandas: merge vs join vs concat?

ZomatoMedium
Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
2718

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
2719

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
2720

Pandas: merge vs join vs concat?

SwiggyMedium
Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
2721

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
2722

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
2723

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
2724

What is SVM and the kernel trick?

SwiggyMedium
Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
2725

How does a CNN work?

SwiggyMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
2726

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
2727

What is the Global Interpreter Lock (GIL)?

SwiggyMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
2728

What is statistical power and how can you increase it?

SwiggyMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
2729

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
2730

Explain the KNN algorithm and its drawbacks.

SwiggyMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
2731

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
2732

What is the difference between an epoch, a batch and an iteration?

SwiggyMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
2733

What is calibration of a classifier?

SwiggyMedium
Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
2734

What is the bias–variance trade-off?

SwiggyMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
2735

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
2736

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
2737

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
2738

Which activation functions do you know and when to use them?

SwiggyMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2739

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
2740

What is the Central Limit Theorem?

SwiggyMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
2741

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
2742

Difference between a shallow copy and a deep copy?

SwiggyMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
2743

What is the difference between apply, map and applymap in Pandas?

SwiggyMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
2744

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
2745

What is sampling bias and how can you reduce it?

SwiggyMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
2746

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
2747

How do you detect outliers?

SwiggyMedium
Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
2748

What are common ways to evaluate NLP models?

SwiggyMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
2749

Why do we use activation functions? Why is ReLU popular?

SwiggyMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
2750

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
2751

What is transfer learning?

SwiggyMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
2752

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
2753

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
2754

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
2755

What is backpropagation?

SwiggyMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
2756

What is a confidence interval?

SwiggyMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
2757

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
2758

Explain the chi-square test.

SwiggyMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
2759

How do you perform feature selection?

SwiggyMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
2760

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
2761

Why is XGBoost so popular?

SwiggyMedium
Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
2762

What is the attention mechanism?

SwiggyMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
2763

How do you pivot data in Pandas?

SwiggyMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
2764

What is regularization? Explain L1 vs L2.

SwiggyMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
2765

What is a normal distribution?

ZeptoEasy
Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
2766

What is feature scaling and which models need it?

ZeptoMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
2767

What is multicollinearity and how do you handle it?

ZeptoHard
Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
2768

What is the difference between apply, map and applymap in Pandas?

ZeptoMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
2769

Which activation functions do you know and when to use them?

ZeptoMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2770

How do you use groupby with multiple aggregations?

ZeptoMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
2771

What is a generator and when would you use one?

ZeptoMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
2772

What is an autoencoder and what is it used for?

ZeptoMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
2773

How do you profile and speed up slow Python code?

ZeptoMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
2774

Why is XGBoost so popular?

ZeptoMedium
Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
2775

How do you design an A/B test?

ZeptoHard
Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
2776

What is TF-IDF?

ZeptoMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
2777

What is skewness?

ZeptoEasy
Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
2778

Explain the Law of Large Numbers.

ZeptoMedium
Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
2779

How do transformers differ from RNNs?

ZeptoHard
Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
2780

Design an end-to-end churn prediction system.

ZeptoHard
Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
2781

What is correlation and why does it not imply causation?

ZeptoMedium
Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
2782

How do you tune hyperparameters?

ZeptoMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
2783

What is gradient descent and what does the learning rate do?

ZeptoMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
2784

What is the Central Limit Theorem?

ZeptoMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
2785

What is the difference between == and is?

ZeptoEasy
Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
2786

Explain p-value in simple words.

ZeptoEasy
Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
2787

Explain ROC curve and AUC.

ZeptoMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
2788

What is tokenisation in NLP?

ZeptoEasy
Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
2789

Why do we use activation functions? Why is ReLU popular?

ZeptoMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
2790

What is the bias–variance trade-off?

ZeptoMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
2791

Difference between a shallow copy and a deep copy?

ZeptoMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
2792

What is the difference between parametric and non-parametric tests?

ZeptoMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
2793

What is the difference between mean, median and mode?

ZeptoEasy
Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
2794

Type I vs Type II error?

ZeptoEasy
Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
2795

How do list comprehensions work and why use them?

ZeptoEasy
Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
2796

What is the difference between list, tuple, set and dict in Python?

ZeptoEasy
Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
2797

What are lambda functions and where are they useful?

ZeptoMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
2798

What is the difference between an epoch, a batch and an iteration?

ZeptoMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
2799

What is backpropagation?

ZeptoMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
2800

What are precision and recall trade-offs in practice?

ZeptoMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
2801

What are decorators in Python?

ZeptoMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
2802

What is regularization? Explain L1 vs L2.

ZeptoMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
2803

What is the difference between generative and discriminative models?

ZeptoHard
Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
2804

Random forest vs a single decision tree?

ZeptoMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
2805

What is the difference between bagging and boosting?

ZeptoEasy
Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
2806

Train accuracy is 95% but test accuracy is 70%. What do you do?

ZeptoHard
Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
2807

How do you detect outliers?

ZeptoMedium
Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
2808

What is the difference between an epoch, a batch and an iteration?

PaytmMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
2809

How does the Gini impurity differ from entropy?

PaytmMedium
Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
2810

What is calibration of a classifier?

PaytmMedium
Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
2811

How do you remove duplicates from a DataFrame?

PaytmEasy
Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
2812

Explain the Law of Large Numbers.

PaytmMedium
Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
2813

How do you handle imbalanced classes?

PaytmMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
2814

What is PCA and when do you use it?

PaytmMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
2815

Pandas: merge vs join vs concat?

PaytmMedium
Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
2816

Pearson vs Spearman correlation?

PaytmEasy
Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
2817

What are lambda functions and where are they useful?

PaytmMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
2818

How do you tune hyperparameters?

PaytmMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
2819

Type I vs Type II error?

PaytmEasy
Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
2820

What is stacking in ensemble learning?

PaytmMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
2821

What is the Global Interpreter Lock (GIL)?

PaytmMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
2822

What is the vanishing gradient problem?

PaytmMedium
Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
2823

What is the difference between regression and classification?

PaytmEasy
Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
2824

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
2825

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
2826

How do you profile and speed up slow Python code?

Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
2827

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
2828

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
2829

What is PCA and when do you use it?

Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
2830

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
2831

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
2832

Why is XGBoost so popular?

Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
2833

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
2834

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
2835

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
2836

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
2837

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
2838

How does a CNN work?

Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
2839

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
2840

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
2841

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
2842

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
2843

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
2844

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
2845

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
2846

Random forest vs a single decision tree?

Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
2847

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
2848

What is sampling bias and how can you reduce it?

Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
2849

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
2850

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
2851

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
2852

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
2853

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
2854

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
2855

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
2856

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2857

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
2858

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
2859

What is TF-IDF?

Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
2860

How do you detect and treat concept drift?

Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
2861

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
2862

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
2863

How do you detect and treat concept drift?

IntuitMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
2864

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
2865

What is the difference between apply, map and applymap in Pandas?

IntuitMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
2866

How does a CNN work?

IntuitMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
2867

What is SVM and the kernel trick?

IntuitMedium
Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
2868

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
2869

What is TF-IDF?

IntuitMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
2870

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
2871

How does K-means clustering work and how do you choose k?

IntuitMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
2872

How do you detect outliers?

IntuitMedium
Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
2873

What is the bias–variance trade-off?

IntuitMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
2874

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
2875

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
2876

What are lambda functions and where are they useful?

IntuitMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
2877

What is correlation and why does it not imply causation?

IntuitMedium
Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
2878

What are precision and recall trade-offs in practice?

IntuitMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
2879

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
2880

What are decorators in Python?

IntuitMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
2881

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
2882

How do you profile and speed up slow Python code?

IntuitMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
2883

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
2884

Explain ROC curve and AUC.

IntuitMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
2885

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
2886

Explain the chi-square test.

IntuitMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
2887

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
2888

What is the difference between parametric and non-parametric tests?

IntuitMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
2889

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
2890

Which activation functions do you know and when to use them?

IntuitMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2891

What is batch normalisation?

IntuitMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
2892

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
2893

What is transfer learning?

IntuitMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
2894

What is the difference between an epoch, a batch and an iteration?

IntuitMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
2895

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
2896

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
2897

What is a confidence interval?

IntuitMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
2898

Explain Bayes' theorem with an example.

IntuitMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
2899

How do you perform feature selection?

IntuitMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
2900

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
2901

What is the attention mechanism?

IntuitMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
2902

What is an autoencoder and what is it used for?

IntuitMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
2903

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
2904

What is a p-value?

WalmartMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
2905

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
2906

Explain ROC curve and AUC.

WalmartMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
2907

What is backpropagation?

WalmartMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
2908

What is Naive Bayes and why is it called naive?

WalmartMedium
Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
2909

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
2910

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
2911

What is the difference between iterators and iterables in Python?

WalmartMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
2912

What is the attention mechanism?

WalmartMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
2913

What is PCA and when do you use it?

WalmartMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
2914

Which activation functions do you know and when to use them?

WalmartMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
2915

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
2916

What is batch normalisation?

WalmartMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
2917

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
2918

What is correlation and why does it not imply causation?

WalmartMedium
Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
2919

What is the difference between apply, map and applymap in Pandas?

WalmartMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
2920

How does a decision tree decide where to split?

WalmartMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
2921

Explain Bayes' theorem with an example.

WalmartMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
2922

Explain the chi-square test.

WalmartMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
2923

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
2924

How does a CNN work?

WalmartMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
2925

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
2926

What is the Global Interpreter Lock (GIL)?

WalmartMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
2927

What are decorators in Python?

WalmartMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
2928

Explain the Law of Large Numbers.

WalmartMedium
Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
2929

How do you detect outliers?

WalmartMedium
Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
2930

Your dataset is highly imbalanced (2% positives). How do you handle it?

WalmartMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
2931

How do you detect and treat concept drift?

WalmartMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
2932

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
2933

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
2934

How does dropout work?

WalmartMedium
Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
2935

How do you choose a learning rate for a neural network?

WalmartMedium
Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
2936

How do you pivot data in Pandas?

WalmartMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
2937

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
2938

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
2939

What is the difference between parametric and non-parametric tests?

WalmartMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
2940

What is TF-IDF?

WalmartMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
2941

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
2942

What is the vanishing gradient problem?

WalmartMedium
Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
2943

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
2944

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
2945

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
2946

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
2947

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
2948

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
2949

What is a generator and when would you use one?

WalmartMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
2950

What are common ways to evaluate NLP models?

WalmartMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
2951

What is a confidence interval?

WalmartMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
2952

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
2953

How does the Gini impurity differ from entropy?

WalmartMedium
Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
2954

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
2955

Random forest vs a single decision tree?

WalmartMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
2956

What are precision and recall trade-offs in practice?

WalmartMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
2957

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
2958

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
2959

What is statistical power and how can you increase it?

WalmartMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
2960

How do you deal with high-cardinality categorical features?

WalmartMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
2961

What is sampling bias and how can you reduce it?

WalmartMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
2962

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
2963

What is transfer learning?

WalmartMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
2964

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
2965

What is the difference between apply, map and applymap in Pandas?

Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
2966

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
2967

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
2968

What is feature scaling and which models need it?

Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
2969

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
2970

What is transfer learning?

Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
2971

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
2972

How do you handle imbalanced classes?

Save to ▾
Show answer
Use stratified splits, class weights, resampling such as SMOTE, threshold tuning and judge models with precision, recall, F1 or PR-AUC instead of accuracy.
2973

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
2974

Pandas: find the top 3 products by revenue in each region.

Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
2975

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
2976

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
2977

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
2978

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
2979

How do you deal with high-cardinality categorical features?

Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
2980

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
2981

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
2982

What is calibration of a classifier?

Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
2983

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
2984

What is an autoencoder and what is it used for?

Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
2985

Explain logistic regression.

Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
2986

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
2987

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
2988

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
2989

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
2990

What is SVM and the kernel trick?

Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
2991

How does a CNN work?

Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
2992

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
2993

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
2994

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
2995

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
2996

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
2997

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
2998

Explain the KNN algorithm and its drawbacks.

Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
2999

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
3000

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
3001

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
3002

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
3003

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
3004

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
3005

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
3006

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
3007

How do you deal with high-cardinality categorical features?

Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
3008

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
3009

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
3010

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
3011

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
3012

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
3013

What is the difference between iterators and iterables in Python?

Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
3014

Which activation functions do you know and when to use them?

Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
3015

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
3016

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
3017

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
3018

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
3019

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
3020

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
3021

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
3022

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
3023

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
3024

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
3025

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
3026

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
3027

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
3028

How does K-means clustering work and how do you choose k?

Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
3029

What is sampling bias and how can you reduce it?

Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
3030

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
3031

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
3032

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
3033

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
3034

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
3035

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
3036

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
3037

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
3038

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
3039

What is the attention mechanism?

Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
3040

How do you pivot data in Pandas?

Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
3041

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
3042

What is stacking in ensemble learning?

Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
3043

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
3044

What is SVM and the kernel trick?

Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
3045

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
3046

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
3047

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
3048

Explain the chi-square test.

Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
3049

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
3050

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
3051

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
3052

What is backpropagation?

Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
3053

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
3054

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
3055

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
3056

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
3057

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
3058

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
3059

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
3060

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
3061

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
3062

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
3063

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
3064

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
3065

Why do we use activation functions? Why is ReLU popular?

Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
3066

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
3067

What is a generator and when would you use one?

Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
3068

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
3069

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
3070

How does dropout work?

Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
3071

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
3072

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
3073

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
3074

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
3075

What is calibration of a classifier?

Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
3076

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
3077

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
3078

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
3079

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
3080

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
3081

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
3082

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
3083

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
3084

What is a confidence interval?

Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
3085

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
3086

What is the difference between an epoch, a batch and an iteration?

Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
3087

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
3088

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
3089

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
3090

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
3091

What is the vanishing gradient problem?

Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
3092

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
3093

Explain the chi-square test.

Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
3094

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
3095

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
3096

How does K-means clustering work and how do you choose k?

Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
3097

Explain Bayes' theorem with an example.

Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
3098

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
3099

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
3100

What is backpropagation?

Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
3101

How do you pivot data in Pandas?

Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
3102

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
3103

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
3104

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
3105

How do you deal with high-cardinality categorical features?

Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
3106

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
3107

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
3108

What is sampling bias and how can you reduce it?

OracleMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
3109

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
3110

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
3111

How do you pivot data in Pandas?

OracleMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
3112

Why is XGBoost so popular?

OracleMedium
Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
3113

Pandas: merge vs join vs concat?

OracleMedium
Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
3114

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
3115

What is SVM and the kernel trick?

OracleMedium
Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
3116

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
3117

How do you tune hyperparameters?

OracleMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
3118

What is a generator and when would you use one?

OracleMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
3119

What is the Global Interpreter Lock (GIL)?

OracleMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
3120

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
3121

How do you detect outliers?

OracleMedium
Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
3122

What is Naive Bayes and why is it called naive?

OracleMedium
Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
3123

Explain the KNN algorithm and its drawbacks.

OracleMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
3124

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
3125

What is the vanishing gradient problem?

OracleMedium
Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
3126

What are RNNs and why did LSTMs improve them?

OracleMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
3127

How does a decision tree decide where to split?

OracleMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
3128

How does the Gini impurity differ from entropy?

OracleMedium
Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
3129

What is stacking in ensemble learning?

OracleMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
3130

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
3131

Explain the chi-square test.

OracleMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
3132

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
3133

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
3134

Explain ROC curve and AUC.

OracleMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
3135

What is the difference between parametric and non-parametric tests?

OracleMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
3136

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
3137

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
3138

What is statistical power and how can you increase it?

OracleMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
3139

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
3140

What are decorators in Python?

OracleMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
3141

How do you use groupby with multiple aggregations?

OracleMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
3142

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
3143

How do you perform feature selection?

OracleMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
3144

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
3145

How does linear regression work and what are its assumptions?

OracleMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
3146

What are common ways to evaluate NLP models?

OracleMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
3147

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
3148

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
3149

What is backpropagation?

OracleMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
3150

What are precision and recall trade-offs in practice?

OracleMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
3151

Your dataset is highly imbalanced (2% positives). How do you handle it?

OracleMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
3152

Why do we use activation functions? Why is ReLU popular?

OracleMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
3153

Random forest vs a single decision tree?

OracleMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
3154

Explain logistic regression.

OracleMedium
Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
3155

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
3156

What is the difference between mean, median and mode?

Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
3157

Pandas: find the top 3 products by revenue in each region.

OracleMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
3158

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
3159

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
3160

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
3161

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
3162

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
3163

How does dropout work?

OracleMedium
Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
3164

What is a p-value?

OracleMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
3165

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
3166

What is batch normalisation?

OracleMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
3167

Difference between a shallow copy and a deep copy?

OracleMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
3168

Explain Bayes' theorem with an example.

OracleMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
3169

How do you profile and speed up slow Python code?

OracleMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
3170

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
3171

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
3172

How do you detect and treat concept drift?

OracleMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
3173

How do you deal with high-cardinality categorical features?

OracleMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
3174

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
3175

What is the bias–variance trade-off?

OracleMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
3176

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
3177

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
3178

What is the Central Limit Theorem?

OracleMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
3179

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
3180

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
3181

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
3182

What is transfer learning?

OracleMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
3183

What is a neural network?

Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
3184

What is gradient descent and what does the learning rate do?

OracleMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
3185

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
3186

How do you evaluate and explain a model to business stakeholders?

CiscoHard
Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
3187

What is standard deviation and what does it tell you?

CiscoEasy
Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
3188

What is calibration of a classifier?

CiscoMedium
Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
3189

Difference between loc and iloc in Pandas?

CiscoEasy
Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
3190

What is overfitting and how do you prevent it?

CiscoEasy
Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
3191

What is a RAG system and why use it?

CiscoHard
Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
3192

What is a normal distribution?

CiscoEasy
Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
3193

How do list comprehensions work and why use them?

CiscoEasy
Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
3194

How do you detect outliers?

CiscoMedium
Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
3195

Pandas: merge vs join vs concat?

CiscoMedium
Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
3196

What is the Global Interpreter Lock (GIL)?

CiscoMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
3197

What is the difference between parametric and non-parametric tests?

CiscoMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
3198

What is NumPy broadcasting?

CiscoEasy
Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
3199

What is batch normalisation?

CiscoMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
3200

Type I vs Type II error?

CiscoEasy
Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
3201

How do you detect and treat concept drift?

CiscoMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
3202

What is backpropagation?

CiscoMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
3203

How do you remove duplicates from a DataFrame?

CiscoEasy
Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
3204

How do you deploy and monitor a machine learning model?

CiscoHard
Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
3205

How do you tune hyperparameters?

CiscoMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
3206

How does dropout work?

CiscoMedium
Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
3207

What are RNNs and why did LSTMs improve them?

CiscoMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
3208

What is SVM and the kernel trick?

CiscoMedium
Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
3209

What are Python's main built-in data types?

CiscoEasy
Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
3210

What is skewness?

CiscoEasy
Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
3211

What is regularization? Explain L1 vs L2.

CiscoMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
3212

How does the Gini impurity differ from entropy?

CiscoMedium
Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
3213

How would you build a churn prediction model end to end?

CiscoHard
Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
3214

How do you design an A/B test?

CiscoHard
Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
3215

What is the difference between == and is?

CiscoEasy
Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
3216

What are *args and **kwargs?

CiscoEasy
Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
3217

What are common ways to evaluate NLP models?

CiscoMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
3218

What is feature scaling and which models need it?

CiscoMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
3219

What is sampling bias and how can you reduce it?

CiscoMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
3220

What is multicollinearity and how do you handle it?

CiscoHard
Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
3221

What are precision and recall trade-offs in practice?

CiscoMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
3222

How does a decision tree decide where to split?

CiscoMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
3223

Explain the chi-square test.

CiscoMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
3224

What is PCA and when do you use it?

CiscoMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
3225

What is the difference between a function and a method?

CiscoEasy
Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
3226

Which activation functions do you know and when to use them?

CiscoMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
3227

Pandas: find the top 3 products by revenue in each region.

CiscoMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
3228

L1 vs L2 regularisation?

CiscoMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
3229

What is the difference between regression and classification?

CiscoEasy
Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
3230

What is a confidence interval?

CiscoMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
3231

What is the difference between apply, map and applymap in Pandas?

CiscoMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
3232

How do you perform feature selection?

CiscoMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
3233

What is Naive Bayes and why is it called naive?

CiscoMedium
Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
3234

Explain p-value in simple words.

CiscoEasy
Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
3235

What is the difference between Bayesian and frequentist approaches?

CiscoHard
Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
3236

What is correlation and why does it not imply causation?

CiscoMedium
Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
3237

CNN vs RNN vs Transformer — what is the difference?

CiscoHard
Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
3238

Explain precision vs recall. When would you prefer recall?

CiscoEasy
Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
3239

How do you handle missing values?

CiscoEasy
Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
3240

What is the difference between iterators and iterables in Python?

CiscoMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
3241

Explain logistic regression.

CiscoMedium
Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
3242

What is the difference between mean, median and mode?

CiscoEasy
Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
3243

Write a function to calculate RMSE without any library.

CiscoEasy
Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
3244

How does a CNN work?

CiscoMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
3245

What is tokenisation in NLP?

CiscoEasy
Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
3246

How does K-means clustering work and how do you choose k?

CiscoMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
3247

What is a confusion matrix?

CiscoEasy
Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
3248

Correlation vs covariance?

CiscoEasy
Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
3249

Explain the KNN algorithm and its drawbacks.

CiscoMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
3250

How do you deal with high-cardinality categorical features?

CiscoMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
3251

What is an autoencoder and what is it used for?

CiscoMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
3252

How do you profile and speed up slow Python code?

CiscoMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
3253

What is the bias–variance trade-off?

CiscoMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
3254

What is the difference between generative and discriminative models?

CiscoHard
Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
3255

Random forest vs a single decision tree?

CiscoMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
3256

Pandas: find the top 3 products by revenue in each region.

VisaMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
3257

How do you design an A/B test?

VisaHard
Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
3258

What is TF-IDF?

VisaMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
3259

What is a p-value?

VisaMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
3260

What are precision and recall trade-offs in practice?

VisaMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
3261

Explain precision vs recall. When would you prefer recall?

VisaEasy
Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
3262

How do you choose a learning rate for a neural network?

VisaMedium
Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
3263

How do you remove duplicates from a DataFrame?

VisaEasy
Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
3264

Random forest vs a single decision tree?

VisaMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
3265

Type I vs Type II error?

VisaEasy
Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
3266

How do transformers differ from RNNs?

VisaHard
Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
3267

Pearson vs Spearman correlation?

VisaEasy
Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
3268

What are Python's main built-in data types?

VisaEasy
Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
3269

Why are NumPy arrays faster than Python lists?

VisaMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
3270

What is feature scaling and which models need it?

VisaMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
3271

Write a function to calculate RMSE without any library.

VisaEasy
Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
3272

What is standard deviation and what does it tell you?

VisaEasy
Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
3273

What is gradient descent and what does the learning rate do?

VisaMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
3274

Explain the Law of Large Numbers.

VisaMedium
Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
3275

What are decorators in Python?

VisaMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
3276

What is tokenisation in NLP?

VisaEasy
Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
3277

What is the difference between a set and a dictionary?

VisaEasy
Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
3278

What is the difference between iterators and iterables in Python?

VisaMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
3279

What is the attention mechanism?

VisaMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
3280

What is PCA and when do you use it?

VisaMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
3281

What is data leakage?

VisaEasy
Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
3282

What is skewness?

VisaEasy
Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
3283

What is sampling bias and how can you reduce it?

VisaMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
3284

What is the difference between bagging and boosting?

VisaEasy
Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
3285

Explain the KNN algorithm and its drawbacks.

VisaMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
3286

How does K-means clustering work and how do you choose k?

VisaMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
3287

What is stacking in ensemble learning?

VisaMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
3288

What is the difference between supervised and unsupervised learning?

VisaEasy
Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
3289

What is batch normalisation?

VisaMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
3290

What is a Poisson distribution used for?

VisaEasy
Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
3291

What is a neural network?

VisaEasy
Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
3292

Why is XGBoost so popular?

VisaMedium
Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
3293

How does a CNN work?

VisaMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
3294

What is SVM and the kernel trick?

VisaMedium
Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
3295

What is the Central Limit Theorem?

VisaMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
3296

How does a decision tree decide where to split?

VisaMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
3297

Difference between a shallow copy and a deep copy?

VisaMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
3298

What is the difference between parametric and non-parametric tests?

VisaMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
3299

How does the Gini impurity differ from entropy?

VisaMedium
Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
3300

What is the difference between a function and a method?

VisaEasy
Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
3301

How do you profile and speed up slow Python code?

VisaMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
3302

What is the difference between regression and classification?

VisaEasy
Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
3303

What is the difference between == and is?

VisaEasy
Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
3304

CNN vs RNN vs Transformer — what is the difference?

VisaHard
Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
3305

What are RNNs and why did LSTMs improve them?

VisaMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
3306

Design an end-to-end churn prediction system.

VisaHard
Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
3307

What is an autoencoder and what is it used for?

VisaMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
3308

What is calibration of a classifier?

VisaMedium
Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
3309

How do you pivot data in Pandas?

VisaMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
3310

What is the vanishing gradient problem?

VisaMedium
Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
3311

Explain the chi-square test.

VisaMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
3312

What is the difference between mean, median and mode?

VisaEasy
Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
3313

How do you perform feature selection?

VisaMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
3314

How do you deal with high-cardinality categorical features?

VisaMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
3315

How does linear regression work and what are its assumptions?

VisaMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
3316

How do you deploy and monitor a machine learning model?

VisaHard
Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
3317

Your dataset is highly imbalanced (2% positives). How do you handle it?

VisaMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
3318

What is the difference between apply, map and applymap in Pandas?

VisaMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
3319

How do you detect and treat concept drift?

VisaMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
3320

Why do we use activation functions? Why is ReLU popular?

VisaMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
3321

What is a normal distribution?

VisaEasy
Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
3322

Difference between loc and iloc in Pandas?

VisaEasy
Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
3323

What is the difference between Bayesian and frequentist approaches?

VisaHard
Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
3324

How do you use groupby with multiple aggregations?

VisaMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
3325

What is a confidence interval?

VisaMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
3326

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
3327

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
3328

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
3329

Why are NumPy arrays faster than Python lists?

Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
3330

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
3331

Random forest vs a single decision tree?

Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
3332

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
3333

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
3334

How do you perform feature selection?

Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
3335

How does a decision tree decide where to split?

Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
3336

How does a CNN work?

Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
3337

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
3338

What is correlation and why does it not imply causation?

Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
3339

What is the attention mechanism?

Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
3340

Explain Bayes' theorem with an example.

Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
3341

How do you choose a learning rate for a neural network?

Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
3342

What is the difference between parametric and non-parametric tests?

Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
3343

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
3344

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
3345

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
3346

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
3347

Pandas: merge vs join vs concat?

Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
3348

Explain the KNN algorithm and its drawbacks.

Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
3349

How do you detect outliers?

Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
3350

How do you use groupby with multiple aggregations?

Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
3351

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
3352

What is gradient descent and what does the learning rate do?

Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
3353

What is the bias–variance trade-off?

Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
3354

What are decorators in Python?

Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
3355

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
3356

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
3357

Difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
3358

What is PCA and when do you use it?

Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
3359

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
3360

Your dataset is highly imbalanced (2% positives). How do you handle it?

Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
3361

Explain the Law of Large Numbers.

Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
3362

What is a generator and when would you use one?

Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
3363

How do you detect and treat concept drift?

Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
3364

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
3365

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
3366

What is transfer learning?

Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
3367

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
3368

What is batch normalisation?

Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
3369

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
3370

What is backpropagation?

Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
3371

What is sampling bias and how can you reduce it?

Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
3372

How does linear regression work and what are its assumptions?

Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
3373

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
3374

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
3375

How does dropout work?

Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
3376

What are RNNs and why did LSTMs improve them?

Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
3377

How does linear regression work and what are its assumptions?

BarclaysMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
3378

What is a p-value?

BarclaysMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
3379

What is the difference between apply, map and applymap in Pandas?

BarclaysMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
3380

What is skewness?

Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
3381

What is the bias–variance trade-off?

BarclaysMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
3382

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
3383

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
3384

How do you profile and speed up slow Python code?

BarclaysMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
3385

How do you use groupby with multiple aggregations?

BarclaysMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
3386

Why do we use activation functions? Why is ReLU popular?

BarclaysMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
3387

What is SVM and the kernel trick?

BarclaysMedium
Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
3388

What is a confidence interval?

BarclaysMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
3389

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
3390

What is statistical power and how can you increase it?

BarclaysMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
3391

What is NumPy broadcasting?

Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
3392

Random forest vs a single decision tree?

BarclaysMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
3393

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
3394

Explain precision vs recall. When would you prefer recall?

Save to ▾
Show answer
Precision = TP / (TP + FP). Recall = TP / (TP + FN). Prefer recall when missing a positive is costly — for example disease screening or fraud detection.
3395

How do you evaluate and explain a model to business stakeholders?

Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
3396

Explain Bayes' theorem with an example.

BarclaysMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
3397

What are precision and recall trade-offs in practice?

BarclaysMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
3398

How do you deal with high-cardinality categorical features?

BarclaysMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
3399

What is an autoencoder and what is it used for?

BarclaysMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
3400

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
3401

What is TF-IDF?

BarclaysMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
3402

How does K-means clustering work and how do you choose k?

BarclaysMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
3403

What is Naive Bayes and why is it called naive?

BarclaysMedium
Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
3404

What are decorators in Python?

BarclaysMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
3405

What is the Central Limit Theorem?

BarclaysMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
3406

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
3407

L1 vs L2 regularisation?

BarclaysMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
3408

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
3409

How does a CNN work?

BarclaysMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
3410

How do you tune hyperparameters?

BarclaysMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
3411

What is sampling bias and how can you reduce it?

BarclaysMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
3412

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
3413

What is the difference between iterators and iterables in Python?

BarclaysMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
3414

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
3415

What is the Global Interpreter Lock (GIL)?

BarclaysMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
3416

What is a Poisson distribution used for?

Save to ▾
Show answer
Modelling the count of events in a fixed interval when events occur independently at a constant average rate, such as calls per hour or defects per batch.
3417

How do you remove duplicates from a DataFrame?

Save to ▾
Show answer
df.drop_duplicates(subset=[...], keep='first') removes repeated rows; use duplicated() first to inspect what will be dropped.
3418

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
3419

Pandas: find the top 3 products by revenue in each region.

BarclaysMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
3420

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
3421

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
3422

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
3423

How do you detect outliers?

BarclaysMedium
Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
3424

What is the difference between an epoch, a batch and an iteration?

BarclaysMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
3425

What is backpropagation?

BarclaysMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
3426

Difference between a shallow copy and a deep copy?

BarclaysMedium
Save to ▾
Show answer
A shallow copy duplicates the outer object but shares nested objects. A deep copy (copy.deepcopy) recursively duplicates everything, so changes to nested items do not leak.
3427

How do you perform feature selection?

BarclaysMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
3428

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
3429

What is the difference between parametric and non-parametric tests?

BarclaysMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
3430

How do you choose a learning rate for a neural network?

BarclaysMedium
Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
3431

What is a generator and when would you use one?

BarclaysMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
3432

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
3433

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
3434

What is regularization? Explain L1 vs L2.

BarclaysMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
3435

Which activation functions do you know and when to use them?

BarclaysMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
3436

What is gradient descent and what does the learning rate do?

BarclaysMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
3437

What is batch normalisation?

BarclaysMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
3438

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
3439

What are RNNs and why did LSTMs improve them?

BarclaysMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
3440

What are lambda functions and where are they useful?

BarclaysMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
3441

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
3442

Correlation vs covariance?

Save to ▾
Show answer
Covariance shows the direction of a relationship but depends on units. Correlation is covariance scaled to −1…+1, so it shows direction and strength and is unit-free.
3443

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
3444

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
3445

How does a decision tree decide where to split?

BarclaysMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
3446

What is data leakage?

Save to ▾
Show answer
Information from outside the training window, such as future data or test statistics, enters training and inflates performance. Split first, then fit scalers and encoders on training data only.
3447

How does the Gini impurity differ from entropy?

BarclaysMedium
Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
3448

What is correlation and why does it not imply causation?

BarclaysMedium
Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
3449

What are common ways to evaluate NLP models?

BarclaysMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
3450

Why is XGBoost so popular?

BarclaysMedium
Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
3451

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
3452

Write a function to calculate RMSE without any library.

Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
3453

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
3454

Pandas: merge vs join vs concat?

BarclaysMedium
Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
3455

Explain logistic regression.

HSBCMedium
Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
3456

How would you optimise a slow Pandas pipeline on a 5 GB file?

HSBCHard
Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
3457

L1 vs L2 regularisation?

HSBCMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
3458

Why are NumPy arrays faster than Python lists?

HSBCMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
3459

How does a CNN work?

HSBCMedium
Save to ▾
Show answer
Convolution filters slide over the input to detect local patterns, pooling reduces size, and deeper layers combine edges into shapes and objects. Used mainly for images.
3460

What is a neural network?

HSBCEasy
Save to ▾
Show answer
Layers of connected neurons that apply weights, biases and activation functions to learn complex patterns, trained by backpropagation.
3461

What is overfitting and how do you prevent it?

HSBCEasy
Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
3462

What are decorators in Python?

HSBCMedium
Save to ▾
Show answer
A decorator wraps a function to add behaviour such as logging, timing or caching without changing its code. It is applied with the @name syntax above the function.
3463

How does K-means clustering work and how do you choose k?

HSBCMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
3464

What is a confidence interval?

HSBCMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
3465

What is the difference between bagging and boosting?

HSBCEasy
Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
3466

How do transformers differ from RNNs?

HSBCHard
Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
3467

Explain train, validation and test sets.

HSBCEasy
Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
3468

What is the difference between parametric and non-parametric tests?

HSBCMedium
Save to ▾
Show answer
Parametric tests assume a distribution (usually normal) and use means; non-parametric tests such as Mann-Whitney use ranks and make fewer assumptions.
3469

What are lambda functions and where are they useful?

HSBCMedium
Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
3470

What is PCA and when do you use it?

HSBCMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
3471

What is batch normalisation?

HSBCMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
3472

What are common ways to evaluate NLP models?

HSBCMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
3473

What is the Global Interpreter Lock (GIL)?

HSBCMedium
Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
3474

How do you pivot data in Pandas?

HSBCMedium
Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
3475

What is the difference between apply, map and applymap in Pandas?

HSBCMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
3476

Type I vs Type II error?

HSBCEasy
Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
3477

How do you detect outliers?

HSBCMedium
Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
3478

What is skewness?

HSBCEasy
Save to ▾
Show answer
A measure of asymmetry. Right-skewed data has a long tail on the right (mean greater than median); left-skewed is the opposite. Log transforms often reduce right skew.
3479

How do you deal with high-cardinality categorical features?

HSBCMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
3480

How does dropout work?

HSBCMedium
Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
3481

Design an end-to-end churn prediction system.

HSBCHard
Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
3482

Explain Bayes' theorem with an example.

HSBCMedium
Save to ▾
Show answer
P(A given B) = P(B given A) x P(A) / P(B). In a medical test it converts test accuracy and disease prevalence into the real chance a positive result means disease.
3483

How do you profile and speed up slow Python code?

HSBCMedium
Save to ▾
Show answer
Measure first with cProfile or timeit, then replace loops with NumPy or Pandas vectorised calls, use built-ins, caching and better data structures.
3484

What is the difference between list, tuple, set and dict in Python?

HSBCEasy
Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
3485

Write a function to calculate RMSE without any library.

HSBCEasy
Save to ▾
Show answer
def rmse(y, p): return (sum((a - b) ** 2 for a, b in zip(y, p)) / len(y)) ** 0.5
3486

What is the attention mechanism?

HSBCMedium
Save to ▾
Show answer
It lets a model weigh which input positions matter most for each output, computing weighted combinations of values from query-key similarity. It is the core of transformers.
3487

What is multicollinearity and how do you handle it?

HSBCHard
Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
3488

What is the difference between regression and classification?

HSBCEasy
Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
3489

How does a decision tree decide where to split?

HSBCMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
3490

What is a generator and when would you use one?

HSBCMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
3491

Explain ROC curve and AUC.

HSBCMedium
Save to ▾
Show answer
The ROC curve plots true positive rate against false positive rate across thresholds. AUC is the probability that a random positive is ranked above a random negative; 0.5 is chance.
3492

What is a p-value?

HSBCMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
3493

What is Naive Bayes and why is it called naive?

HSBCMedium
Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
3494

Pearson vs Spearman correlation?

HSBCEasy
Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
3495

What is correlation and why does it not imply causation?

HSBCMedium
Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
3496

How do you choose a learning rate for a neural network?

HSBCMedium
Save to ▾
Show answer
Start with a sensible default such as 1e-3 for Adam, run a learning-rate range test, and use schedulers or warm-up while watching the loss curve.
3497

How do you perform feature selection?

HSBCMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
3498

What is stacking in ensemble learning?

HSBCMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
3499

What is calibration of a classifier?

HSBCMedium
Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
3500

What is NumPy broadcasting?

HSBCEasy
Save to ▾
Show answer
The rule that lets arrays of different shapes operate together by virtually stretching the smaller one, for example adding a scalar or a (3,) vector to a (4,3) matrix.
3501

CNN vs RNN vs Transformer — what is the difference?

HSBCHard
Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
3502

What are *args and **kwargs?

HSBCEasy
Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
3503

What is a RAG system and why use it?

HSBCHard
Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
3504

What is the bias–variance trade-off?

HSBCMedium
Save to ▾
Show answer
Bias is error from overly simple assumptions (underfitting). Variance is sensitivity to the training data (overfitting). More model complexity lowers bias but raises variance — aim for the lowest total error using cross-validation and regularization.
3505

How do you handle missing values?

HSBCEasy
Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
3506

Explain the chi-square test.

HSBCMedium
Save to ▾
Show answer
It checks whether observed category counts differ from expected counts, used for independence between two categorical variables and for goodness of fit.
3507

What is the difference between mean, median and mode?

HSBCEasy
Save to ▾
Show answer
Mean is the average, median is the middle value after sorting and mode is the most frequent value. Median is more robust to outliers.
3508

How would you build a churn prediction model end to end?

HSBCHard
Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
3509

What is regularization? Explain L1 vs L2.

HSBCMedium
Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
3510

Your dataset is highly imbalanced (2% positives). How do you handle it?

HSBCMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
3511

What is the difference between supervised and unsupervised learning?

HSBCEasy
Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
3512

How do you evaluate and explain a model to business stakeholders?

HSBCHard
Save to ▾
Show answer
Tie metrics to business outcomes such as cost saved, show feature importance or SHAP values, give example predictions and be transparent about limitations.
3513

How do you design an A/B test?

HSBCHard
Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
3514

How do you detect and treat concept drift?

HSBCMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
3515

What is a confusion matrix?

HSBCEasy
Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
3516

What is the vanishing gradient problem?

HSBCMedium
Save to ▾
Show answer
Gradients shrink as they pass through many layers (for example with sigmoid), so early layers barely learn. ReLU, residual connections and good initialisation help.
3517

What is tokenisation in NLP?

HSBCEasy
Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
3518

Explain the KNN algorithm and its drawbacks.

HSBCMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
3519

What is SVM and the kernel trick?

HSBCMedium
Save to ▾
Show answer
SVM finds the maximum-margin separating hyperplane. Kernels such as RBF compute similarity in a higher-dimensional space implicitly, so non-linear boundaries are possible.
3520

What is the difference between generative and discriminative models?

HSBCHard
Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
3521

What is the difference between == and is?

HSBCEasy
Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
3522

Difference between loc and iloc in Pandas?

HSBCEasy
Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
3523

What is the difference between a function and a method?

HSBCEasy
Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
3524

Why do we use activation functions? Why is ReLU popular?

HSBCMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
3525

What is cross-validation and why use it?

HSBCEasy
Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
3526

Pandas: merge vs join vs concat?

HCLTechMedium
Save to ▾
Show answer
merge joins on columns, SQL-style (how='inner', 'left', ...). join joins on the index. concat stacks DataFrames along rows or columns.
3527

What are Python's main built-in data types?

Save to ▾
Show answer
int, float, complex, bool, str, list, tuple, set, dict and NoneType. Mutable ones are list, set and dict; the others are immutable.
3528

How do you deal with high-cardinality categorical features?

HCLTechMedium
Save to ▾
Show answer
Use target or frequency encoding with cross-validation, hashing, embeddings or grouping rare categories, instead of huge one-hot matrices.
3529

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
3530

What is the difference between iterators and iterables in Python?

HCLTechMedium
Save to ▾
Show answer
An iterable can produce an iterator (it has __iter__); an iterator has __next__ and remembers its position. A for-loop calls iter() on the iterable and then next() repeatedly.
3531

How would you optimise a slow Pandas pipeline on a 5 GB file?

Save to ▾
Show answer
Read in chunks or use usecols and dtypes, convert strings to category, avoid apply with row loops in favour of vectorised ops, and consider Polars, Dask or Parquet storage.
3532

What is the difference between bagging and boosting?

Save to ▾
Show answer
Bagging trains models in parallel on bootstrap samples and averages them (reduces variance, e.g. Random Forest). Boosting trains models one after another, each fixing the previous errors (reduces bias, e.g. XGBoost).
3533

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
3534

What is the difference between apply, map and applymap in Pandas?

HCLTechMedium
Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
3535

What is calibration of a classifier?

HCLTechMedium
Save to ▾
Show answer
Calibration checks whether predicted probabilities match real frequencies (e.g. 70% predictions are right about 70% of the time). Fix with Platt scaling or isotonic regression.
3536

How does K-means clustering work and how do you choose k?

HCLTechMedium
Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
3537

How do you tune hyperparameters?

HCLTechMedium
Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
3538

What is correlation and why does it not imply causation?

HCLTechMedium
Save to ▾
Show answer
Correlation measures linear association between variables (-1 to 1). A third factor, reverse causality or chance can create it, so causation needs controlled experiments.
3539

What is backpropagation?

HCLTechMedium
Save to ▾
Show answer
It computes the gradient of the loss with respect to every weight by applying the chain rule backwards through the network, so gradient descent can update them.
3540

What is TF-IDF?

HCLTechMedium
Save to ▾
Show answer
Term Frequency × Inverse Document Frequency: a word scores high if it is frequent in one document but rare across all documents. A classic way to turn text into numeric features.
3541

What is the difference between Bayesian and frequentist approaches?

Save to ▾
Show answer
Frequentists treat parameters as fixed and use long-run frequencies; Bayesians treat parameters as distributions updated with data via priors and posteriors, giving direct probability statements.
3542

How does dropout work?

HCLTechMedium
Save to ▾
Show answer
During training it randomly switches off a fraction of neurons so the network cannot depend on any single unit, acting as a regulariser against overfitting.
3543

Which activation functions do you know and when to use them?

HCLTechMedium
Save to ▾
Show answer
ReLU for hidden layers, sigmoid for binary outputs, softmax for multi-class outputs and tanh when zero-centred outputs help; Leaky ReLU avoids dead neurons.
3544

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
3545

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
3546

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
3547

What is the difference between an epoch, a batch and an iteration?

HCLTechMedium
Save to ▾
Show answer
An epoch is one pass over the training data; a batch is the subset used for one update; an iteration is one weight update on a batch.
3548

Train accuracy is 95% but test accuracy is 70%. What do you do?

Save to ▾
Show answer
This is overfitting. Check for data leakage, simplify the model, add regularization, get more data or augment it, use cross-validation, early stopping and feature selection.
3549

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
3550

What is PCA and when do you use it?

HCLTechMedium
Save to ▾
Show answer
It projects data onto orthogonal directions of maximum variance to reduce dimensions, remove correlation and speed up models, at some cost of interpretability.
3551

What is batch normalisation?

HCLTechMedium
Save to ▾
Show answer
It normalises layer inputs per mini-batch and then rescales them, stabilising and speeding up training and allowing higher learning rates.
3552

What is an autoencoder and what is it used for?

HCLTechMedium
Save to ▾
Show answer
A network that compresses inputs into a small latent code and reconstructs them; used for denoising, dimensionality reduction and anomaly detection.
3553

What are common ways to evaluate NLP models?

HCLTechMedium
Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
3554

Your dataset is highly imbalanced (2% positives). How do you handle it?

HCLTechMedium
Save to ▾
Show answer
Use stratified splits, class weights, resampling (SMOTE or undersampling) and threshold tuning, and judge the model with PR-AUC or F1 instead of accuracy.
3555

Explain the Law of Large Numbers.

HCLTechMedium
Save to ▾
Show answer
As the number of independent trials grows, the sample average converges to the true expected value, which is why larger samples give more stable estimates.
3556

Pearson vs Spearman correlation?

Save to ▾
Show answer
Pearson measures linear relationships on continuous data; Spearman uses ranks, so it captures monotonic relationships and is less sensitive to outliers.
3557

Why do we use activation functions? Why is ReLU popular?

HCLTechMedium
Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
3558

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
3559

What is a confidence interval?

HCLTechMedium
Save to ▾
Show answer
A range built from sample data that would contain the true parameter in a stated percentage (for example 95%) of repeated samples. It is not the probability that the parameter lies inside this one interval.
3560

What are RNNs and why did LSTMs improve them?

HCLTechMedium
Save to ▾
Show answer
RNNs process sequences with a hidden state but struggle with long dependencies. LSTMs add gates that control what to remember or forget, easing the vanishing gradient.
3561

How does linear regression work and what are its assumptions?

HCLTechMedium
Save to ▾
Show answer
It fits a line minimising squared error. Assumes linearity, independent errors, constant variance (homoscedasticity), normally distributed residuals and no strong multicollinearity.
3562

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
3563

What is the difference between generative and discriminative models?

Save to ▾
Show answer
Discriminative models learn P(y given x) directly (logistic regression, SVM). Generative models learn the joint P(x, y) and can generate data (Naive Bayes, GANs).
3564

How do you perform feature selection?

HCLTechMedium
Save to ▾
Show answer
Use filter methods (correlation, chi-square), wrapper methods (RFE), embedded methods (Lasso, tree importance) and domain knowledge, validating each choice with cross-validation.
3565

How would you fine-tune a pretrained language model for classification?

Save to ▾
Show answer
Add a classification head, freeze or gradually unfreeze layers, use a small learning rate, train on labelled data with validation, and track F1 per class.
3566

Difference between loc and iloc in Pandas?

Save to ▾
Show answer
loc selects by label (row and column names, inclusive of the end label); iloc selects by integer position (end-exclusive).
3567

How do you detect and treat concept drift?

HCLTechMedium
Save to ▾
Show answer
Monitor input distributions and live metrics, compare to training baselines, and retrain or recalibrate on fresh data when performance drops.
3568

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
3569

What are *args and **kwargs?

Save to ▾
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They make function signatures flexible and are common in wrappers and decorators.
3570

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
3571

What is overfitting and how do you prevent it?

Save to ▾
Show answer
The model memorises noise and fails on new data. Prevent it with more data, simpler models, regularisation, cross-validation, early stopping and dropout.
3572

Why are NumPy arrays faster than Python lists?

HCLTechMedium
Save to ▾
Show answer
They store same-type values in contiguous memory and run vectorised operations in compiled C, avoiding Python loop overhead and per-object type checks.
3573

Type I vs Type II error?

Save to ▾
Show answer
Type I = false positive (rejecting a true null), probability α. Type II = false negative (missing a real effect), probability β. Power = 1 − β.
3574

What is a p-value?

HCLTechMedium
Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
3575

What is a generator and when would you use one?

HCLTechMedium
Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
3576

L1 vs L2 regularisation?

HCLTechMedium
Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
3577

What is statistical power and how can you increase it?

HCLTechMedium
Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
3578

What is the Central Limit Theorem?

HCLTechMedium
Save to ▾
Show answer
The distribution of sample means approaches a normal distribution as the sample size grows (roughly 30+), whatever the population's shape. It lets us build confidence intervals and run hypothesis tests on means.
3579

What is transfer learning?

HCLTechMedium
Save to ▾
Show answer
Reusing a model pretrained on a large dataset and fine-tuning it on a smaller task-specific dataset, saving data, time and compute.
3580

What is feature scaling and which models need it?

HCLTechMedium
Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
3581

Random forest vs a single decision tree?

HCLTechMedium
Save to ▾
Show answer
A forest averages many trees trained on bootstrapped rows and random feature subsets, which cuts variance and overfitting at the cost of interpretability.
3582

What is gradient descent and what does the learning rate do?

HCLTechMedium
Save to ▾
Show answer
An optimisation method that updates weights in the opposite direction of the loss gradient. The learning rate sets the step size: too high and it diverges, too low and it is slow. Variants include SGD, mini-batch and Adam.
3583

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
3584

Explain the KNN algorithm and its drawbacks.

HCLTechMedium
Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.
3585

What are precision and recall trade-offs in practice?

HCLTechMedium
Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
3586

What is stacking in ensemble learning?

HCLTechMedium
Save to ▾
Show answer
Training a meta-model on the predictions of several base models, often using cross-validated predictions to avoid leakage.
3587

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
3588

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
3589

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
3590

How do you use groupby with multiple aggregations?

HCLTechMedium
Save to ▾
Show answer
df.groupby('region').agg(total=('sales','sum'), avg=('sales','mean')) gives named aggregations per group in one pass.
3591

How does a decision tree decide where to split?

HCLTechMedium
Save to ▾
Show answer
It tries candidate splits and picks the one that most reduces impurity — Gini or entropy (information gain) for classification, variance / MSE for regression.
3592

What is cross-validation and why use it?

Save to ▾
Show answer
Split the data into k folds, train on k−1 folds and validate on the remaining one, rotate and average the scores. It gives a more reliable estimate than one split and helps tune hyperparameters without touching the test set.
3593

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
3594

What is sampling bias and how can you reduce it?

HCLTechMedium
Save to ▾
Show answer
Bias occurs when the sample does not represent the population. Reduce it with random or stratified sampling, higher response rates and by checking sample demographics against the population.
3595

Explain logistic regression.

HCLTechMedium
Save to ▾
Show answer
It models the log-odds of a binary outcome as a linear function and passes it through a sigmoid to give probabilities, trained by maximising likelihood.
3596

How do you design an A/B test?

Save to ▾
Show answer
Define the hypothesis and one primary metric, calculate sample size from the baseline, minimum detectable effect, α and power, randomise users, run for full business cycles, check for sample-ratio mismatch, then test both statistical and practical significance.
3597

Pandas: find the top 3 products by revenue in each region.

HCLTechMedium
Save to ▾
Show answer
(df.assign(rev=df.price * df.qty) .groupby(['region', 'product'])['rev'].sum() .reset_index() .sort_values('rev', ascending=False) .groupby('region').head(3))
3598

How would you build a churn prediction model end to end?

Save to ▾
Show answer
Define churn and the prediction window, build behavioural features, split by time, train and compare models, evaluate with recall and lift, explain drivers and monitor drift after deployment.
3599

What is tokenisation in NLP?

Save to ▾
Show answer
Splitting text into units such as words, subwords or characters that are mapped to ids; subword methods like BPE handle rare words well.
3600

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
3601

What is the difference between a set and a dictionary?

Save to ▾
Show answer
A set stores unique values with no keys; a dictionary stores key-value pairs with unique keys. Both use hashing, so lookups are O(1) on average.
3602

Explain p-value in simple words.

Save to ▾
Show answer
The probability of seeing a result at least this extreme if the null hypothesis were true. A small p-value (for example < 0.05) is evidence against the null hypothesis.
3603

How do you detect outliers?

HCLTechMedium
Save to ▾
Show answer
Use the IQR rule (below Q1-1.5 IQR or above Q3+1.5 IQR), z-scores beyond 3, box plots or model-based methods such as Isolation Forest, then decide whether to cap, remove or keep them.
3604

Why do we use activation functions? Why is ReLU popular?

Save to ▾
Show answer
Activations add non-linearity so networks can learn complex patterns. ReLU (max(0, x)) is cheap and reduces vanishing gradients compared with sigmoid/tanh; Leaky ReLU avoids 'dead' neurons.
3605

How do you handle missing values?

Save to ▾
Show answer
First understand why data is missing. Then drop rows or columns with too many nulls, impute with mean/median/mode or a model (KNN), add a 'was_missing' flag, and fit imputers on training data only.
3606

What is the difference between a function and a method?

Save to ▾
Show answer
A method is a function that belongs to an object or class and receives the instance (self) as its first argument.
3607

How do you tune hyperparameters?

Save to ▾
Show answer
Use grid search, random search or Bayesian optimisation with cross-validation, starting with a coarse random search and narrowing the promising ranges.
3608

What are common ways to evaluate NLP models?

Save to ▾
Show answer
Accuracy, F1 and confusion matrices for classification, BLEU or ROUGE for generation and summarisation, perplexity for language models, plus human review.
3609

What is a confusion matrix?

Save to ▾
Show answer
A table of true positives, false positives, true negatives and false negatives from which accuracy, precision, recall and F1 are calculated.
3610

What is a normal distribution?

Save to ▾
Show answer
A symmetric bell-shaped distribution defined by mean and standard deviation, where about 68%, 95% and 99.7% of values lie within 1, 2 and 3 standard deviations.
3611

What is the difference between supervised and unsupervised learning?

Save to ▾
Show answer
Supervised learning trains on labelled data to predict a target; unsupervised learning finds structure such as clusters or components in unlabelled data.
3612

How does the Gini impurity differ from entropy?

Save to ▾
Show answer
Both measure node impurity; Gini is cheaper to compute and entropy is slightly more sensitive to class balance, with similar trees in practice.
3613

What is a p-value?

Save to ▾
Show answer
The probability of seeing a result at least as extreme as the observed one if the null hypothesis were true. A small p-value is evidence against the null, not proof that the alternative is true.
3614

What is regularization? Explain L1 vs L2.

Save to ▾
Show answer
Regularization adds a penalty on weights to reduce overfitting. L1 (Lasso) adds |w| and can push features to exactly zero. L2 (Ridge) adds w² and shrinks weights smoothly.
3615

L1 vs L2 regularisation?

Save to ▾
Show answer
L1 (Lasso) adds absolute weights and can shrink some to zero, giving feature selection. L2 (Ridge) adds squared weights and shrinks them smoothly without removing features.
3616

What is the difference between == and is?

Save to ▾
Show answer
== compares values for equality, while is checks whether two names point to the same object in memory. Use is mainly for None checks.
3617

What is feature scaling and which models need it?

Save to ▾
Show answer
Putting features on comparable ranges using standardisation or min-max scaling. Distance-based and gradient-based models (KNN, SVM, regression, neural nets) need it; tree models do not.
3618

What is the difference between list, tuple, set and dict in Python?

Save to ▾
Show answer
List: ordered and mutable. Tuple: ordered and immutable (hashable, slightly faster). Set: unordered, unique items, fast membership checks. Dict: key–value pairs with fast lookup by key.
3619

What is a generator and when would you use one?

Save to ▾
Show answer
A function using yield that produces values lazily, one at a time. It saves memory when processing large files or streams because the full sequence is never held in RAM.
3620

Why is XGBoost so popular?

Save to ▾
Show answer
It combines gradient boosting with regularisation, handling of missing values, parallel tree construction and speed optimisations, and it performs strongly on tabular data.
3621

What is the difference between apply, map and applymap in Pandas?

Save to ▾
Show answer
map works element-wise on a Series, apply works on a Series or along a DataFrame axis, and applymap (now DataFrame.map) applies a function to every cell.
3622

What is statistical power and how can you increase it?

Save to ▾
Show answer
Power is the probability of detecting a real effect. Increase it with a larger sample, a bigger effect size, lower noise or a higher significance level.
3623

How do transformers differ from RNNs?

Save to ▾
Show answer
Transformers use self-attention to process all tokens in parallel and capture long-range context, making them faster to train and more scalable than sequential RNNs.
3624

How does K-means clustering work and how do you choose k?

Save to ▾
Show answer
It assigns points to the nearest centroid and updates centroids until stable. Choose k with the elbow method, silhouette score or business context.
3625

How do you pivot data in Pandas?

Save to ▾
Show answer
pd.pivot_table(df, index='region', columns='month', values='sales', aggfunc='sum') reshapes long data into a summary matrix; melt() does the reverse.
3626

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
It applies Bayes' theorem assuming features are independent given the class. The assumption is rarely true but the model is fast and works well for text.
3627

Design an end-to-end churn prediction system.

Save to ▾
Show answer
Define churn and the prediction window → build usage and billing features → handle imbalance → train gradient boosting → evaluate with PR-AUC and lift → explain with SHAP → deploy as batch scoring or an API → monitor drift → hand top-risk users to the retention team.
3628

What is the difference between regression and classification?

Save to ▾
Show answer
Regression predicts continuous values such as price; classification predicts discrete categories such as spam or not spam.
3629

How do you deploy and monitor a machine learning model?

Save to ▾
Show answer
Package the model behind an API with versioning, track latency and errors, monitor input drift and prediction quality, and automate retraining with rollback.
3630

What is multicollinearity and how do you handle it?

Save to ▾
Show answer
Predictors that are highly correlated make coefficients unstable. Detect with VIF above about 5-10, then drop or combine features, use PCA or apply regularisation.
3631

What are lambda functions and where are they useful?

Save to ▾
Show answer
Small anonymous one-line functions, handy as arguments to sort, map, filter or Pandas apply.
3632

CNN vs RNN vs Transformer — what is the difference?

Save to ▾
Show answer
CNNs use convolutions to find spatial patterns (images). RNNs/LSTMs process sequences step by step but struggle with long context. Transformers use self-attention to look at all tokens at once — parallel and better at long-range context; they power modern LLMs.
3633

Explain train, validation and test sets.

Save to ▾
Show answer
Train fits the model, validation tunes hyperparameters and model choice, and the untouched test set gives a final unbiased estimate of performance.
3634

How do list comprehensions work and why use them?

Save to ▾
Show answer
They build a list in one readable expression, for example [x*x for x in data if x > 0]. They are usually faster than an equivalent for-loop with append.
3635

What are precision and recall trade-offs in practice?

Save to ▾
Show answer
Raising the threshold improves precision but lowers recall. Fraud detection leans to recall, while spam filters often prefer precision; choose by the cost of each error.
3636

What is standard deviation and what does it tell you?

Save to ▾
Show answer
The square root of the variance; it measures how far values typically sit from the mean, in the same units as the data.
3637

What is a RAG system and why use it?

Save to ▾
Show answer
Retrieval-Augmented Generation fetches relevant documents and gives them to an LLM as context, reducing hallucination and keeping answers grounded in current private data.
3638

What is the Global Interpreter Lock (GIL)?

Save to ▾
Show answer
A mutex in CPython that lets only one thread execute Python bytecode at a time. Use multiprocessing for CPU-bound work and threads or asyncio for I/O-bound work.
3639

Explain the KNN algorithm and its drawbacks.

Save to ▾
Show answer
It predicts from the k nearest labelled points. It is simple but slow at prediction time, sensitive to scaling and irrelevant features, and weak in high dimensions.