- Updated
Interview Prep
AI & Machine Learning Interview Questions 2026
57 questions that come up in real AI, ML and GenAI interviews in India — from bias-variance to RAG and model deployment — with the answer the interviewer is listening for.
This page started as a list of ten fundamentals. Those ten are still here, because they still open almost every machine learning interview. But 2026 hiring loops have moved on: an interview for an AI engineer role now spends as much time on LLMs, retrieval and deployment as on gradient descent, so the list now covers the whole loop.
How to use it: read each question, answer it out loud before you read ours, then compare. The answers are deliberately short — they are the core an interviewer wants to hear, not a script to memorise. Expect a follow-up on anything you mention, so only mention what you can explain.
Machine learning fundamentals
Q1. What is the difference between supervised and unsupervised learning?
Answer: Supervised learning trains on labelled examples — inputs with known answers — to predict the label for new inputs, such as spam detection or price prediction. Unsupervised learning finds structure in unlabelled data, such as customer segmentation or anomaly detection. Self-supervised learning sits in between: it creates its own labels from raw data, which is how large language models are pre-trained by predicting the next token.
Q2. What is the difference between classification and regression?
Answer: Classification predicts a category (fraud or not fraud, which of ten digits); regression predicts a continuous number (house price, delivery time). The choice drives the loss function — cross-entropy versus mean squared error — and the metrics: accuracy, F1 and AUC versus MAE and RMSE.
Q3. What is overfitting and how do you prevent it?
Answer: Overfitting happens when a model learns the noise in its training data, so it scores well in training but poorly on new data. You spot it as a growing gap between training and validation scores. Prevention: more data, simpler models, regularisation (L1/L2), dropout, early stopping and data augmentation.
Q4. Explain the bias-variance tradeoff.
Answer: Bias is error from a model too simple to capture the pattern (underfitting). Variance is error from a model that reacts too much to the particular training sample (overfitting). Making a model more flexible lowers bias but raises variance, so you look for the complexity where total validation error is lowest — usually with cross-validation.
Q5. What is regularisation, and how do L1 and L2 differ?
Answer: Regularisation adds a penalty on model weights to the loss function, discouraging overly complex fits. L1 (Lasso) penalises absolute values and pushes some weights to exactly zero, which doubles as feature selection. L2 (Ridge) penalises squared values and shrinks all weights smoothly. Elastic Net combines both, and dropout plays a similar role in neural networks.
Q6. What is gradient descent?
Answer: An optimisation method that reduces the loss by repeatedly moving the weights a small step in the direction of the negative gradient. Batch gradient descent uses all the data per step, stochastic uses one example, and mini-batch — the default in practice — uses a small batch. Optimisers such as Adam adapt the step size per parameter. Too high a learning rate diverges; too low takes forever.
Q7. What are hyperparameters and how do you tune them?
Answer: Settings chosen before training rather than learned from data — learning rate, tree depth, number of layers, batch size, regularisation strength. Tune them on a validation set or with cross-validation, using grid search, random search (usually more efficient) or Bayesian optimisation with tools like Optuna. Never tune on the test set.
Q8. How does a decision tree decide where to split?
Answer: At each node it tests candidate features and thresholds and picks the split that most reduces impurity — Gini impurity or entropy for classification, variance for regression. Left unchecked, trees memorise the data, so you limit depth, set a minimum number of samples per leaf, or prune.
Q9. What is the difference between bagging and boosting?
Answer: Bagging trains many models in parallel on bootstrapped samples and averages them, which mainly reduces variance — Random Forest is the classic example. Boosting trains models in sequence, each focusing on the errors of the previous ones, which mainly reduces bias — XGBoost, LightGBM and CatBoost. On tabular data, gradient boosting is usually the strongest baseline.
Q10. When would you choose logistic regression over a more complex model?
Answer: When you need a fast, well-calibrated and explainable model — credit scoring, where regulators ask why a decision was made — when data is small, or as the baseline every complex model has to beat. If a gradient-boosted model only beats it by a hair, the simpler model often wins in production.
Q11. How does k-means clustering work, and how do you choose k?
Answer: It places k centroids, assigns each point to the nearest one, moves each centroid to the mean of its points, and repeats until assignments stop changing. Choose k with the elbow method, the silhouette score, or what the business can actually act on. It assumes roughly round clusters and needs scaled features.
Q12. What is the curse of dimensionality?
Answer: As the number of features grows, data becomes sparse and distances lose meaning, so models need far more data and distance-based methods like k-NN degrade. Handle it with feature selection, dimensionality reduction such as PCA, regularisation, and domain knowledge about which features really matter.
Model evaluation and data
Q13. What are precision, recall and F1 score?
Answer: Precision is the share of predicted positives that are truly positive; recall is the share of actual positives the model caught. F1 is their harmonic mean, useful when classes are imbalanced. Which to favour depends on the cost of mistakes: a cancer screen favours recall, a spam filter favours precision.
Q14. What is a confusion matrix?
Answer: A table of true positives, true negatives, false positives and false negatives for a classifier. Precision, recall, specificity and accuracy all come from it, and it shows which kind of mistake the model makes — something a single accuracy number hides, especially on imbalanced data.
Q15. What do ROC-AUC and PR-AUC measure, and when do you prefer PR-AUC?
Answer: ROC-AUC measures how well the model ranks positives above negatives across all thresholds, plotting true-positive rate against false-positive rate. PR-AUC plots precision against recall. When positives are rare — fraud, loan defaults, rare diseases — ROC-AUC can look flattering, so PR-AUC gives a more honest picture.
Q16. How do you handle an imbalanced dataset?
Answer: First choose the right metric — precision, recall, F1 or PR-AUC, not accuracy. Then use class weights in the loss, resampling (undersampling the majority class, oversampling or SMOTE for the minority), and tune the decision threshold to the business cost. Keep validation and test sets at the real-world ratio, or your scores will mislead you.
Q17. What is cross-validation, and why use it?
Answer: You split the training data into k folds, train on k–1 of them and validate on the remaining one, rotating through every fold. It gives a more reliable estimate than a single split and makes better use of small datasets. Use stratified folds for imbalanced classes and time-based splits for time series.
Q18. What is data leakage? Give an example.
Answer: Information that won't exist at prediction time sneaking into training, so validation scores look too good to be true. Examples: scaling with statistics from the full dataset before splitting, a "days since account closed" feature in a churn model, or a random split on time-series data that lets the model see the future. Fit all preprocessing on the training data only.
Q19. How do you handle missing values?
Answer: First ask why they are missing — at random, or for a reason (an empty "previous loan" field often means there was no previous loan). Then drop rows or columns when little is lost, impute with the mean, median or mode, use model-based imputation, or add a "was missing" indicator. Libraries like XGBoost can also handle missing values natively.
Q20. Why do we scale features, and when does it matter?
Answer: Scaling puts features on comparable ranges. It matters for distance- and gradient-based methods — k-NN, k-means, SVMs, regularised linear models and neural networks — and barely at all for tree-based models, which split on thresholds. Use standardisation or min-max scaling, fitted on the training data only.
Q21. How do you choose between candidate models?
Answer: Start from the problem: data size, how much explainability is needed, and the latency and cost limits. Build a simple baseline, compare candidates on the same validation scheme and the metric the business cares about, then weigh training and serving cost, maintenance effort, and how each model behaves on the failure cases that matter most.
Q22. How would you know a model in production is degrading?
Answer: Monitor input drift (feature distributions moving away from the training data, measured with PSI or a KS test), drift in the predictions themselves, and — once labels arrive — live accuracy against a baseline. Set alert thresholds, keep a fixed "golden" test set, and trigger investigation or retraining when they are crossed.
Deep learning
Q23. What is a neural network, in plain terms?
Answer: Layers of simple units, each computing a weighted sum of its inputs and passing it through a non-linear function. Stacking layers lets the network learn increasingly abstract features — edges, then shapes, then whole objects in an image. Training adjusts the weights using backpropagation and gradient descent.
Q24. What is backpropagation?
Answer: The algorithm that works out how much each weight contributed to the error, by applying the chain rule backwards from the loss through every layer. Those gradients then drive the gradient-descent update. Frameworks like PyTorch compute them automatically, but interviewers expect you to explain the idea.
Q25. Why do we need activation functions? Compare ReLU, sigmoid and softmax.
Answer: Without a non-linearity, any stack of layers collapses into a single linear transformation. ReLU, max(0, x), is the default in hidden layers because it is cheap and limits vanishing gradients. Sigmoid squashes values to between 0 and 1 for binary outputs; softmax turns a vector into probabilities across several classes.
Q26. What are vanishing and exploding gradients?
Answer: In deep or recurrent networks, gradients multiplied through many layers can shrink towards zero, so early layers stop learning, or blow up, so training diverges. Fixes include ReLU-family activations, careful weight initialisation (He or Xavier), normalisation layers, residual connections and gradient clipping.
Q27. What does dropout do?
Answer: During training it randomly switches off a fraction of neurons at each step, so the network can't depend on any single pathway and learns more robust features. It works as regularisation. At inference time every neuron is active, with outputs scaled to match.
Q28. What is the difference between a CNN and an RNN?
Answer: A CNN slides convolutional filters over the input to detect local patterns, which suits images and other grid-like data. An RNN processes a sequence step by step while carrying a hidden state, which suits text and time series; LSTMs and GRUs fix much of its memory problem. For language, both have largely been replaced by transformers.
Q29. What is transfer learning?
Answer: Reusing a model pre-trained on a large dataset — ResNet for images, BERT or an LLM for text — and adapting it to your task, either by training a new output layer or by fine-tuning some of its layers. It needs far less labelled data and compute than training from scratch, which is why it is the default approach in industry.
Q30. What is batch normalisation, and why does it help?
Answer: It normalises a layer's inputs within each mini-batch to a stable mean and variance, then rescales them with learned parameters. Training becomes faster and more stable and tolerates higher learning rates. Transformers use the related layer normalisation, which normalises across features instead of across the batch.
NLP, LLMs and generative AI
Q31. Explain the transformer architecture and self-attention.
Answer: A transformer processes all the tokens in a sequence at once. Self-attention lets each token weigh how relevant every other token is, using query, key and value vectors, so it captures context regardless of distance. Multiple attention heads, positional encodings, feed-forward layers and residual connections complete each block. Because it parallelises well, it scaled into today's LLMs.
Q32. What are embeddings?
Answer: Dense vectors that represent items — words, sentences, images, products — so that similar items sit close together. They power semantic search, recommendations, clustering and the retrieval step of RAG. Similarity between embeddings is usually measured with cosine similarity.
Q33. What is tokenisation, and why does it matter for LLMs?
Answer: Splitting text into the units a model actually processes, usually sub-word pieces. It matters because context limits, pricing and latency are all counted in tokens, and because some text — code, numbers, Indian-language scripts — can use far more tokens than you would expect from its length.
Q34. How do BERT-style and GPT-style models differ?
Answer: BERT is an encoder trained to fill in masked words using context from both sides, which makes it strong at understanding tasks such as classification, search and entity extraction. GPT-style models are decoders trained to predict the next token, which makes them built for generating text. Most modern chat models are decoder-only.
Q35. What is RAG, and when would you use it?
Answer: Retrieval-augmented generation: instead of relying only on what the model memorised, you retrieve relevant documents for each question — usually through embeddings in a vector database — and include them in the prompt so the model answers from them. Use it when answers must come from your own or frequently changing data, such as policies, product documentation or support tickets, and when you need citations.
Q36. RAG or fine-tuning: how do you choose?
Answer: RAG adds knowledge — facts that change or are private — and is cheap to keep current. Fine-tuning changes behaviour — tone, output format, a narrow task done consistently — and needs good training examples. Many production systems use both. Start with prompting and RAG, and fine-tune only when you can show they are not enough.
Q37. A RAG system gives wrong answers. How do you improve it?
Answer: Diagnose before fixing. Check retrieval first: are the right chunks coming back? Improve chunking, add metadata filters, try hybrid search (keyword plus vector) and a re-ranker. Then the generation step: clearer instructions to answer only from the context and to say "I don't know", plus citations. Measure every change against an evaluation set of real questions, not spot checks.
Q38. What are hallucinations, and how do you reduce them?
Answer: Fluent, confident output that isn't supported by facts or the context provided. Reduce them by grounding answers in retrieved sources, asking for citations, using a low temperature for factual tasks, constraining output formats, adding verification steps, and allowing the model to decline. They can't be eliminated, so systems need checks wherever errors are costly.
Q39. What do temperature and top-p control?
Answer: Both shape how the next token is sampled. Temperature scales the probability distribution: low values give focused, repeatable output, high values give more varied output. Top-p (nucleus sampling) samples only from the smallest set of tokens whose probabilities add up to p. For extraction and factual answers, keep both low.
Q40. Which prompt engineering techniques actually help?
Answer: Clear instructions and context, a few good examples (few-shot prompting), asking for step-by-step reasoning on complex tasks, structured output formats such as JSON, and breaking a large task into smaller chained calls. Test prompts against a fixed set of cases rather than tweaking by feel.
Q41. What is LoRA, and why is it popular for fine-tuning?
Answer: Low-Rank Adaptation freezes the original model weights and trains small low-rank matrices added to selected layers. Only a tiny fraction of parameters is trained, so it needs much less GPU memory and storage, and one base model can serve several small task-specific adapters. QLoRA adds quantisation to cut memory further.
Q42. How do you evaluate an LLM application?
Answer: Build an evaluation set of realistic inputs with expected answers or grading criteria. Combine automatic checks (exact match, format validation, retrieval hit rate), LLM-as-a-judge scoring for open-ended answers — validated against human ratings — and human review of samples. Track cost and latency alongside quality, and re-run the set on every prompt or model change.
Q43. What is an AI agent, and how is it different from a chatbot?
Answer: A chatbot answers within a conversation. An agent works towards a goal: it plans steps, calls tools — search, APIs, code execution, databases — reads the results and continues until the task is done. Frameworks such as LangGraph and CrewAI help structure this. The usual follow-up is about guardrails: limits on tools, steps and spend, and human approval for risky actions.
Q44. How would you cut the cost and latency of an LLM feature?
Answer: Use the smallest model that meets the quality bar, route simple requests to cheaper models, trim prompts and retrieved context, cache repeated answers, stream responses, batch offline work and cap output length. Measure cost per request and quality on the same evaluation set, so savings don't quietly break answers.
MLOps and deployment
Q45. How do you deploy a machine learning model?
Answer: Package the model with its preprocessing, wrap it in an API (FastAPI is common), containerise it with Docker, and deploy it to a managed platform or Kubernetes. Add input validation, logging, monitoring and a rollback path. For large volumes that don't need instant answers, scheduled batch scoring is often simpler and cheaper.
Q46. What is MLOps?
Answer: The practices that take models from notebooks to reliable production: versioning data, code and models; reproducible training pipelines; CI/CD and automated tests for models; deployment; and monitoring with retraining. Common tools include MLflow, DVC, Airflow or Kubeflow, and cloud platforms such as SageMaker, Vertex AI and Azure ML.
Q47. What is the difference between data drift and concept drift?
Answer: Data drift is when the inputs change — new user segments, a different product mix — while the underlying relationship stays the same. Concept drift is when the relationship itself changes — fraud patterns evolve, customer behaviour shifts after a policy change. Both degrade models; concept drift usually needs fresh labels and retraining.
Q48. How do you make an experiment reproducible?
Answer: Fix random seeds, pin library versions, version the exact data snapshot and code commit, and log parameters, metrics and artefacts with a tracker such as MLflow or Weights & Biases. Anyone should be able to rerun the training job and get the same model — or see exactly why not.
Q49. Batch or real-time inference: how do you decide?
Answer: Real-time inference suits decisions made in the moment — a fraud check at payment time, recommendations on page load — and demands low latency and high availability. Batch inference suits predictions that can be computed ahead, like nightly churn scores or weekly demand forecasts, and is simpler and cheaper to run. Many systems use both.
Q50. How would you A/B test a new model?
Answer: Split live traffic between the current model and the new one, fix the business metric and guardrail metrics in advance, and run until the result is statistically significant. A shadow deployment — the new model scores real traffic without acting on it — is a safe step before a full A/B test.
Python and the coding round
Q51. How do a list, tuple, set and dictionary differ in Python?
Answer: A list is ordered and mutable; a tuple is ordered and immutable, so it can be a dictionary key; a set holds unique items with fast membership checks; a dictionary maps keys to values with fast lookups. Interviewers use this to check that you reach for a set or dictionary for lookups instead of scanning a list.
Q52. Why are NumPy and pandas operations faster than Python loops?
Answer: They are vectorised: the work runs in optimised C code over whole arrays instead of one Python object at a time. In practice that means avoiding row-by-row loops and apply() on large data wherever a built-in vectorised operation exists.
Q53. How would you process a dataset that doesn't fit in memory?
Answer: Read it in chunks, stream it with generators, load only the columns you need with efficient types, store it as Parquet, or move to tools built for it — Polars, DuckDB, Dask or Spark. The interviewer wants to see you think about memory before you write code.
Scenario and project questions
Q54. Your model is 95% accurate. Is that good?
Answer: Not necessarily. If 95% of the data belongs to one class, a model that always predicts that class also scores 95%. Ask for the class balance, the confusion matrix and the cost of each type of error, and compare against a simple baseline. The question tests whether you challenge a number before celebrating it.
Q55. A model did well offline but badly after launch. What do you check?
Answer: Training-serving skew (features computed differently in production), leakage that inflated the offline scores, drift between the training period and now, bugs in the live preprocessing, and whether the offline metric really reflects the business outcome. Compare live inputs with training inputs feature by feature.
Q56. How would you build a chatbot that answers questions about a company's HR policies?
Answer: As a RAG system: ingest the policy documents, split them into sensible chunks with metadata such as department and effective date, embed and index them, retrieve the most relevant chunks for each question, and have the LLM answer only from them, with citations. Add access control, a hand-off to HR for unanswered questions, and an evaluation set built from real employee questions.
Q57. Walk me through a project on your resume.
Answer: Structure it as problem, data, approach, result and what you would change. Be ready for: why that model, what the baseline was, how you validated it, what went wrong and how you found it, and how it was — or would be — deployed. Know your numbers. A small project you can defend in depth beats an impressive one you only half understand.
How to prepare in the last two weeks
Rehearse your two strongest projects until you can explain each in five minutes and defend it for thirty. Re-derive the core ideas — gradient descent, precision and recall, attention — on paper instead of re-reading them. Build one small RAG app end to end, because LLM questions now appear even in fresher interviews, and practise the Python round against a timer. If salary comes up, know the market range for your level first; our AI salary guide has the numbers.
Crack AI Interviews with Confidence
Our AI program includes dedicated interview preparation — mock interviews, real questions, and feedback from industry mentors.