Lab viva guide

Machine learning viva questions and answers: 62 short answers for the ML lab, regression to neural networks

25 min read Updated English

Machine learning viva questions start from the notebook you ran: the examiner asks why you scaled the features, what your confusion matrix shows, or why the decision tree chose that attribute at the root, then moves to the theory behind each algorithm. This page gives 62 machine learning viva questions with short, exam-ready answers, grouped the way an ML lab runs (basics, data preparation, regression, classification algorithms, model evaluation, ensembles, unsupervised learning, neural networks, and the classic concept-learning experiments), plus an algorithm table, the mistakes examiners catch and a plan for the night before.

How the examiner runs a machine learning lab viva

Most machine learning labs in Indian universities use Python with NumPy, pandas, scikit-learn and Matplotlib, and sometimes TensorFlow or Keras. Typical experiments are the Find-S and candidate elimination algorithms, the ID3 decision tree, linear and logistic regression, k-nearest neighbours, naive Bayes on a text or tabular dataset, support vector machines, k-means and the EM algorithm for clustering, PCA, and a backpropagation neural network. The viva starts from your notebook and dataset.

  • First, your data: 'how many rows and features?', 'how did you handle missing values?', 'why this train-test split?'
  • Then the algorithm: 'what is the hypothesis or decision rule?', 'what does the cost function measure?'
  • Then your result: 'what is the precision here, and why is it lower than the accuracy?'
  • Then a what-if: 'what if k is 1?', 'what if the classes are imbalanced?', 'what if you do not scale the data?'
  • Then a comparison: bagging versus boosting, L1 versus L2, k-means versus hierarchical clustering.

Name your dataset and your number

Answer with your own numbers: 'On the Iris dataset with a 70-30 split, my k-NN with k equal to 5 reached 96 percent test accuracy.' A concrete result followed by the reason it is good or bad is the answer examiners remember.

Machine learning basics

What is machine learning?

Machine learning is a branch of artificial intelligence in which a program improves its performance at a task by learning patterns from data rather than following hand-written rules. Tom Mitchell's definition says a program learns from experience E with respect to a task T and a performance measure P if its performance at T, measured by P, improves with E.

What are supervised, unsupervised and reinforcement learning?

In supervised learning the model learns from labelled examples, input with the correct output, as in spam classification or house price prediction. In unsupervised learning the data has no labels, and the model finds structure such as clusters. In reinforcement learning an agent learns by acting in an environment and receiving rewards or penalties.

What is the difference between AI, machine learning and deep learning?

Artificial intelligence is the broad goal of making machines perform tasks that need intelligence, by any method, including hand-written rules. Machine learning is the subset of AI in which systems learn from data. Deep learning is the subset of machine learning that uses neural networks with many layers, and it dominates image, speech and language tasks.

What is semi-supervised learning?

Semi-supervised learning uses a small amount of labelled data together with a large amount of unlabelled data. The unlabelled data helps the model learn the structure of the input space, for example through self-training, where confident predictions on unlabelled examples are added as labels. It helps when labelling is expensive, as with medical images.

What is the difference between regression and classification?

Both are supervised. Regression predicts a continuous numerical value, such as a house price or a temperature. Classification predicts a discrete class label, such as spam or not spam, or one of three flower species. Logistic regression, despite its name, is a classification method.

What are features, labels and instances?

An instance is one example, a row of the dataset. Features are its measured input attributes, the columns used for prediction, such as petal length and petal width. The label, or target, is the output the model must predict, such as the species. A dataset of 150 flowers with 4 features has 150 instances.

What is the difference between training, validation and test sets?

The training set is used to fit the model's parameters. The validation set is used to tune hyperparameters and choose between models. The test set is held back until the end and used once to estimate performance on new data. Using the test set for tuning makes the reported accuracy over-optimistic.

What is the difference between a parameter and a hyperparameter?

Parameters are learned from data during training, such as the weights of a linear regression or a neural network. Hyperparameters are set before training and control the learning process, such as the learning rate, the value of k in k-NN, the depth of a tree or the regularisation strength. They are tuned using validation data.

What is inductive bias?

