36 practice questions with answers for Machine Learning interviews in Nagpur.
Machine Learning jobs in Nagpur
Nagpur's MIHAN SEZ hosts IT-services and BFSI delivery centres, giving central India a steady market for data and QA roles. Interviews are usually service-company style, with aptitude, technical and HR rounds.
Below are 36 questions that match the mix of service, product and domain employers hiring machine learning engineers in Nagpur.
Solved for NagpurStart 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
Find the most similar items using cosine similarity.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.neighbors import NearestNeighbors
X = TfidfVectorizer(min_df=2).fit_transform(df['title'])
nn = NearestNeighbors(n_neighbors=6, metric='cosine').fit(X)
dist, idx = nn.kneighbors(X[0])
print(df['title'].iloc[idx[0][1:]].tolist())
The first neighbour is the item itself, so skip it.
02
The fraud team can only review 500 alerts a day. How do you set the threshold?
Instead of 0.5, rank transactions by predicted probability and pick the threshold that yields about 500 alerts per day on recent data. Then report precision and recall at that cut-off, or precision at k. I would monitor daily alert volume because drift can change it, and recompute the threshold periodically. If cost data exists, I would choose the threshold that maximises expected savings.
03
Explain gradient descent and the role of the learning rate.
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.
04
Your training loss is not decreasing at all. What could be wrong?
Common causes are a learning rate that is too high or too low, unscaled features, a bug in labels or feature alignment, wrong loss for the task, or data that has been shuffled away from its labels. I would try overfitting a tiny subset first; if the model cannot even fit 50 rows, there is a bug. Then check scaling, learning rate and gradient values.
05
What is target encoding and how do you avoid leakage with it?
Target encoding replaces each category with the mean target value for that category, which works well for high-cardinality features. It leaks if computed on the full data because each row sees its own label. Avoid this by computing encodings out-of-fold within cross-validation and adding smoothing toward the global mean for rare categories. scikit-learn 1.3+ has TargetEncoder with built-in cross-fitting.
06
Your dataset has a city column with 2,000 unique values. How will you encode it?
One-hot would create 2,000 sparse columns, so I would first group rare cities below a frequency threshold into 'Other'. Then options are frequency encoding, out-of-fold target encoding, or mapping cities to useful attributes such as tier, state or population. For boosting models like CatBoost or LightGBM, native categorical handling also works well. I would compare options with cross-validation.
07
Use statsmodels to get p-values for regression coefficients.
import statsmodels.api as sm
Xc = sm.add_constant(X_train)
ols = sm.OLS(y_train, Xc).fit()
print(ols.summary())
The summary shows coefficients, standard errors, p-values, confidence intervals, R-squared and diagnostics. scikit-learn focuses on prediction and does not report p-values, so statsmodels is preferred for inference.
As the number of features grows, data becomes sparse in the feature space, distances between points become similar, and the amount of data needed to generalise grows rapidly. Distance-based methods like k-NN and k-means suffer most. Remedies include feature selection, dimensionality reduction such as PCA, regularisation and collecting more data. Text and genomics data often face this problem.
Isolation Forest builds random trees that split on random features and random thresholds. Anomalies are few and different, so they get isolated in fewer splits, giving shorter average path lengths. The anomaly score comes from that path length. It is fast, works without labels and scales well. The contamination parameter sets the expected share of anomalies and determines the threshold.
10
What is regularisation in general and why does it reduce overfitting?
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.
11
What is one-hot encoding and when can it cause problems?
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.
import lightgbm as lgb
m = lgb.LGBMClassifier(n_estimators=5000, learning_rate=0.05,
num_leaves=31, subsample=0.8, subsample_freq=1, colsample_bytree=0.8)
m.fit(X_train, y_train, eval_set=[(X_val, y_val)],
eval_metric='auc', callbacks=[lgb.early_stopping(100)])
print(m.best_iteration_)
The large n_estimators is only an upper limit; early stopping picks the real number.
13
What should you monitor for a model in production?
Monitor service health such as latency, error rate and throughput; input data quality such as missing values, schema changes and out-of-range values; feature and prediction distribution drift; and real performance once labels arrive. Also track business KPIs the model influences. Set alerts with thresholds and owners, and keep a dashboard so issues are found before users report them.
14
How do you approach a time series forecasting problem differently from normal regression?
Time series data is ordered and autocorrelated, so random splits leak future information. I use time-based splits or TimeSeriesSplit, create lag and rolling-window features from past values only, and handle trend and seasonality. Baselines like last value or seasonal naive come first. Models range from ARIMA and Prophet to gradient boosting on lag features.
15
What is a loss function? Name common ones for regression and classification.
A loss function measures how wrong a prediction is for one example, and training minimises its average over the data. Regression commonly uses mean squared error, mean absolute error or Huber loss, which is robust to outliers. Classification uses log loss, also called cross-entropy, and hinge loss for SVMs. The choice should reflect the business cost of errors.
16
Validation AUC is 0.99 on a loan default model. What do you suspect?
Such a high score on a hard problem usually signals leakage. I would check feature importances for a suspiciously dominant feature, look for fields recorded after the loan outcome such as collection status, verify preprocessing was fit only on training data, and check for duplicate customers across train and test. Then re-run with a time-based split to confirm a realistic score.
17
How do you select the top k features using mutual information in scikit-learn?
SelectKBest with mutual_info_classif captures non-linear relationships, unlike plain correlation.
from sklearn.feature_selection import SelectKBest, mutual_info_classif
sel = SelectKBest(score_func=mutual_info_classif, k=20)
X_new = sel.fit_transform(X_train, y_train)
print(X_train.columns[sel.get_support()])
Put the selector inside a pipeline so selection is redone in each CV fold.
18
What is heteroscedasticity and why does it matter?
Heteroscedasticity means the variance of residuals changes with the level of the prediction, such as errors growing for expensive houses. Predictions remain unbiased, but standard errors and p-values become unreliable. Detect it with a residuals versus fitted plot or the Breusch-Pagan test. Fixes include log-transforming the target, weighted least squares, or robust standard errors.
19
How do one-vs-rest and multinomial approaches differ for multiclass classification?
One-vs-rest trains one binary classifier per class against all others and picks the highest score; it is simple but probabilities may not sum to one. Multinomial (softmax) logistic regression models all classes jointly with a single loss, giving consistent probabilities. For metrics, use macro averaging to treat classes equally or weighted averaging to account for class frequency.
20
How do you create polynomial features with regularisation in a pipeline?
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
model = make_pipeline(
PolynomialFeatures(degree=2, include_bias=False),
StandardScaler(),
Ridge(alpha=1.0)
)
model.fit(X_train, y_train)
Tune degree and alpha together with GridSearchCV to avoid overfitting.
21
When should you use TimeSeriesSplit or GroupKFold instead of normal k-fold?
Use TimeSeriesSplit when data is ordered in time, so each validation fold comes after its training data and no future information leaks back. Use GroupKFold when multiple rows belong to the same entity, such as several visits per patient, so the same entity never appears in both train and validation. Normal k-fold in these cases gives over-optimistic scores.
22
How does ordinary least squares find the regression coefficients?
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.
23
A product team wants 'similar products' recommendations with no purchase labels. How would you start?
I would build product embeddings from content: TF-IDF or sentence embeddings of titles and descriptions, plus category and price features. Then use cosine similarity with nearest-neighbour search, such as scikit-learn NearestNeighbors or an approximate index like FAISS for large catalogues. I would review samples with the product team and later add co-view or co-purchase signals once collected.
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.
25
Why do single decision trees overfit and how do you control it?
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.
26
How do you create lag and rolling features for a sales forecasting model in pandas?
Sort by item and date, then shift so features use only past values.
df = df.sort_values(['item', 'date'])
g = df.groupby('item')['sales']
df['lag_7'] = g.shift(7)
df['roll_mean_28'] = g.transform(lambda s: s.shift(1).rolling(28).mean())
The shift before rolling prevents the current day's sales from leaking into its own feature.
A learning curve plots training and validation scores against training set size; if both converge at a low score the model underfits, and if a gap remains, more data may help. A validation curve plots scores against one hyperparameter, such as max_depth, showing where overfitting starts. Both help decide whether to collect data, add features or change complexity.
28
What are overfitting and underfitting, and how do you detect them?
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.
29
What are shadow deployment and canary release for models?
In shadow deployment the new model receives a copy of live traffic and its predictions are logged but not used, so you can compare it with the current model safely. In a canary release a small share of real traffic, such as 5 percent, is served by the new model, and the share grows if metrics stay healthy. Both reduce the risk of a bad model affecting all users.
30
What is the difference between PCA and t-SNE or UMAP?
PCA is a linear method that preserves global variance, is fast, deterministic and can transform new data, so it is used for preprocessing. t-SNE and UMAP are non-linear methods that preserve local neighbourhoods, producing good 2D visualisations of clusters. t-SNE distances between clusters are not meaningful. UMAP is faster, keeps more global structure and can transform new points.
31
How do you tune the alpha of Ridge regression using cross-validation?
RidgeCV tests many alphas efficiently; scale features first.
from sklearn.linear_model import RidgeCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
import numpy as np
m = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 3, 30)))
m.fit(X_train, y_train)
print(m[-1].alpha_)
LassoCV and ElasticNetCV work the same way.
32
Tell me about a time your analysis was not used by stakeholders. What did you learn?
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.
Start with the right metrics, such as PR-AUC, recall at fixed precision or F1, not accuracy. Then use class_weight='balanced', resampling like random undersampling or SMOTE applied only on training folds, and threshold tuning based on business cost. Boosting models with scale_pos_weight also help. Stratified splits keep class ratios consistent across folds.
34
XGBoost validation loss starts rising after 300 rounds while training loss keeps falling. What do you do?
That is overfitting beyond about 300 rounds. I would use early stopping with a patience such as 50 rounds on a validation set so training stops at the best iteration, then lower the learning rate, reduce max_depth, add subsample and colsample_bytree below 1, and increase min_child_weight or lambda. The final model is refit using the best iteration count found.
Principal Component Analysis finds new orthogonal axes, the principal components, that capture maximum variance in the data. It works by computing eigenvectors of the covariance matrix, or via SVD, after centring and usually standardising the data. Keeping the top components that explain, say, 95 percent of variance reduces dimensions, removes correlation and speeds up models, but the components are harder to interpret.
Few big employers listed in Nagpur?
Many Nagpur candidates also apply to teams in Pune and to remote or hybrid roles. Practise the Pune set as well.
Which companies hire Machine Learning professionals in Nagpur?
Companies with large offices in Nagpur include many IT services and product firms. Use their company pages below to practise employer-specific sets.
Are Machine Learning interviews in Nagpur different from other cities?
The questions depend more on the company than the city. Nagpur's mix of employers decides the style: Interviews are usually service-company style, with aptitude, technical and HR rounds
How do I find Machine Learning jobs in Nagpur?
Shortlist companies with Nagpur offices, keep your CV focused on Machine Learning projects, apply on company career pages and job portals with the Nagpur filter, and practise the questions on this page before each interview.