Skip to content

TCS Machine Learning Interview Questions & Answers

Curated interview practice questions with answers. These are practice scenarios, not a verified list of past interview questions.

About TCS hiring for Machine Learning roles

Tata Consultancy Services is a Tata Group company and one of the largest IT services and consulting firms in the world. It delivers application development, testing, cloud, data and analytics services to clients in banking, retail, manufacturing and other industries. In India it hires freshers and experienced staff for software testing, data engineering, BI reporting and analytics roles across its delivery centres.

For Machine Learning roles, this TCS practice set focuses most on Decision Trees and Ensembles (6), Classification Models (5), ML Fundamentals (4), Data Preprocessing and Feature Engineering (3). It has 13 easy, 16 medium, 1 hard questions, so you can start easy and work up to the harder ones.

Company type
IT services
Headquarters
Mumbai, India
Main India offices
Mumbai, Chennai, Pune, Bengaluru, Hyderabad

TCS Machine Learning interview process

  1. TCS NQT online assessment (aptitude + coding)
  2. Technical interview
  3. Managerial round
  4. HR round

Typical pattern based on public candidate experiences. Rounds vary by role, team and year.

Solved for TCSStart 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 data leakage? Give two examples.

Save to ▾
Show answer
Data leakage is when information not available at prediction time gets into training, giving falsely high validation scores. Example one: fitting a scaler or imputer on the full dataset before splitting. Example two: using a feature created after the event, such as 'refund issued' when predicting fraud. Prevent it with pipelines, time-aware splits and checking each feature's timestamp.
02

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

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

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

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

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))
07

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

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

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

A new model version performs badly right after release. How do you handle it?

Save to ▾
Show answer
Roll back immediately to the previous version from the model registry, which should be a one-step action. Then investigate: compare the input features served with those used in validation, check for training-serving skew, version mismatches or a wrong artifact. Add the failure case to automated pre-release checks, and use canary or shadow releases next time so issues affect only a small share of traffic.
11

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

What is polynomial regression and what risk does it carry?

Save to ▾
Show answer
Polynomial regression adds powers and interaction terms of features, such as x squared and x1 times x2, so a linear model can fit curves. It is still linear in its coefficients. The main risk is overfitting at high degrees, plus wild behaviour outside the training range. Use cross-validation to choose the degree, scale features, and combine it with Ridge regularisation.
13

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

Marketing wants customer segments for campaigns. How do you approach it?

Save to ▾
Show answer
I would agree on the purpose first, such as retention or upsell. Then build RFM features (recency, frequency, monetary) plus category preferences, log-transform skewed values and scale them. I would try k-means for k between 3 and 8, use silhouette and business review to pick k, profile each segment and give them clear names. Finally, test segment-based campaigns against a control group.
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

What is the bias-variance trade-off?

Save to ▾
Show answer
Bias is error from overly simple assumptions, which causes underfitting. Variance is error from sensitivity to the particular training sample, which causes overfitting. Increasing model complexity usually lowers bias but raises variance. The goal is the complexity that minimises total test error. For example, a linear model on curved data has high bias, while a very deep unpruned tree has high variance.
17

Explain the bias in AUC when classes are extremely imbalanced, with a numeric intuition.

Save to ▾
Show answer
With 100 fraud and 100,000 genuine cases, a false positive rate of 1 percent looks tiny on the ROC curve, but it means 1,000 false alerts versus at most 100 true ones, so precision is below 10 percent. ROC-AUC can be 0.97 while the model is impractical. Precision-recall curves expose this because precision directly depends on the count of false positives.
18

Serve a scikit-learn model with FastAPI.

Save to ▾
Show answer
from fastapi import FastAPI from pydantic import BaseModel import joblib, pandas as pd app = FastAPI() model = joblib.load('model_v1.joblib') class Item(BaseModel): age: int income: float city: str @app.post('/predict') def predict(item: Item): df = pd.DataFrame([item.model_dump()]) return {'score': float(model.predict_proba(df)[0, 1])} Run it with: uvicorn app:app --host 0.0.0.0 --port 8000
19

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

Describe a project where you improved a model's performance significantly.

