Skip to content

Easy Machine Learning Interview Questions

54 easy questions with answers. Definitions and fundamentals every candidate must answer quickly and correctly.

Topics in the easy set

Classification Models: 11 ML Fundamentals: 10 Data Preprocessing and Feature Engineering: 8 Regression Models: 6 Decision Trees and Ensembles: 6 Model Evaluation and Tuning: 5 MLOps and Deployment: 5 Clustering and Dimensionality Reduction: 3
Solved — easyStart 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 machine learning and how is it different from traditional programming?

Save to ▾
Show answer
Machine learning is a way of building programs that learn patterns from data instead of following hand-written rules. In traditional programming you give rules and data to get answers; in ML you give data and answers to get the rules, stored as model parameters. For example, a spam filter learns which word patterns indicate spam from labelled emails rather than from a fixed keyword list.
02

Explain supervised, unsupervised and reinforcement learning with one example each.

Save to ▾
Show answer
Supervised learning trains on labelled data, such as predicting house prices from past sales. Unsupervised learning finds structure in unlabelled data, such as grouping customers into segments with k-means. Reinforcement learning trains an agent through rewards and penalties from an environment, such as a program learning to play a game. Semi-supervised and self-supervised learning sit between these when labels are scarce.
03

What is the difference between a regression and a classification problem?

Save to ▾
Show answer
Regression predicts a continuous number, such as sales next month or delivery time in minutes. Classification predicts a discrete category, such as fraud or not fraud, or one of five product types. The choice decides the loss function and metrics: regression uses MSE, MAE or R-squared, while classification uses log loss, accuracy, precision, recall or AUC.
04

What are overfitting and underfitting, and how do you detect them?

Save to ▾
Show answer
Overfitting is when a model memorises training noise and performs much worse on unseen data. Underfitting is when the model is too simple to capture the pattern, so both training and validation scores are poor. Detect them by comparing training and validation metrics or plotting learning curves. A large gap means overfitting; two low, close scores mean underfitting.
05

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.
06

What is the difference between parameters and hyperparameters?

Save to ▾
Show answer
Parameters are learned from data during training, such as the weights of a linear regression or split thresholds of a tree. Hyperparameters are set before training and control the learning process, such as learning rate, max_depth, number of trees or regularisation strength C. Hyperparameters are tuned with validation data using grid search, random search or Bayesian optimisation.
07

How do you set up a basic train-test split with scikit-learn?

Save to ▾
Show answer
Use train_test_split with a fixed random_state for reproducibility and stratify for classification so class ratios match. from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y ) For time series, avoid random splits and use the most recent period as the test set.
08

Write a minimal scikit-learn workflow to train and evaluate a model.

Save to ▾
Show answer
The fit, predict, score pattern is the same for almost every estimator. from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score model = LogisticRegression(max_iter=1000) model.fit(X_train, y_train) preds = model.predict(X_test) print(accuracy_score(y_test, preds)) Use predict_proba when you need probabilities for thresholds or ranking.
09

How would you build a quick baseline before trying complex models?

Save to ▾
Show answer
Use a DummyClassifier or DummyRegressor to see the score of a trivial guess, then a simple model. from sklearn.dummy import DummyClassifier base = DummyClassifier(strategy='most_frequent') base.fit(X_train, y_train) print(base.score(X_test, y_test)) Any real model must clearly beat this number; otherwise the features carry little signal.
10

Why do you want to work as a machine learning engineer?

Save to ▾
Show answer
I enjoy turning data into decisions that people actually use. During my projects I liked the full cycle: framing the problem, cleaning messy data, comparing models and explaining results. ML engineering lets me combine coding with statistics and see measurable business impact, such as reducing manual review time. I also want to keep growing into deployment and monitoring, which I am already practising with FastAPI and Docker.
11

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.
12

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.
13

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.
14

What is one-hot encoding and when can it cause problems?

Save to ▾
Show answer
One-hot encoding turns a categorical column into binary columns, one per category, so models do not assume order. It causes problems with high-cardinality features like city or product ID, creating thousands of sparse columns and higher memory and overfitting risk. Alternatives are target encoding, frequency encoding, hashing, or grouping rare categories into 'Other'. Use handle_unknown='ignore' for unseen categories.
15

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.
16

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.
17

How do you find and remove duplicate rows and check missing values in pandas?

Save to ▾
Show answer
Quick data-quality checks before modelling: print(df.isna().sum().sort_values(ascending=False)) print(df.duplicated().sum()) df = df.drop_duplicates() df['age'] = df['age'].fillna(df['age'].median()) For modelling, do the median imputation inside a pipeline instead so the value is learned only from training data.
18

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.
19

What are the assumptions of linear regression?

Save to ▾
Show answer
Linear regression assumes a linear relationship between features and target, independent errors, constant error variance (homoscedasticity), normally distributed errors for valid inference, and little multicollinearity among features. Violations mainly hurt confidence intervals and coefficient interpretation more than raw predictions. Check them with residual plots, Q-Q plots, the Durbin-Watson test and VIF.
20

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.
21

Compare MAE, MSE and RMSE as regression metrics.

Save to ▾
Show answer
MAE is the average absolute error, easy to explain and robust to outliers. MSE averages squared errors and punishes large errors heavily, which suits cases where big misses are costly. RMSE is the square root of MSE, so it is in the same unit as the target. If RMSE is much higher than MAE, a few large errors are present. MAPE is useful for percentage errors but fails near zero.
22

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.
23

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.
24

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.
25

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.
26

Why is logistic regression called regression if it is used for classification?

Save to ▾
Show answer
It models a continuous quantity, the log-odds of the positive class, as a linear function of features, which is regression in the statistical sense. The classification comes only when you apply a threshold to the predicted probability. This is why it outputs well-calibrated probabilities more naturally than many other classifiers.
27

