Machine Learning Interview Questions for Data Science Freshers
Data science interviews test whether you can show an ML idea in code, not only define it. This guide covers six topics with runnable sklearn snippets and the patterns to explain on a live screen.
Say you are in a data science interview and you are asked to explain overfitting. You answer well. Then the interviewer turns the laptop toward you and says, "Show me." Could you write the code and read its output aloud, with the interviewer watching your screen?
Data science interviews test whether you can show an ML idea in code, not only define it. Prepare six topics: feature engineering, bias-variance, regularization, imbalanced metrics, cross-validation and the confusion matrix. For each, learn one short sklearn snippet and the output it prints. Then you can answer the theory and prove it on a live screen.
This is not a full question bank. It covers six topics you can show in code, and it leaves out decision trees, random forest vs gradient boosting, KNN and handling missing values. Every topic below comes with code you can paste into a Jupyter notebook. Where the output is fixed, I show it. Where it depends on random data, I tell you which pattern to look for, because your decimals may differ from any I could print. If you are still deciding whether this role suits you, read how to become a data scientist after a BSc in Computer Science first.
Feature engineering: turn raw columns into model inputs
Feature engineering means creating, transforming or selecting columns so a model can learn from them, such as pulling month out of a date or one-hot encoding a city, as the GeeksforGeeks ML interview list defines it.
Interviewers like to hear the parts by name:
- Create: build a new column from old ones, like the joining month from a date.
- Transform: change how a column looks, like a log on skewed salaries or one-hot encoding on a category.
- Select: keep only useful columns. Filter methods score each column on its own. Wrapper methods train a model on different subsets. Embedded methods pick features during training, which is what Lasso does.
Here is a tiny dataset of employees with a date, a city and a salary:
import numpy as np
import pandas as pd
df = pd.DataFrame({
"joined": ["2024-01-15", "2023-07-01", "2025-03-20"],
"city": ["Kolkata", "Pune", "Kolkata"],
"salary": [300000, 450000, 1200000],
})
df["joined"] = pd.to_datetime(df["joined"])
df["join_year"] = df["joined"].dt.year
df["join_month"] = df["joined"].dt.month
df["log_salary"] = np.log1p(df["salary"]).round(2)
df = pd.get_dummies(df, columns=["city"], dtype=int)
print(df.drop(columns=["joined", "salary"]))
join_year join_month log_salary city_Kolkata city_Pune
0 2024 1 12.61 1 0
1 2023 7 13.02 0 1
2 2025 3 14.00 1 0
Look at the salary column. The raw values were spread wide, but after the log they sit close together. A linear model handles that much better. I used log1p rather than log because it does not break on a zero. In a real project you would use sklearn's OneHotEncoder inside a pipeline, since get_dummies cannot remember the categories it saw during training.
Follow-up you will hear: "On a messy dataset, which step do you do first?" Start by understanding the data. Run df.info(), check missing values and fix wrong types, like dates stored as text. Then create and transform features. Selection comes last, because you cannot select columns that do not exist yet.
Standardization vs normalization
Standardization shifts each feature to mean 0 and standard deviation 1, while normalization squeezes values into the 0 to 1 range, and the choice depends on the model and on outliers, per the GeeksforGeeks definitions.
| StandardScaler (standardization) | MinMaxScaler (normalization) | |
|---|---|---|
| Output | Centred on zero, no fixed range | Fixed between zero and one |
| Effect of one big outlier | Shifts the mean a little; normal values keep their spread | Squeezes all normal values into a narrow band |
| Models that need it | Linear and logistic regression, SVM, PCA | KNN, neural networks, pixel values |
| Tree models | Not needed | Not needed |
The snippet below scales one column both ways. The last value is an outlier on purpose.
from sklearn.preprocessing import StandardScaler, MinMaxScaler
x = np.array([[10], [20], [30], [40], [100]])
out = pd.DataFrame({
"raw": x.ravel(),
"standard": StandardScaler().fit_transform(x).ravel().round(2),
"minmax": MinMaxScaler().fit_transform(x).ravel().round(2),
})
print(out)
raw standard minmax
0 10 -0.95 0.00
1 20 -0.63 0.11
2 30 -0.32 0.22
3 40 0.00 0.33
4 100 1.90 1.00
In the minmax column, the four normal values are pushed into the bottom third of the range. A distance-based model like KNN would then treat them as almost the same. That is the outlier problem in one printout.
This demo fits on all the data, which is fine for a toy column. In a real project, call scaler.fit(X_train) and then transform both train and test. Fitting on the full dataset lets the test set's mean leak into training. Fitting the scaler on the training rows only is the habit that prevents this leak.
Bias-variance tradeoff you can show in code
A model that is too simple misses the pattern (high bias), and a model that is too complex memorizes noise (high variance), so test error is lowest between the two, as the data-science-interviews theory notes explain.
The same notes give the formula: ExpectedTestError = Variance + Bias² + IrreducibleError (source). Irreducible error is the noise in the data that no model can remove.
The code fits polynomial curves of degree one, four and fifteen to the same noisy sine wave. The random seed is fixed, so every run on your machine gives the same numbers.
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
rng = np.random.RandomState(0)
X = np.sort(rng.rand(40, 1), axis=0)
y = np.sin(2 * np.pi * X).ravel() + rng.normal(0, 0.2, 40)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, random_state=0)
for degree in [1, 4, 15]:
model = make_pipeline(PolynomialFeatures(degree), LinearRegression())
model.fit(X_tr, y_tr)
print(f"degree {degree:>2}: train R2 = {model.score(X_tr, y_tr):.2f}, "
f"test R2 = {model.score(X_te, y_te):.2f}")
Here is the pattern your three printed lines will show:
| Degree | Train R2 | Test R2 | Diagnosis |
|---|---|---|---|
| One (straight line) | Middling | Middling, close to train | Underfit, high bias |
| Four | High | High, close to train | Good fit |
| Fifteen | Near perfect | Far lower, often below zero | Overfit, high variance |
With only twenty training points, the degree-fifteen curve can come very close to every one of them. Between those points it swings wildly, so it misses the test points. R2 is 1 for a perfect fit and 0 if you just predict the average. A negative R2 means the model is worse than predicting the average every time.
How to say it out loud: "The straight line scores low on both sets, so it is too simple. Degree fifteen scores almost perfectly on training but badly on test. That gap means it memorized the noise. Degree four has both scores high and close, so I would pick it, or confirm with cross-validation."
L1 vs L2 regularization: Lasso and Ridge
Lasso (L1) can shrink some weights to exactly zero, which removes features, while Ridge (L2) only makes weights smaller and keeps every feature, according to GeeksforGeeks.
To show it, create data where only a few features matter and the rest are noise:
from sklearn.datasets import make_regression
from sklearn.linear_model import Ridge, Lasso
X, y = make_regression(n_samples=100, n_features=10, n_informative=3,
noise=10, random_state=0)
for model in [LinearRegression(), Ridge(alpha=1.0), Lasso(alpha=1.0)]:
model.fit(X, y)
zeros = np.sum(model.coef_ == 0)
print(type(model).__name__, np.round(model.coef_, 1), "zeros:", zeros)
Plain linear regression and Ridge will report zero exact zeros. Their useless coefficients are small, but none of them disappear. Lasso typically sets several of the useless features to exactly zero and keeps the few real ones, so read the printed zeros count instead of expecting a fixed number. Point at that count during the interview. It shows feature selection happening inside training.
Pros
- Lasso drops useless features, so the model is easier to explain.
- Lasso works well when only a few features matter.
- Ridge stays steady when many features each matter a little.
Cons
- With two correlated features, Lasso tends to keep one and drop the other almost at random.
- Lasso can drop a feature that matters a little.
- Ridge never removes anything, so it gives no feature selection.
Expect the next question: "What else stops overfitting?" The GeeksforGeeks list names early stopping, L1 and L2 regularization, k-fold cross-validation, dropout and simpler models. Regularization is the one you just ran, so mention it first.
Accuracy fails on imbalanced data
On a 95/5 split, a model that always predicts the majority class scores 95% accuracy and still catches no positive cases, which is the example GeeksforGeeks uses.
A DummyClassifier plays that lazy model:
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
y_toy = np.array([0] * 95 + [1] * 5)
X_toy = np.zeros((100, 1))
dummy = DummyClassifier(strategy="most_frequent").fit(X_toy, y_toy)
pred = dummy.predict(X_toy)
print("accuracy :", accuracy_score(y_toy, pred))
print("precision:", precision_score(y_toy, pred, zero_division=0))
print("recall :", recall_score(y_toy, pred))
print("f1 :", f1_score(y_toy, pred, zero_division=0))
accuracy : 0.95
precision: 0.0
recall : 0.0
f1 : 0.0
Write the formulas on the whiteboard: precision = TP/(TP+FP), recall = TP/(TP+FN), and F1 = 2PR/(P+R), the harmonic mean of the two (formulas from GeeksforGeeks). The dummy has no true positives, so every metric built on them falls to zero.
Next, train a real model that pays more attention to the rare class:
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
X, y = make_classification(n_samples=2000, weights=[0.95], random_state=42)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=42)
model = LogisticRegression(class_weight="balanced", max_iter=1000).fit(X_tr, y_tr)
print(classification_report(y_te, model.predict(X_te), digits=2))
In the report, recall for class 1 jumps well above zero. Accuracy usually drops a little, because the model now flags some negatives too. That trade is the whole point: you give up some accuracy to catch the cases you care about.
Which metric to pick depends on which mistake costs more. For fraud detection, choose recall, because a missed fraud costs real money. For spam filtering, choose precision, because a real email lost in the spam folder hurts more than a spam message in the inbox. Moving the decision threshold trades one for the other. A higher threshold raises precision and lowers recall, which the interview notes call the precision-recall tradeoff.
Confusion matrix and ROC-AUC
The confusion matrix counts the four outcomes (TP, FP, FN, TN), and ROC-AUC summarizes how well the model ranks positives above negatives, where 1 is perfect and 0.5 is random, as GeeksforGeeks puts it.
from sklearn.metrics import confusion_matrix, roc_auc_score, average_precision_score
print(confusion_matrix(y_toy, pred))
print("dummy AUC:", roc_auc_score(y_toy, dummy.predict_proba(X_toy)[:, 1]))
proba = model.predict_proba(X_te)[:, 1]
print(confusion_matrix(y_te, model.predict(X_te)))
print("model AUC:", round(roc_auc_score(y_te, proba), 2))
print("model PR-AUC:", round(average_precision_score(y_te, proba), 2))
The first two prints come from the dummy, so their output is fixed:
[[95 0]
[ 5 0]]
dummy AUC: 0.5
Read it line by line. In sklearn, rows are the actual class and columns are the predicted class. The top row says 95 real negatives were all predicted negative, with no false positives. The bottom row says all 5 real positives were predicted negative, so the model has 5 false negatives and no true positives. The AUC of 0.5 means random ranking (scale from GeeksforGeeks), which makes sense for a model that gives every row the same score.
| Cell | Name | Where it is used |
|---|---|---|
| Top left | True negative (TN) | Accuracy only |
| Top right | False positive (FP) | Precision denominator |
| Bottom left | False negative (FN) | Recall denominator |
| Bottom right | True positive (TP) | Top of both precision and recall |
Interview trap: the balanced model's ROC-AUC can look excellent while its PR-AUC is clearly lower. The ROC curve's false positive rate divides by all negatives. When negatives are huge in number, a pile of false positives barely moves it. Precision does not hide them. If you mention this without being asked, you show you have done more than read a definition.
Why do we need train, validation and test splits, and what does k-fold add?
The validation set is used to tune choices, the test set is touched once at the end, and k-fold cross-validation gives a more stable score when data is small, as the theory notes describe.
Split
Hold out a test set first and do not look at it again.
Tune on validation
Compare models, degrees and alpha values on the validation set.
Cross-validate
On small data, rotate the validation part through k folds and average the scores.
Final test
Score the chosen model once on the test set and report that number.
Here is five-fold cross-validation on a small built-in dataset:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
X, y = load_breast_cancer(return_X_y=True)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
scores = cross_val_score(pipe, X, y, cv=5)
print("fold scores:", scores.round(3))
print(f"mean = {scores.mean():.3f}, std = {scores.std():.3f}")
You will see five scores that are close but not equal. The mean is your estimate of real performance. The standard deviation tells you how much to trust it: a large spread means the score depends on which rows landed in which fold. The scaler sits inside the pipeline, so it is refitted on each training fold, which avoids the leakage problem from the scaling section.
Common mistake: tuning on the test set. If you try ten alpha values and keep the one with the best test score, the test set has become a validation set. Your reported score will look better than the model really is, and a sharp interviewer will ask how you chose alpha.
For the easier questions that analyst roles ask, like what a p-value means, use the companion list of ML questions data analyst freshers face. If your campus drive mixes coding and theory, the Infosys SP and DSE interview write-up shows how such rounds run.
Open a notebook today and run the bias-variance snippet with your own random seed. Then write the three printed scores on paper and practise explaining them out loud in under a minute. Next, repeat with the imbalanced-metrics snippet, and read the analyst interview post for the lighter questions.