Save to ▾
Show answer
Situation: a product-return prediction model had 0.68 AUC with logistic regression. Task: improve it for a warehouse pilot. Action: I engineered features like past return rate per customer and category, moved to LightGBM with early stopping, and tuned it with Optuna on time-based folds. Result: AUC rose to 0.81, and the pilot reduced avoidable returns in two categories. I documented each step's gain.
21

Your dataset has 800 correlated features and the model trains slowly. What would you do?

Save to ▾
Show answer
I would remove constant and near-duplicate features, drop one from each highly correlated pair, then apply PCA inside the pipeline and keep components explaining about 95 percent of variance. Alternatively, use L1-regularised models or tree importances for supervised selection. I would compare speed and cross-validated scores; often 50 to 100 features give nearly the same accuracy.
22

What is boosting and how is it different from bagging?

Save to ▾
Show answer
Boosting trains models sequentially, each one focusing on the errors of the combined previous models, which mainly reduces bias. Bagging trains models independently in parallel and averages them, which mainly reduces variance. Boosting uses shallow trees and a learning rate, and can overfit if run too long, so early stopping is important. Examples are AdaBoost, Gradient Boosting, XGBoost, LightGBM and CatBoost.
23

What makes XGBoost, LightGBM and CatBoost different?

Save to ▾
Show answer
XGBoost adds regularisation to the objective, uses second-order gradients and handles missing values natively. LightGBM grows trees leaf-wise and uses histogram binning, making it very fast on large data, though it can overfit small data. CatBoost handles categorical features with ordered target statistics and uses symmetric trees, giving strong defaults with less tuning. All three support GPU training.
24

How does a support vector machine work?

Save to ▾
Show answer
An SVM finds the hyperplane that separates classes with the maximum margin, and the points on the margin are the support vectors. The soft-margin version uses C to trade off margin width against misclassification. Kernels like RBF or polynomial let SVMs learn non-linear boundaries by implicitly mapping data to higher dimensions. SVMs need scaled features and become slow beyond roughly a hundred thousand rows.
25

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

Tell me about a time your model did not work as expected. What did you do?

Save to ▾
Show answer
Situation: my first churn model scored 0.95 AUC in validation but failed in a pilot. Task: find out why. Action: I traced features and found one field updated after customers left, which leaked the label. I removed it, rebuilt features with a strict cut-off date and moved to a time-based split. Result: AUC dropped to 0.78 but held steady in production, and I added a leakage checklist to my workflow.
27

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

Validation AUC is 0.99 on a loan default model. What do you suspect?

Save to ▾
Show answer
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.
29

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

XGBoost validation loss starts rising after 300 rounds while training loss keeps falling. What do you do?

Save to ▾
Show answer
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.

Tips to crack the TCS Machine Learning interview

  • Practise TCS NQT style numerical, verbal and reasoning sections along with two basic coding problems under strict time limits.
  • Be ready to explain your final-year project, SQL basics and core concepts like OOP, DBMS and software testing life cycle.
  • Read about TCS service lines such as BFSI and its iON and Ignio platforms to answer why you want to join.
  • Keep a one-minute story ready for every project on your CV: problem, your part, tools, result.
  • Practise the hard questions on this page aloud; TCS interviewers usually ask follow-ups on your first answer.

Frequently asked questions

How many rounds are there in the TCS Machine Learning interview?

Candidates usually go through 4 stages: TCS NQT online assessment (aptitude + coding); Technical interview; Managerial round; HR round. The exact rounds change with the role, team, location and your experience, so confirm the process with the recruiter.

Which topics should I prepare for the TCS Machine Learning interview?

This practice set leans on Decision Trees and Ensembles (6), Classification Models (5), ML Fundamentals (4), Data Preprocessing and Feature Engineering (3). Revise those first, then practise explaining one or two of your own projects end to end, because most TCS interviewers ask you to walk through real work.

Are these the exact questions asked at TCS?

No. These are curated practice questions that match the skills and difficulty usually tested in it services interviews like TCS's. They are not a leaked or verified list of past questions.

Where does TCS hire Machine Learning professionals in India?

TCS has large teams in Mumbai, Chennai, Pune, Bengaluru, Hyderabad. Openings and locations change often, so check the TCS careers page and filter by city and experience.

Machine Learning questions for similar companies