Inductive bias is the set of assumptions a learning algorithm uses to generalise beyond the training examples. Linear regression assumes a linear relation; ID3 prefers shorter trees with high-information attributes near the root; k-NN assumes nearby points share a label. Without some bias, a learner cannot generalise to unseen data at all.

Data preparation

How do you handle missing values?

First check how many values are missing and whether the gaps are random. Rows or columns with very few useful values can be dropped. Otherwise, impute: the mean or median for numerical features, the most frequent value for categorical ones, or a model-based estimate. In my lab I used the median for age because the data was skewed.

Why is feature scaling needed?

Algorithms that use distances or gradients, such as k-NN, k-means, SVM, PCA and gradient descent, are dominated by features with large ranges. If salary is in lakhs and age in years, salary decides every distance. Scaling puts the features on comparable ranges. Tree-based methods do not need it.

What is the difference between normalisation and standardisation?

Min-max normalisation rescales a feature to a fixed range, usually 0 to 1, by subtracting the minimum and dividing by the range; it is sensitive to outliers. Standardisation subtracts the mean and divides by the standard deviation, giving mean 0 and standard deviation 1. The scaler must be fitted on the training data only.

How are categorical features encoded?

Label encoding maps each category to an integer, which suits ordinal data like low, medium and high, and tree models. One-hot encoding creates one binary column per category, which suits nominal data like city names in linear and distance-based models, because it does not imply a false order.

What is data leakage?

Data leakage is when information that would not be available at prediction time gets into training, so the model looks better in testing than it will be in use. A common example is scaling or imputing using the whole dataset before splitting, or including a feature that is recorded only after the outcome is known.

What is the curse of dimensionality?

As the number of features grows, the volume of the feature space grows so fast that data becomes sparse, distances between points become similar, and many more samples are needed to learn reliably. Distance-based methods like k-NN suffer most. Feature selection and dimensionality reduction such as PCA help.

What is the difference between feature selection and feature extraction?

Feature selection keeps a subset of the original features, for example by correlation with the target, by recursive elimination or through L1 regularisation, so the features stay interpretable. Feature extraction builds new features from combinations of the original ones, as PCA does, which can capture more information in fewer dimensions but is harder to interpret.

How do you detect and handle outliers?

I look at box plots and summary statistics, and flag values beyond 1.5 times the interquartile range from the quartiles, or with a z-score beyond about 3. Then I check whether each is an error or a genuine extreme. Errors are corrected or removed; genuine values can be kept, capped, or handled with robust methods such as tree models or median-based scaling.

Regression and gradient descent

What is linear regression?

Linear regression models the target as a weighted sum of the features plus an intercept, y equals w-naught plus w1 x1 and so on. The weights are chosen to minimise the mean squared error between predicted and actual values, either in closed form by the normal equation or iteratively by gradient descent.

What is the least squares method?

It chooses the line that minimises the sum of squared vertical differences, the residuals, between the observed values and the line's predictions. Squaring makes all residuals positive and penalises large errors more. For one feature it gives the slope as the covariance of x and y divided by the variance of x.

What is gradient descent?

Gradient descent is an iterative optimisation method. It starts with some weights, computes the gradient of the cost function with respect to each weight, and moves the weights a small step in the opposite direction, scaled by the learning rate. It repeats until the cost stops decreasing appreciably.

What happens if the learning rate is too high or too low?

If it is too high, the steps overshoot the minimum and the cost oscillates or diverges. If it is too low, training is very slow and may stop before reaching a good solution. I usually try values on a log scale, such as 0.1, 0.01 and 0.001, and plot the cost against iterations.

What are batch, stochastic and mini-batch gradient descent?

Batch gradient descent computes the gradient over the whole training set for each update, which is stable but slow for large data. Stochastic gradient descent updates after each single example, which is fast and noisy. Mini-batch uses small batches, such as 32 or 64 examples, balancing the two; it is the standard for neural networks.

How is a regression model evaluated?

With mean absolute error, mean squared error or its square root, RMSE, which is in the same unit as the target, and the coefficient of determination R squared, the fraction of the target's variance explained by the model. An R squared of 0.85 means 85 percent of the variance is explained.

