Skip to content

Machine Learning Interview Questions for Freshers

40 questions with answers for candidates with Freshers — 27 easy, 13 medium.

What interviewers expect: freshers

Freshers are tested on fundamentals: types of learning, bias-variance, overfitting, common algorithms, preprocessing and metrics like precision and recall. Expect short coding tasks in pandas and scikit-learn and deep questions about your projects, such as why you chose a metric or how you handled missing data. Clear explanations matter as much as correct answers.

This set is weighted towards Classification Models (7), Regression Models (6), Data Preprocessing and Feature Engineering (6), Decision Trees and Ensembles (6).

ML fundamentals and metrics pandas data cleaning scikit-learn pipelines Explaining your projects
Solved at this levelStart practicing
3 QUESTIONS FREESign up 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

What is Naive Bayes and why is it called naive?

Save to ▾
Show answer
Naive Bayes applies Bayes' theorem to compute the probability of each class given the features, assuming features are conditionally independent given the class. That independence assumption is rarely true, hence 'naive', but the model still works well for text classification like spam detection. Variants include Gaussian, Multinomial for word counts and Bernoulli for binary features. It is fast and needs little data.
02

What is the log loss metric and why is it useful?

Save to ▾
Show answer
Log loss, or cross-entropy, is the negative average log of the probability assigned to the true class. It heavily penalises confident wrong predictions, such as predicting 0.99 for an event that does not happen. It evaluates probability quality, not just ranking, so it suits problems where probabilities drive decisions. Lower is better, and a constant base-rate prediction is the baseline to beat.
03

What is R-squared and what is adjusted R-squared?

Save to ▾
Show answer
R-squared is the share of variance in the target explained by the model, 1 - SS_res / SS_tot. It never decreases when you add features, even useless ones. Adjusted R-squared penalises extra features: 1 - (1 - R2)(n - 1)/(n - p - 1), so it only rises if a new feature improves fit more than expected by chance. R-squared can be negative on test data if the model is worse than predicting the mean.
04

How do you extract useful features from a datetime column in pandas?

Save to ▾
Show answer
Convert to datetime and pull out calendar parts. import pandas as pd df['ts'] = pd.to_datetime(df['ts']) df['hour'] = df['ts'].dt.hour df['dow'] = df['ts'].dt.dayofweek df['month'] = df['ts'].dt.month df['is_weekend'] = df['dow'].isin([5, 6]).astype(int) For cyclical features like hour, sine and cosine encoding keeps 23 and 0 close together.
05

How does logistic regression work?

Save to ▾
Show answer
Logistic regression computes a weighted sum of features and passes it through the sigmoid function, 1 / (1 + e^-z), to get a probability between 0 and 1. It is trained by minimising log loss. Coefficients represent change in log-odds per unit of a feature, and exp(coefficient) gives the odds ratio. A threshold, 0.5 by default, converts probabilities into class labels.
06

Explain precision, recall and F1 score.

Save to ▾
Show answer
Precision is TP / (TP + FP): of the cases flagged positive, how many were right. Recall is TP / (TP + FN): of the actual positives, how many were found. F1 is the harmonic mean of the two and is low if either is low. Use precision when false alarms are costly, such as spam filters; use recall when misses are costly, such as cancer screening or fraud.
07

What is feature engineering and why does it matter?

Save to ▾
Show answer
Feature engineering is creating input variables that make patterns easier for a model to learn, using domain knowledge. Examples are extracting day of week from a date, ratios like debt-to-income, rolling averages of past purchases, or text length. On tabular problems good features often improve results more than switching algorithms. Features must use only information available at prediction time.
08

How does gradient boosting work?

Save to ▾
Show answer
Gradient boosting starts with a simple prediction, like the mean, then repeatedly fits a small tree to the negative gradient of the loss, which for MSE is just the residuals. Each tree's output is scaled by a learning rate and added to the ensemble. A lower learning rate with more trees usually generalises better. Any differentiable loss can be used, which makes it flexible.
09

What is regularisation in general and why does it reduce overfitting?

Save to ▾
Show answer
Regularisation adds a constraint or penalty that discourages overly complex models, such as large weights in linear models, deep trees or too many boosting rounds. It trades a little extra bias for a larger drop in variance, so test error falls. Examples include L1 and L2 penalties, dropout in neural networks, early stopping, pruning and limiting tree depth.
10

Tell me about a time your analysis was not used by stakeholders. What did you learn?