Explain the k-nearest neighbours algorithm and its weaknesses.

Save to ▾
Show answer
k-NN predicts by finding the k closest training points and taking a majority vote for classification or the average for regression. It has no training phase but is slow at prediction on large data, needs feature scaling, suffers from the curse of dimensionality and is sensitive to irrelevant features. Small k overfits, large k underfits; choose k with cross-validation.
28

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.
29

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.
30

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.
31

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.
32

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.
33

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.
34

How do you plot an ROC curve and get AUC in scikit-learn?

Save to ▾
Show answer
from sklearn.metrics import roc_auc_score, RocCurveDisplay import matplotlib.pyplot as plt proba = clf.predict_proba(X_test)[:, 1] print('AUC', roc_auc_score(y_test, proba)) RocCurveDisplay.from_predictions(y_test, proba) plt.show() Pass probabilities or decision scores, not hard labels, otherwise the curve has only one point.
35

How do you keep learning new ML techniques while working full time?

Save to ▾
Show answer
I set a small weekly routine: one paper summary or library release note, and one hands-on experiment on a public dataset. I follow scikit-learn and LightGBM release notes, and I rebuild ideas on a small problem before suggesting them at work. Recently I tried TunedThresholdClassifierCV and later used it to replace a manual threshold script in our project.
36

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.
37

What is the difference between Gini impurity and entropy?

Save to ▾
Show answer
Gini impurity is 1 - sum of p squared and measures the chance of misclassifying a random sample. Entropy is - sum of p log p and comes from information theory; the reduction is called information gain. Both usually produce very similar trees. Gini is slightly faster because it avoids logarithms, which is why it is the scikit-learn default.
38

Why do single decision trees overfit and how do you control it?

Save to ▾
Show answer
An unrestricted tree keeps splitting until leaves are pure, memorising noise. Control it with pre-pruning hyperparameters like max_depth, min_samples_split, min_samples_leaf and max_leaf_nodes, or with post-pruning through cost-complexity pruning using ccp_alpha. In practice ensembles such as random forests or boosting are used to reduce the variance of single trees.
39

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.
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))
41

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.
42

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.
43

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.
44

Run k-means and plot the elbow and silhouette scores.

Save to ▾
Show answer
from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score Xs = StandardScaler().fit_transform(X) for k in range(2, 10): km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(Xs) print(k, round(km.inertia_), round(silhouette_score(Xs, km.labels_), 3)) Look for the bend in inertia and a high silhouette value.
45

What is k-fold cross-validation and why is it better than a single split?

Save to ▾
Show answer
k-fold cross-validation splits training data into k folds, trains on k-1 folds and validates on the remaining one, repeating k times so every row is validated once. Averaging the k scores gives a more stable estimate than one random split and shows variance across folds. Five or ten folds are common. Use StratifiedKFold for classification and GroupKFold when rows from one user must stay together.
46

What is a holdout set and why should it be touched only once?

Save to ▾
Show answer
A holdout or test set is kept aside for the final evaluation after all model and hyperparameter choices are done. If you check it repeatedly and adjust the model, you are indirectly tuning on it, so its score becomes optimistic. Use cross-validation or a separate validation set for decisions, and report the holdout score once as the realistic estimate.
47

Run stratified 5-fold cross-validation with multiple metrics.

Save to ▾
Show answer
from sklearn.model_selection import StratifiedKFold, cross_validate cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) res = cross_validate(pipe, X, y, cv=cv, scoring=['roc_auc', 'average_precision', 'f1'], n_jobs=-1) for k in ['test_roc_auc', 'test_average_precision', 'test_f1']: print(k, res[k].mean().round(3), res[k].std().round(3))
48

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.
49

How do you explain the precision-recall trade-off to a business manager?

Save to ▾
Show answer
I use their own example. For fraud: 'If we flag more transactions, we catch more fraud, which is recall, but more genuine customers get blocked, which hurts precision. Here is a table of what each threshold means per day: frauds caught, customers disturbed, reviews needed.' Then we choose the threshold together based on cost. Managers relate much better to counts than to percentages.
50

What does it mean to deploy a machine learning model?

Save to ▾
Show answer
Deployment makes a trained model available to produce predictions for real users or systems. It can be batch, scoring data on a schedule and writing results to a table, or real-time, serving predictions through a REST API, or streaming, scoring events as they arrive. It includes packaging the model with its preprocessing, setting up infrastructure, logging, monitoring and a retraining plan.
51

How do you save and load a scikit-learn model?

Save to ▾
Show answer
Save the whole fitted pipeline so preprocessing travels with the model. import joblib joblib.dump(pipe, 'model_v1.joblib') pipe = joblib.load('model_v1.joblib') preds = pipe.predict(new_df) Load with the same scikit-learn version used for training, and never load pickle or joblib files from untrusted sources because they can execute code. ONNX or skops are safer portable options.
52

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.
53

Why containerise an ML model with Docker?

Save to ▾
Show answer
Docker packages the model, code, Python version and exact library versions into one image that runs the same on a laptop, a test server or Kubernetes. This removes 'works on my machine' problems, especially with scikit-learn version mismatches. Images can be scanned, versioned and deployed through CI/CD, and scaled horizontally behind a load balancer on platforms like Kubernetes, ECS or Cloud Run.
54

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.

Frequently asked questions

Who should practise easy Machine Learning questions?

Freshers and career switchers should start here, and experienced candidates should skim them the day before an interview.

How should I practise these?

Answer each question aloud before opening the answer, mark it as solved only when your answer matches the key idea, and save misses to Last-Minute Revision.

Other difficulty levels