What is polynomial regression?

It fits a curve by adding powers of the features, such as x squared and x cubed, as new features and then fitting linear regression on them. It is still linear in the weights. A high degree fits the training data very closely but tends to overfit, so the degree is chosen with validation data.

What is logistic regression?

Logistic regression is a classification method that passes a linear combination of the features through the sigmoid function, which outputs a probability between 0 and 1. A threshold, usually 0.5, turns it into a class. It is trained by minimising the log loss, or cross-entropy, rather than squared error.

Why is squared error not used for logistic regression?

With the sigmoid inside, the squared error cost becomes non-convex in the weights and can have local minima, so gradient descent is not guaranteed to find the best solution. The log loss is convex for logistic regression, and it heavily penalises confident wrong predictions, which is what a probability model needs.

Classification algorithms

How does k-nearest neighbours work?

k-NN stores the training data. To classify a new point, it finds the k training points nearest to it, usually by Euclidean distance, and takes a majority vote of their labels; for regression it averages their values. It has no training phase, so prediction is slow on large datasets, and it needs scaled features.

How do you choose k in k-NN?

A small k, such as 1, follows the training data too closely and is sensitive to noise, which is overfitting. A large k smooths the boundary too much and underfits. I chose k by cross-validation, trying odd values from 1 to 15 for a two-class problem so that votes cannot tie, and picked the one with the best validation accuracy.

What is the naive Bayes classifier?

It applies Bayes' theorem to find the class with the highest posterior probability given the features, assuming the features are conditionally independent given the class. That naive assumption makes the probabilities easy to compute from counts. It works well for text classification, such as spam filtering, despite the assumption rarely being exactly true.

What is Laplace smoothing?

In naive Bayes, a word that never appears with a class in training gets a probability of zero, which wipes out the whole product. Laplace, or add-one, smoothing adds one to every count, and adjusts the denominator accordingly, so no probability is exactly zero.

Can naive Bayes handle continuous features?

Yes. Gaussian naive Bayes assumes each continuous feature follows a normal distribution within each class and uses the class-wise mean and variance to compute the likelihood. Multinomial naive Bayes suits word counts in text, and Bernoulli naive Bayes suits binary features. Continuous features can also be binned into categories.

How does a decision tree choose the attribute to split on?

At each node it picks the attribute that best separates the classes. ID3 uses information gain, the reduction in entropy after the split. C4.5 uses the gain ratio to avoid favouring attributes with many values, and CART uses the Gini index. The process repeats on each branch until the nodes are pure or a stopping rule applies.

What are entropy and information gain?

Entropy measures the impurity of a set: minus the sum over classes of p times log base 2 of p. It is 0 for a pure set and 1 for an even two-class split. Information gain of an attribute is the entropy of the parent minus the weighted average entropy of the children after splitting on it.

How do you prevent a decision tree from overfitting?

By pre-pruning, which stops growth early with limits such as a maximum depth, a minimum number of samples per leaf or a minimum gain; or by post-pruning, which grows the full tree and then removes branches that do not improve validation accuracy. Ensembles like random forests also reduce the variance of single trees.

What is a support vector machine?

An SVM finds the hyperplane that separates two classes with the maximum margin, the largest distance to the nearest points of each class. Those nearest points are the support vectors, and only they define the boundary. A soft margin, controlled by the parameter C, allows some misclassified points so the model tolerates noise.

What is the kernel trick?

When classes are not linearly separable, an SVM can implicitly map the data into a higher-dimensional space where they are. A kernel function computes the inner products in that space directly from the original features, without computing the mapping. Common kernels are linear, polynomial and the radial basis function.

Model evaluation

What are overfitting and underfitting?

Overfitting is when a model learns the training data, including its noise, so well that it performs poorly on new data: high training accuracy, much lower test accuracy. Underfitting is when the model is too simple to capture the pattern, so it does poorly on both. The aim is a model that generalises.

Explain the bias-variance trade-off.

Bias is error from wrong or overly simple assumptions, causing underfitting. Variance is error from sensitivity to the particular training sample, causing overfitting. Making a model more complex usually lowers bias and raises variance. The best model balances them to minimise the total error on unseen data.