Save to ▾
Show answer
Situation: I built eight customer segments, but marketing did not use them. Task: understand why. Action: I met the team and learned the segments were hard to act on and lacked clear names. I reduced them to five, added a one-page profile and suggested campaign ideas for each. Result: two segments were used in the next campaign. I learned to involve users from the start.
11

Your model shows 99 percent training accuracy but 72 percent validation accuracy. What will you do?

Save to ▾
Show answer
This is overfitting. I would first check for leakage or a split mismatch, then simplify the model: add regularisation, reduce depth or features, use early stopping, or prune trees. I would gather more data or use augmentation if possible and use cross-validation to confirm the fix. Plotting learning curves shows whether more data would actually help.
12

How do you choose the number of clusters k?

Save to ▾
Show answer
Common methods are the elbow method, plotting inertia against k and looking for the bend; the silhouette score, which measures how close points are to their own cluster versus the next one; and the gap statistic. Business usability matters too: four clear segments a marketing team can act on are better than nine statistically optimal but confusing ones.
13

Why is feature scaling needed and which algorithms need it?

Save to ▾
Show answer
Scaling puts features on comparable ranges so that one large-valued feature does not dominate distances or gradients. Distance and gradient based models need it: k-NN, k-means, SVM, PCA, linear and logistic regression with regularisation, and neural networks. Tree-based models like random forest and XGBoost split on thresholds, so they are largely unaffected by scaling.
14

A fraud model has 99.6 percent accuracy, but the business says it is useless. Why?

Save to ▾
Show answer
If only 0.4 percent of transactions are fraud, predicting 'not fraud' for everything gives 99.6 percent accuracy and catches nothing. I would switch to recall, precision and PR-AUC, check the confusion matrix, then retrain with class weights or resampling and tune the threshold so the fraud team gets a manageable number of alerts with high recall.
15

How do you interpret a coefficient in a multiple linear regression?

Save to ▾
Show answer
A coefficient is the expected change in the target for a one-unit increase in that feature, holding other features constant. For example, a coefficient of 2,500 on 'area in square metres' means each extra square metre adds about 2,500 to price. Interpretation breaks down with multicollinearity or when features are scaled, so report units clearly and check stability.
16

What is MLOps?

Save to ▾
Show answer
MLOps applies DevOps practices to machine learning: version control for code, data and models, automated training pipelines, testing, CI/CD for model releases, model registries, monitoring and automated retraining. Its aim is to move models from notebooks to production reliably and keep them healthy. Common tools are MLflow, DVC, Airflow, Kubeflow, and cloud platforms like SageMaker, Vertex AI and Azure ML.
17

How does ordinary least squares find the regression coefficients?

Save to ▾
Show answer
OLS chooses coefficients that minimise the sum of squared residuals between actual and predicted values. It has a closed-form solution, beta = (X^T X)^-1 X^T y, when X^T X is invertible. For very large or ill-conditioned data, gradient descent or a pseudo-inverse is used instead. Squaring errors penalises large mistakes heavily, which makes OLS sensitive to outliers.
18

Tell me about a time you took a model from notebook to production.

Save to ▾
Show answer
Situation: our demand model ran only in a notebook on my laptop. Task: make it run daily for 300 stores. Action: I refactored it into modules with a scikit-learn pipeline, added tests and input checks, containerised it with Docker and scheduled it with Airflow writing forecasts to the warehouse. Result: forecasts became available by 6 a.m. daily without manual work, and failures triggered alerts instead of silent gaps.
19

What is a confusion matrix?

Save to ▾
Show answer
A confusion matrix is a table of actual versus predicted classes. For binary problems it has true positives, false positives, true negatives and false negatives. From it you derive precision, recall, specificity and accuracy. For example, in fraud detection a false negative is a missed fraud and a false positive is a genuine customer blocked, and these usually have very different costs.
20

What is the difference between standardisation and normalisation?

Save to ▾
Show answer
Standardisation (StandardScaler) transforms a feature to mean 0 and standard deviation 1 using (x - mean) / std; it keeps outliers but does not bound values. Min-max normalisation (MinMaxScaler) rescales to a fixed range such as 0 to 1 and is sensitive to outliers. RobustScaler uses median and IQR and is better when outliers are present. Always fit the scaler on training data only.
21

How do you handle missing values in a dataset?