What is k-fold cross-validation?

The data is split into k equal folds. The model is trained k times, each time on k minus 1 folds and validated on the remaining fold, and the k scores are averaged. With k equal to 5 or 10, every example is used for validation once, giving a more reliable estimate than one train-test split, especially for small datasets.

What is a confusion matrix?

For binary classification it is a 2 by 2 table of true positives, false positives, false negatives and true negatives, comparing predicted with actual classes. All the usual metrics, accuracy, precision, recall and F1, are computed from it, and it shows which kind of error the model makes.

Define precision, recall and F1 score.

Precision is true positives divided by all predicted positives: of the emails marked spam, how many were spam. Recall is true positives divided by all actual positives: of all spam, how much was caught. F1 is the harmonic mean of precision and recall, 2 times their product divided by their sum.

Why is accuracy misleading on imbalanced data?

If 98 percent of transactions are genuine, a model that labels everything genuine gets 98 percent accuracy while catching no fraud at all. Precision, recall, the F1 score and the confusion matrix show the real performance on the minority class. Resampling or class weights can help the model learn it.

What are type I and type II errors in classification?

A type I error is a false positive: predicting the positive class when it is actually negative, such as flagging a genuine email as spam. A type II error is a false negative: missing an actual positive, such as failing to detect a disease. Which one is costlier depends on the problem, and it decides whether to favour precision or recall.

What is the ROC curve and AUC?

The ROC curve plots the true positive rate against the false positive rate as the classification threshold varies. The area under it, AUC, summarises how well the model ranks positives above negatives: 0.5 is random guessing and 1 is perfect separation. It does not depend on any single threshold.

What is regularisation? Compare L1 and L2.

Regularisation adds a penalty on the size of the weights to the cost function to reduce overfitting. L2, used in ridge regression, adds the sum of squared weights and shrinks all weights smoothly. L1, used in lasso, adds the sum of absolute weights and can drive some weights exactly to zero, so it also selects features.

Ensembles and unsupervised learning

What is ensemble learning?

Ensemble learning combines the predictions of several models to get better accuracy and stability than any single one. The main approaches are bagging, which trains models in parallel on bootstrap samples, boosting, which trains them in sequence to fix earlier errors, and stacking, which learns how to combine different models.

How does a random forest work?

A random forest trains many decision trees, each on a bootstrap sample of the data, and at every split considers only a random subset of the features. The trees are therefore different, and averaging their votes reduces variance and overfitting compared with a single deep tree. It also gives feature importance scores.

What is the difference between bagging and boosting?

Bagging trains models independently on random bootstrap samples and averages them, which mainly reduces variance; random forest is an example. Boosting trains models one after another, each giving more weight to the examples the previous ones got wrong, which mainly reduces bias; AdaBoost and gradient boosting are examples.

What is gradient boosting?

Gradient boosting builds an ensemble of shallow trees in sequence. Each new tree is fitted to the residual errors, more precisely the negative gradient of the loss, of the ensemble built so far, and is added with a small learning rate. Libraries such as XGBoost and LightGBM implement it efficiently, and it is a strong default for tabular data.

How does k-means clustering work?

Choose k, place k initial centroids, assign each point to the nearest centroid, then move each centroid to the mean of its assigned points. Repeat the assign and update steps until the assignments stop changing. It minimises the within-cluster sum of squared distances, and the result depends on the initial centroids, so it is run several times.

How do you choose k in k-means?

With the elbow method, I plot the within-cluster sum of squares against k and pick the value where the decrease flattens into an elbow. The silhouette score, which compares how close each point is to its own cluster versus the nearest other cluster, is another check. Domain knowledge also matters.

What is hierarchical clustering?

Agglomerative hierarchical clustering starts with every point as its own cluster and repeatedly merges the two closest clusters, using single, complete or average linkage to define closeness, until one cluster remains. The result is a dendrogram, and cutting it at a chosen height gives the clusters. It does not need k in advance.

What is the EM algorithm?

Expectation-maximisation fits models with hidden variables, such as a Gaussian mixture model. The E-step computes, for each point, the probability that it belongs to each component using the current parameters. The M-step re-estimates the means, variances and weights using those probabilities. The two steps repeat until the likelihood converges. It gives soft cluster memberships, unlike k-means.

What is principal component analysis?

PCA is a dimensionality reduction method that finds new orthogonal axes, the principal components, along which the data varies most. They are the eigenvectors of the covariance matrix of the mean-centred data, usually standardised first, ordered by their eigenvalues. Keeping the first few components, for example those explaining 95 percent of the variance, reduces the features with little loss of information.

Neural networks and concept learning

What is a perceptron?

A perceptron is the simplest artificial neuron: it computes a weighted sum of its inputs plus a bias and outputs 1 if the sum is above a threshold, else 0. The perceptron learning rule adjusts the weights after each mistake. A single perceptron can learn only linearly separable functions, so it cannot learn XOR.

Why are activation functions needed? Name some.

Without a non-linear activation, a stack of layers is still just a linear function, so the network could not learn complex patterns. Common activations are sigmoid, which outputs between 0 and 1, tanh, between minus 1 and 1, and ReLU, which outputs the input if positive and zero otherwise; ReLU is the default in hidden layers because it trains fast.

Explain backpropagation.

After a forward pass computes the output and the loss, backpropagation applies the chain rule to compute the gradient of the loss with respect to every weight, layer by layer from the output back to the input. Gradient descent then updates each weight against its gradient. One pass over all the training data is an epoch.

What is the vanishing gradient problem?

In deep networks with sigmoid or tanh activations, gradients are multiplied by small derivatives at each layer during backpropagation, so they shrink towards zero in the early layers, which then learn very slowly. ReLU activations, careful weight initialisation, batch normalisation and residual connections reduce the problem.

What is dropout?

Dropout is a regularisation method for neural networks. During training, each neuron in a layer is switched off at random with a set probability, such as 0.5, on every pass, so the network cannot rely on any single neuron and learns more robust features. At test time all neurons are used, with outputs scaled to match the training behaviour.

What is a convolutional neural network used for?

CNNs are used mainly for images. Convolutional layers slide small learned filters over the image to detect local features such as edges and textures, pooling layers reduce the spatial size, and fully connected layers at the end classify. Sharing filter weights across the image makes them far more efficient than fully connected networks for this task.

What does the Find-S algorithm do?

Find-S finds the most specific hypothesis consistent with the positive training examples. It starts with the most specific hypothesis and, for each positive example, generalises each attribute that does not match to a question mark, meaning any value. It ignores negative examples, so it cannot tell whether the data is consistent or whether other hypotheses fit.

What is the candidate elimination algorithm?

It keeps the whole version space, the set of all hypotheses consistent with the training examples, using two boundaries: the specific boundary S and the general boundary G. Each positive example generalises S and removes inconsistent members of G; each negative example specialises G and removes inconsistent members of S. When S and G meet, the concept is learned.

Algorithms at a glance

AlgorithmTypeKey ideaNeeds scalingViva hook
Linear regressionSupervised, regressionMinimise squared errorFor gradient descentR squared, RMSE
Logistic regressionSupervised, classificationSigmoid of a linear scoreRecommendedLog loss, threshold
k-NNSupervised, bothVote of k nearest pointsYesChoice of k, slow prediction
Naive BayesSupervised, classificationBayes rule with independent featuresNoLaplace smoothing
Decision treeSupervised, bothSplit on best information gain or GiniNoPruning against overfitting
Random forestEnsemble, baggingMany trees on bootstrap samplesNoFeature importance
SVMSupervised, mainly classificationMaximum margin hyperplaneYesKernel trick, C
k-meansUnsupervised, clusteringAssign to nearest centroid, update meansYesElbow method
Hierarchical clusteringUnsupervised, clusteringMerge closest clustersYesDendrogram
PCAUnsupervised, dimensionality reductionEigenvectors of the covariance matrixYes, standardiseExplained variance
Neural networkSupervised, bothLayers of weighted sums and activationsYesBackpropagation, epochs