Save to ▾
Show answer
First understand why values are missing: completely at random, at random, or not at random. Options are dropping rows or columns with heavy missingness, simple imputation with mean, median or mode, model-based imputation like KNNImputer or IterativeImputer, or a separate 'missing' category. Adding a missing-indicator column often helps because missingness itself can be predictive, such as income left blank.
22

Tune a pipeline with GridSearchCV.

Save to ▾
Show answer
from sklearn.model_selection import GridSearchCV params = {'clf__C': [0.01, 0.1, 1, 10], 'clf__penalty': ['l2']} gs = GridSearchCV(pipe, params, cv=5, scoring='roc_auc', n_jobs=-1) gs.fit(X_train, y_train) print(gs.best_params_, gs.best_score_) best = gs.best_estimator_ The step__param naming targets parameters inside a pipeline step.
23

Apply PCA and check explained variance.

Save to ▾
Show answer
from sklearn.decomposition import PCA import numpy as np pca = PCA().fit(Xs) cum = np.cumsum(pca.explained_variance_ratio_) n = np.argmax(cum >= 0.95) + 1 print(n, 'components explain 95 percent') X_red = PCA(n_components=0.95).fit_transform(Xs) Passing a float to n_components keeps enough components to reach that variance.
24

Explain gradient descent and the role of the learning rate.

Save to ▾
Show answer
Gradient descent minimises a loss by repeatedly moving parameters in the direction of the negative gradient: w = w - learning_rate * gradient. The learning rate controls step size. Too high and the loss oscillates or diverges; too low and training is very slow or gets stuck. Variants include batch, stochastic and mini-batch gradient descent, plus adaptive optimisers like Adam.
25

Visualise a small decision tree and its rules.

Save to ▾
Show answer
from sklearn.tree import DecisionTreeClassifier, export_text, plot_tree import matplotlib.pyplot as plt dt = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X_train, y_train) print(export_text(dt, feature_names=list(X_train.columns))) plot_tree(dt, feature_names=X_train.columns, filled=True) plt.show() Shallow trees are a good way to explain rules to business teams.
26

How do you work with data engineers and software engineers on an ML project?

Save to ▾
Show answer
I agree early on interfaces: which tables or APIs provide features, the input and output schema, latency targets and who owns monitoring. I share a short design document and keep my code in the same repository standards as theirs, with tests and reviews. In my last project weekly syncs with data engineering helped us fix a late-arriving data issue before launch rather than after.
27

Fit a linear regression in scikit-learn and print RMSE and R-squared.

Save to ▾
Show answer
from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score import numpy as np lr = LinearRegression().fit(X_train, y_train) pred = lr.predict(X_test) print('RMSE', np.sqrt(mean_squared_error(y_test, pred))) print('R2', r2_score(y_test, pred)) print(dict(zip(X_train.columns, lr.coef_))) Newer scikit-learn versions also provide root_mean_squared_error directly.
28

How do you explain data cleaning decisions to a non-technical manager?

Save to ▾
Show answer
I avoid jargon and tie each decision to its effect on business results. For example: 'About 8 percent of orders had missing delivery times. Instead of deleting them, which would hide slow regions, I filled them using similar orders and flagged them, so the model still learns from those regions.' I keep a short log of decisions so they can be reviewed later and repeated.
29

Plot a learning curve in scikit-learn.

Save to ▾
Show answer
from sklearn.model_selection import LearningCurveDisplay import numpy as np LearningCurveDisplay.from_estimator(model, X, y, cv=5, train_sizes=np.linspace(0.1, 1.0, 6), scoring='roc_auc', n_jobs=-1) plt.show() A persistent gap between curves suggests more data or regularisation; two low curves suggest a richer model or better features.
30

How do you check regression residuals visually in Python?

Save to ▾
Show answer
import matplotlib.pyplot as plt res = y_test - pred fig, ax = plt.subplots(1, 2, figsize=(10, 4)) ax[0].scatter(pred, res, s=8); ax[0].axhline(0, color='red') ax[0].set_xlabel('Predicted'); ax[0].set_ylabel('Residual') ax[1].hist(res, bins=40) plt.show() A funnel shape suggests heteroscedasticity; a curve suggests a missing non-linear term.
31

How do you implement simple gradient descent for linear regression in NumPy?

Save to ▾
Show answer
Compute predictions, the gradient of MSE, and update weights in a loop. import numpy as np w = np.zeros(X.shape[1]); b = 0.0; lr = 0.01 for _ in range(1000): err = X @ w + b - y w -= lr * (2 / len(y)) * (X.T @ err) b -= lr * (2 / len(y)) * err.sum() Scale features first or the loop converges slowly.
32