Common mistakes in a machine learning viva

  • Not knowing the size, features and target of your own dataset.
  • Fitting the scaler or imputer on the whole dataset before splitting, which leaks test information.
  • Reporting only accuracy on an imbalanced dataset.
  • Calling logistic regression a regression algorithm in the sense of predicting a number.
  • Saying k-means needs labels, or that it always finds the same clusters whatever the initial centroids.
  • Mixing up precision and recall. Precision is about predicted positives; recall is about actual positives.
  • Saying more features always help. Irrelevant features add noise and can make results worse.

What the ExamPilot AI examiner checks when you practise

In a CS/IT lab viva session on ExamPilot you name your ML experiment, for example ID3, k-NN on Iris or k-means, and an AI examiner questions you by voice for about twelve minutes: your data and preprocessing, how the algorithm works, what your metrics mean, and a what-if. It follows up whenever an answer is vague, and you can answer in English or Hindi.

  • Data reasoning: missing values, scaling, encoding and the split, each with a reason.
  • Algorithm mechanics said in plain words: the decision rule, the cost function, the update step.
  • Metric interpretation: what your precision, recall or R squared actually says about the model.
  • Trade-offs: bias and variance, k too small or too large, L1 against L2, bagging against boosting.
  • Brevity and honesty: two or three sentences, and a clean 'I am not sure' rather than a guess.

Start with the CS/IT lab viva mock. If you are preparing for a data or AI job rather than a lab exam, the AI and ML interview mock asks the same concepts at interview depth.

The night before the machine learning lab exam

  1. 1

    Re-run every notebook

    Note the dataset size, the split, the preprocessing and the final metric for each experiment, and be ready to explain every cell.

  2. 2

    Work two calculations by hand

    The entropy and information gain of one attribute on a small play-tennis style table, and precision, recall and F1 from a confusion matrix.

  3. 3

    Say the algorithms aloud

    For each algorithm in the table, one sentence on how it works and one on when it fails.

  4. 4

    Run one mock viva

    Twelve minutes with the AI examiner on your own experiment shows which answers come out clearly and which need work.

ML labs run on Python, so revise Python viva questions. Data handling questions overlap with DBMS viva questions, complexity questions with DAA viva questions, and many final-year projects use ML, so see final-year project viva questions too.

Frequently asked questions

What are the most important machine learning viva questions?
Supervised versus unsupervised learning, regression versus classification, overfitting and underfitting, the bias-variance trade-off, train, validation and test sets, cross-validation, feature scaling, gradient descent, logistic regression, k-NN, naive Bayes, decision trees with entropy and information gain, SVM and kernels, random forest, bagging versus boosting, k-means, PCA, the confusion matrix and precision, recall and F1.
Which libraries should I know for the ML lab viva?
NumPy for arrays, pandas for loading and cleaning data, scikit-learn for models, preprocessing, splitting and metrics, and Matplotlib for plots. If your lab includes neural networks, know the basics of the library you used, such as Keras layers, compile, fit and evaluate. Be ready to explain the functions in your own code.
Is the ML lab viva the same as an AI ML interview?
The concepts overlap heavily, but a lab viva starts from your experiment and syllabus, including classic items like Find-S and candidate elimination. Job interviews go deeper into practical modelling, metrics for business problems, feature engineering and deployment, and often ask you to discuss a project end to end.
How do I explain an algorithm without equations in the viva?
Describe what it does with the data in plain steps, then name the quantity it optimises. For k-means: place k centres, assign each point to the nearest, move each centre to the mean of its points, repeat until nothing changes, which minimises the within-cluster squared distance. Add one weakness, such as sensitivity to initial centres.
How can I practise machine learning viva questions out loud?
On ExamPilot you can run a CS/IT lab viva by voice. Name your ML experiment and the AI examiner asks about your data, the algorithm and your metrics, follows up with what-ifs like an external examiner, then gives you a transcript with tighter answers to repeat. It is free to start.

Practise out loud

Practise your ML lab viva out loud

The AI examiner asks about your dataset, preprocessing, algorithm and metrics, then follows up with what-ifs on overfitting and model choice, like an examiner.

Engineering Viva · CS / IT lab viva

Read how this interview works

Official sources