How does a decision tree decide where to split?

Save to ▾
Show answer
At each node the tree tries candidate features and thresholds and picks the split that most reduces impurity in the child nodes. For classification, impurity is measured by Gini or entropy; for regression, by variance or MSE. The process repeats recursively until a stopping rule such as max_depth, min_samples_leaf or pure leaves is reached. This greedy approach is fast but not globally optimal.
33

Explain bagging and how a random forest uses it.

Save to ▾
Show answer
Bagging trains many models on bootstrap samples, random samples with replacement, and averages their predictions to reduce variance. A random forest adds feature randomness: each split considers only a random subset of features, controlled by max_features. This de-correlates the trees, so averaging helps more. Out-of-bag samples, about 37 percent left out per tree, give a free validation estimate.
34

You must build a spam classifier quickly with limited compute. What do you choose?

Save to ▾
Show answer
I would use TF-IDF features with a Multinomial Naive Bayes or linear model like logistic regression or LinearSVC. They train in seconds, handle high-dimensional sparse text well and give strong baselines. I would evaluate precision carefully because blocking genuine mail is costly. Only if this is not good enough would I try fine-tuning a small transformer model.
35

How does k-means clustering work?

Save to ▾
Show answer
k-means picks k initial centroids, assigns each point to its nearest centroid, recomputes each centroid as the mean of its points, and repeats until assignments stop changing. It minimises within-cluster sum of squares (inertia). It needs k in advance, scaled features, and assumes roughly spherical, similar-sized clusters. k-means++ initialisation and multiple runs with n_init reduce bad starting points.
36

Print a confusion matrix and classification report in scikit-learn.

Save to ▾
Show answer
from sklearn.metrics import confusion_matrix, classification_report pred = clf.predict(X_test) print(confusion_matrix(y_test, pred)) print(classification_report(y_test, pred, digits=3)) The report shows precision, recall, F1 and support per class plus macro and weighted averages. ConfusionMatrixDisplay.from_estimator draws it as a plot.
37

Compute permutation importance on validation data.

Save to ▾
Show answer
from sklearn.inspection import permutation_importance import pandas as pd r = permutation_importance(model, X_val, y_val, n_repeats=10, scoring='roc_auc', random_state=42, n_jobs=-1) imp = pd.Series(r.importances_mean, index=X_val.columns) print(imp.sort_values(ascending=False)) Near-zero or negative values mean the feature adds little on unseen data.
38

Write a unit test for a model prediction function.

Save to ▾
Show answer
import joblib, pandas as pd def test_predict_shape_and_range(): model = joblib.load('model_v1.joblib') df = pd.DataFrame([{'age': 30, 'income': 50000.0, 'city': 'Pune'}, {'age': 45, 'income': 0.0, 'city': 'UnknownCity'}]) p = model.predict_proba(df)[:, 1] assert p.shape == (2,) assert ((p >= 0) & (p <= 1)).all() Run with pytest in CI so broken artifacts never reach production.
39

Why do we split data into training, validation and test sets?

Save to ▾
Show answer
The training set fits model parameters, the validation set is used to choose hyperparameters and compare models, and the test set gives a final unbiased estimate of performance. If you tune on the test set, its score becomes optimistic because information has leaked into model choices. A common split is 70/15/15, or train/test plus cross-validation on the training part.
40

Train a random forest and show feature importances in scikit-learn.

Save to ▾
Show answer
from sklearn.ensemble import RandomForestClassifier import pandas as pd rf = RandomForestClassifier(n_estimators=300, min_samples_leaf=2, n_jobs=-1, random_state=42, oob_score=True) rf.fit(X_train, y_train) print('OOB', rf.oob_score_) imp = pd.Series(rf.feature_importances_, index=X_train.columns) print(imp.sort_values(ascending=False).head(10))

Frequently asked questions

What is asked in Machine Learning interviews for Freshers?

Freshers are tested on fundamentals: types of learning, bias-variance, overfitting, common algorithms, preprocessing and metrics like precision and recall. Expect short coding tasks in pandas and scikit-learn and deep questions about your projects, such as why you chose a metric or how you handled missing data. Clear explanations matter as much as correct answers.

How many questions should I practise before a Machine Learning interview?

Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.

Which topics matter most for Freshers?

Focus first on ML fundamentals and metrics, pandas data cleaning, scikit-learn pipelines, Explaining your projects.