Home / Blog / Programming / Machine Learning
Top 50 Machine Learning Interview Questions with Answers
Programming · Machine Learning · 38 min read
Fifty machine learning interview questions with answers, from bias and variance to RAG. Every program ran on scikit-learn 1.9.1, with real output shown.
How this sheet works
Fifty machine learning interview questions are grouped here by topic. The first ten cover the core ideas: what learning from data means, and where it goes wrong. Evaluation and metrics come next, then the algorithms, then clustering and features. Pipelines and scikit-learn practice follow. System design and MLOps come after those, and language models close the theory. The page ends with two coding tasks, written out in full.
Each program on this page ran on Python 3.12.3 with scikit-learn 1.9.1, NumPy 2.5.4 and pandas 3.1.1, and its printed output is shown exactly as it appeared. The data sets are small and fixed, and every random step uses a set seed, so running the same program gives the same numbers. One program is meant to fail: it hands raw text to a model. Its output slot shows the error line instead.
Work one question at a time. Try an answer in your own words before you look at the one written here. Then run the program that belongs to it. An answer you speak and a program you run will stay with you longer than a page you only read.
The ideas here rest on four courses. Pandas Beginner covers the data work: reading tables, finding gaps, grouping rows. Python Beginner covers the language: functions, lists, dictionaries. PyTorch Beginner covers deep learning: tensors, gradients, a first classifier. The System Design ML course covers production: training, serving, evaluation. Answers that lean on one of those name the lesson.
Three limits are worth stating. This sheet trains one small network by hand and no more. Deeper learning belongs to PyTorch Beginner. It never fine-tunes a language model. The site has no LLM course yet. And its system design answers are reasoning on paper, not running systems.
1. What is machine learning?
Machine learning is a way of writing programs that learn rules from data instead of receiving the rules from a programmer. A programmer shows the program examples. The program finds the pattern in those examples. Then it applies the pattern to new examples it has never seen.
A spam filter is a plain example. The examples are emails, each marked spam or not spam. The program learns which words and patterns mark an email as spam. A new email arrives, and the program judges it from what it learned.
Machine learning fits problems where the rule is hard to write by hand but easy to show by example. It does not fit problems with an exact answer, like adding two numbers. A formula answers those better.
2. What is the difference between supervised, unsupervised and reinforcement learning?
Supervised learning learns from labelled examples. Each example carries its answer. The program learns to map inputs to those answers. Predicting house prices from size and rooms is supervised learning. So is sorting emails into spam and not spam.
Unsupervised learning learns from examples with no answers. The program looks for structure on its own. Grouping shoppers by buying habits is unsupervised learning. So is finding odd transactions in a pile of normal ones.
Reinforcement learning learns by trial and reward. An agent acts, and the world answers with a reward or a penalty. The agent repeats what earned rewards. Teaching a program to play a game is reinforcement learning. The three kinds differ in what the data carries: answers, no answers, or rewards.
3. What is the difference between classification and regression?
Classification predicts a category. The answer is one of a fixed set of labels. Is this email spam or not spam. Is this picture a cat, a dog, or a bird. The labels are named in advance, and the model picks one.
Regression predicts a number. The answer sits on a continuous scale. What will this house sell for. How many units will sell next month. The model gives a value, not a label.
The two kinds need different measures. A classifier is judged by how often it picks the right label. A regressor is judged by how close its number lands to the true number. Mixing the two up is a common interview slip.
4. What is a feature, and what is a label?
A feature is one input the model reads. A label is the answer the model must predict. In a house-price model, the features are size, rooms, and age. The label is the price.
Features arrive as columns in a table. Each row is one example. The label is one more column, the one the model tries to guess. Training is the act of finding the link between the feature columns and the label column.
A good feature carries signal about the label. A useless feature carries none. Much of applied machine learning is choosing features that carry signal and dropping the ones that do not. The A First DataFrame lesson shows how a table of features is built and read.
5. What does a machine learning workflow look like, step by step?
A workflow has six steps. First comes the problem: state what the model must predict and how success will be measured. Second comes the data: gather it and check its quality. Third comes preparation: clean it, fill gaps, and turn words into numbers.
Fourth comes the model: pick an algorithm, train it on one part of the data, and test it on another part. Fifth comes evaluation: measure it with the right metric and compare it against a simple baseline. Sixth comes deployment: ship it, watch it, and retrain it when the world changes.
Skipping a step is how projects fail. A model trained on dirty data learns the dirt. A model measured with the wrong metric looks good while it fails. The order matters, and the measurement step matters most.
6. What is overfitting, and how do you spot it?
Overfitting is learning the noise in the training data instead of the pattern. An overfit model scores well on the data it trained on and badly on new data. It memorised the examples instead of learning the rule.
The spot check is simple: compare the training score with the test score. A large gap means overfitting. A model that scores 99% on training data and 70% on test data has overfit. A model that scores 75% on both has not.
Three fixes work in practice. Train on more data, so the noise matters less. Simplify the model, so it cannot memorise as much. Or regularise it, which is the subject of question 21. The PyTorch Overfitting, a First Look lesson shows the same gap appearing in a neural network.
7. What is the bias-variance tradeoff?
Bias is the error from a model that is too simple. It misses the pattern and underfits. A straight line fitted to curved data has high bias. It is wrong in the same way on every data set.
Variance is the error from a model that is too flexible. It chases the noise and overfits. A wiggly curve through every point has high variance. It is right on one data set and wrong on the next.
The tradeoff is that shrinking one grows the other. A model with low bias and low variance is the goal, and it is rarely reached. The practical answer is to measure both with cross-validation and pick the complexity where the test error is lowest. Question 16 shows how cross-validation measures it.
8. What is a train/test split, and why does it matter?
A train/test split divides the data into two parts. The model trains on the first part and is tested on the second part. The test part is never shown during training. It stands in for new data the model has never seen.
The split matters because a score on training data proves nothing. A model can memorise its training data and still fail on new examples. Only a held-out test set shows how the model behaves on fresh data.
A common split is 80% for training and 20% for testing. The random_state value fixes the shuffle, so the same split comes out every time the program runs. The program below splits the iris data set, 120 rows for training and 30 for testing.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=7)
print("train rows:", len(X_train))
print("test rows:", len(X_test))
print("first train label:", y_train[0])
Output:
train rows: 120
test rows: 30
first train label: 29. What is data leakage, and why is it dangerous?
Data leakage is when information from the test set slips into training. The model learns from data it should not have seen. Its test score looks good, and the score is a lie.
A classic leak is scaling the whole data set before splitting it. The scaler learns the test set's mean and spread. The test set is no longer unseen. Another leak is filling missing values with the whole column's average before the split.
The fix is order: split first, then fit every preparation step on the training part only. A pipeline enforces this order, which is why question 35 matters. Leakage is the first thing an experienced interviewer checks in a take-home task.
10. What is the difference between a model and an algorithm?
An algorithm is the recipe. A model is what the recipe produces. Logistic regression is an algorithm. A logistic regression fitted to house data is a model, with its own weights and its own bias term.
The same algorithm trained on different data gives a different model. The same data trained with a different algorithm gives a different model too. The algorithm is the method. The model is the fitted result.
Interviewers use the words loosely, and so do many teams. The distinction still matters when the talk turns to saving, loading, and versioning. You save a model, not an algorithm. Question 39 shows how a saved model is loaded back.
11. What is a confusion matrix?
A confusion matrix is a table of what a classifier got right and wrong. Each row is the true label. Each column is the predicted label. The diagonal holds the correct predictions. The off-diagonal cells hold the mistakes.
The matrix shows which classes the model confuses. A model can score 90% overall while failing one class completely. The matrix makes that failure visible. It is the first thing to read when a classifier misbehaves.
The program below trains a logistic regression on iris flowers and prints its confusion matrix. Four flowers are wrong, all between the second and third species. No setosa flower is ever mistaken, which the first row shows.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=7)
model = LogisticRegression(max_iter=500).fit(X_train, y_train)
print(confusion_matrix(y_test, model.predict(X_test)))
Output:
[[12 0 0]
[ 0 14 2]
[ 0 2 15]]12. What is precision, and what is recall?
Precision answers one question: of everything the model called positive, how many were truly positive. Recall answers another: of everything truly positive, how many did the model find. The two pull in opposite directions.
A spam filter with high precision rarely marks a real email as spam. A filter with high recall rarely lets a spam email through. Raising one usually lowers the other. The balance depends on which mistake costs more.
The program below counts the four numbers by hand: true positives and true negatives, plus false positives and false negatives. With 4 true positives, 1 false positive and 1 false negative, both precision and recall come out at 0.8.
y_true = [1, 0, 1, 1, 0, 1, 0, 0, 1, 0]
y_pred = [1, 0, 1, 0, 0, 1, 1, 0, 1, 0]
tp = sum(1 for t, p in zip(y_true, y_pred) if t == 1 and p == 1)
fp = sum(1 for t, p in zip(y_true, y_pred) if t == 0 and p == 1)
fn = sum(1 for t, p in zip(y_true, y_pred) if t == 1 and p == 0)
precision = tp / (tp + fp)
recall = tp / (tp + fn)
print("true positives:", tp)
print("false positives:", fp)
print("false negatives:", fn)
print("precision:", round(precision, 2))
print("recall:", round(recall, 2))
Output:
true positives: 4
false positives: 1
false negatives: 1
precision: 0.8
recall: 0.813. What is the F1 score, and when is it better than accuracy?
The F1 score is the harmonic mean of precision and recall. It is one number that punishes a model for favouring either side. A model with precision 0.9 and recall 0.1 scores an F1 near 0.18, not near 0.5. The harmonic mean drags the score toward the weaker side.
F1 beats accuracy when the classes are uneven. A data set with 95% negatives lets a lazy model score 95% accuracy by guessing negative every time. Its F1 is zero, because it never finds a positive. Accuracy hides that failure. F1 exposes it.
The program below scores the same ten predictions as question 12. Precision and recall are both 0.8, so the F1 score is 0.8 as well.
from sklearn.metrics import f1_score
y_true = [1, 0, 1, 1, 0, 1, 0, 0, 1, 0]
y_pred = [1, 0, 1, 0, 0, 1, 1, 0, 1, 0]
print("F1:", round(f1_score(y_true, y_pred), 2))
Output:
F1: 0.814. When is accuracy a misleading metric?
Accuracy misleads whenever one class dwarfs the others. A fraud detector sees 99 honest transactions for every fraud. A model that always answers honest scores 99% accuracy and catches no fraud at all. The number looks excellent. The model is useless.
Accuracy also misleads when mistakes cost different amounts. Missing a cancer diagnosis costs far more than a false alarm. A single accuracy figure treats both mistakes as equal. The business never does.
The fix is to pick the metric that matches the cost. Recall matters when missing a positive is expensive. Precision matters when a false alarm is expensive. F1 or ROC-AUC matter when both sides count. Question 17 shows the fraud case in code.
15. What is ROC-AUC, and how do you compute it?
ROC-AUC measures how well a model ranks positives above negatives. The model gives every example a score. Sort the examples by that score. AUC is the chance that a random positive outranks a random negative. A perfect ranker scores 1.0. Random guessing scores 0.5.
The clean way to compute it is the Mann-Whitney count: compare every positive against every negative, and count how often the positive scores higher. Ties count as half. Divide by the number of pairs. No curve needs drawing.
The program below scores six examples by hand. Three are positive and three are negative. Seven of the nine pairs rank the positive higher, so the AUC is 0.778. AUC suits ranking problems. It suits imbalanced data better than accuracy does.
scores = [0.9, 0.8, 0.7, 0.4, 0.6, 0.3]
labels = [1, 1, 0, 1, 0, 0]
pos = [s for s, y in zip(scores, labels) if y == 1]
neg = [s for s, y in zip(scores, labels) if y == 0]
wins = sum(1 for p in pos for n in neg if p > n)
ties = sum(1 for p in pos for n in neg if p == n)
auc = (wins + 0.5 * ties) / (len(pos) * len(neg))
print("positive scores:", pos)
print("negative scores:", neg)
print("AUC:", round(auc, 3))
Output:
positive scores: [0.9, 0.8, 0.4]
negative scores: [0.7, 0.6, 0.3]
AUC: 0.77816. What is cross-validation, and what is k-fold CV?
Cross-validation measures a model on several different test sets instead of one. The data is split into k equal folds. The model trains on k minus 1 folds and tests on the fold left out. The fold left out rotates until every fold has been the test set once.
One split can flatter or punish a model by luck. Five scores give a mean and a spread, which say far more than one number. A mean of 0.96 with scores from 0.9 to 1.0 is a steadier claim than a single 0.97.
The program below runs 5-fold cross-validation by hand on the iris data with a 3-nearest-neighbour model. The fold scores are 0.9, 1.0, 1.0, 0.967 and 0.933, and the mean is 0.96. No library helper does the splitting here. The loop is the whole method.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier
X, y = load_iris(return_X_y=True)
rng = np.random.RandomState(7)
idx = rng.permutation(len(X))
folds = np.array_split(idx, 5)
scores = []
for k in range(5):
test = folds[k]
train = np.concatenate([folds[j] for j in range(5) if j != k])
model = KNeighborsClassifier(n_neighbors=3)
model.fit(X[train], y[train])
scores.append(round(model.score(X[test], y[test]), 3))
print("fold scores:", scores)
print("mean score:", round(sum(scores) / len(scores), 3))
Output:
fold scores: [0.9, 1.0, 1.0, 0.967, 0.933]
mean score: 0.9617. How do you handle a severely imbalanced dataset?
A severely imbalanced data set has one class far smaller than the others. Fraud, rare disease, and churn all look like this. A plain model learns to ignore the rare class, because ignoring it is almost always right.
Three fixes work. Resampling changes the balance: copy rare examples, or drop common ones. Class weights change the cost: tell the model a missed rare example counts more. Threshold tuning changes the decision line: predict positive at a lower score than 0.5.
The program below trains on data that is 95% one class and 5% the other. The plain model finds only a quarter of the rare class. Giving the rare class a higher weight lifts its recall from 0.25 to 0.38. Weighting helps, and it does not work miracles.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import recall_score
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=500, weights=[0.95, 0.05], random_state=7)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=7)
plain = LogisticRegression(max_iter=500).fit(X_train, y_train)
weighted = LogisticRegression(
max_iter=500, class_weight="balanced").fit(X_train, y_train)
print("plain recall (rare class):",
round(recall_score(y_test, plain.predict(X_test)), 2))
print("balanced recall (rare class):",
round(recall_score(y_test, weighted.predict(X_test)), 2))
Output:
plain recall (rare class): 0.25
balanced recall (rare class): 0.3818. What is the difference between a validation set and a test set?
A validation set guides choices made during training. A test set judges the finished model once, at the end. The two jobs must stay apart. Using the test set to pick settings leaks the test set into training.
The usual split is three parts: train, validate, test. Train the model on the training part. Pick settings, like the number of neighbours, on the validation part. Measure the final model once on the test part. The test part is touched last and only once.
Cross-validation often replaces a fixed validation set, because it uses the data better. The test set stays separate either way. A model chosen on the test set has a test score that no longer means anything.
19. How does linear regression work?
Linear regression fits a straight line to the data. It picks the slope and intercept that make the line sit closest to the points. Closest means the smallest sum of squared gaps between the line and the points. That rule has one exact answer, which the maths finds directly.
The line is the model. A new input goes in, the line gives a number back. The slope says how much the answer moves when the input moves by one. The intercept says where the line crosses zero.
The program below fits a line to five points. The slope is 2.01 and the intercept is 0.03. For an input of 6 the line predicts 12.09. Linear regression is the simplest model in machine learning, and it is still the right tool when the link is genuinely straight.
import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[1], [2], [3], [4], [5]], dtype=float)
y = np.array([2.1, 4.0, 6.1, 7.9, 10.2])
model = LinearRegression().fit(X, y)
print("slope:", round(model.coef_[0], 3))
print("intercept:", round(model.intercept_, 3))
print("prediction for 6:", round(model.predict([[6]])[0], 3))
Output:
slope: 2.01
intercept: 0.03
prediction for 6: 12.0920. How does logistic regression work?
Logistic regression is a classifier, despite its name. It fits a line, then squeezes the line through a curve that turns any number into a probability between 0 and 1. That curve is the sigmoid. Above 0.5 the answer is one class. Below 0.5 it is the other.
The weights are found by gradient descent. The program starts with zero weights and nudges them, step by step, toward values that make the true labels more likely. Each nudge follows the slope of the error downhill.
The program below trains a logistic regression from scratch in NumPy, with no library doing the fitting. After 1,000 steps the weights are -10.412 and 4.694. An input of 2.2 gets a probability of 0.479, just below the halfway line, so the model calls it class 0.
import numpy as np
X = np.array([[0.5], [1.0], [1.5], [2.0], [2.5], [3.0], [3.5], [4.0]])
y = np.array([0, 0, 0, 0, 1, 1, 1, 1], dtype=float)
Xb = np.c_[np.ones(len(X)), X]
w = np.zeros(2)
for _ in range(1000):
z = Xb @ w
p = 1 / (1 + np.exp(-z))
grad = Xb.T @ (p - y) / len(y)
w -= 0.5 * grad
print("weights:", [round(float(v), 3) for v in w])
prob = 1 / (1 + np.exp(-(w[0] + w[1] * 2.2)))
print("P(y=1 | x=2.2):", round(float(prob), 3))
Output:
weights: [-10.412, 4.694]
P(y=1 | x=2.2): 0.47921. What is regularisation, and what is the difference between L1 and L2?
Regularisation is a penalty added to the error for large weights. It stops a model from leaning hard on any one feature. The model pays for every unit of weight, so it keeps only the weights that earn their keep.
L1, called Lasso, penalises the sum of the absolute weights. It drives useless weights all the way to zero, which also selects features. L2, called Ridge, penalises the sum of squared weights. It shrinks weights toward zero but rarely reaches it.
The program below fits both to data where only the first of three features matters. Lasso keeps 2.445 on the first feature and sets the other two to -0.0. Ridge keeps 2.947 on the first and small values, -0.019 and 0.008, on the rest. Lasso selects. Ridge shrinks.
import numpy as np
from sklearn.linear_model import Lasso, Ridge
rng = np.random.RandomState(7)
X = rng.normal(size=(40, 3))
y = 3 * X[:, 0] + rng.normal(scale=0.1, size=40)
for name, model in [("Lasso (L1)", Lasso(alpha=0.5)),
("Ridge (L2)", Ridge(alpha=0.5))]:
model.fit(X, y)
print(name, "coefficients:", [round(float(c), 3) for c in model.coef_])
Output:
Lasso (L1) coefficients: [2.445, -0.0, -0.0]
Ridge (L2) coefficients: [2.947, -0.019, 0.008]22. How does a decision tree decide where to split?
A decision tree splits the data by asking one yes-or-no question at a time. Each question picks a feature and a threshold, like petal length below 2.45. The split that best separates the classes wins. Best is measured by how pure the two sides become.
Purity is usually measured by Gini impurity or entropy. A group with one class only is pure. A group split evenly across classes is impure. The tree tries every feature and threshold, keeps the purest split, and repeats inside each side until it stops.
The program below grows a tree two levels deep on the iris data. The first split is petal length at 2.45, which pulls out the setosa flowers. The second split is petal width at 1.75, which separates the other two species. The printed tree is the whole model.
from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier, export_text X, y = load_iris(return_X_y=True) model = DecisionTreeClassifier(max_depth=2, random_state=7).fit(X, y) print(export_text(model, feature_names=load_iris().feature_names)) Output: |--- petal length (cm) <= 2.45 | |--- class: 0 |--- petal length (cm) > 2.45 | |--- petal width (cm) <= 1.75 | | |--- class: 1 | |--- petal width (cm) > 1.75 | | |--- class: 2
23. What is a random forest, and why does it beat a single tree?
A random forest is many decision trees voting together. Each tree trains on a different random slice of the rows and a different random slice of the features. The forest predicts by majority vote. The randomness is the point, not a flaw.
A single tree overfits easily: it memorises quirks of its training data. A forest averages those quirks away. Each tree is wrong in its own way, and the vote cancels the individual mistakes. The forest keeps the trees' ability to find patterns while dropping most of their variance.
The program below trains 50 trees on the iris data and scores 0.911. It also prints which features mattered most: petal width 0.472, petal length 0.362, sepal length 0.124, and sepal width 0.043. The petals carry the signal, which matches the tree in question 22.
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=7)
model = RandomForestClassifier(n_estimators=50, random_state=7)
model.fit(X_train, y_train)
print("accuracy:", round(model.score(X_test, y_test), 3))
print("importances:", [round(float(v), 3) for v in model.feature_importances_])
Output:
accuracy: 0.911
importances: [0.124, 0.043, 0.362, 0.472]24. What is the difference between bagging and boosting?
Bagging trains many models in parallel on random slices of the data and averages their answers. Each model sees a different slice, so their mistakes differ, and the average cancels them. A random forest is bagging with trees.
Boosting trains models in sequence, and each new model studies the last model's mistakes. The first model fits the data. The second fits what the first got wrong. The third fits what the second got wrong. The models add up into one strong model.
Bagging cuts variance, so it suits flexible models like deep trees. Boosting cuts bias, so it suits weak models like shallow trees. Boosting can overfit if left running too long, because each round chases the remaining errors harder.
25. How does gradient boosting work, and when do you pick XGBoost, LightGBM or sklearn's HistGradientBoosting?
Gradient boosting builds trees one at a time, and each tree predicts the errors of all the trees before it. The errors are gradients of the loss, which is where the name comes from. Each tree is small and shallow. Hundreds of them add up to a strong model.
XGBoost, LightGBM, and sklearn's HistGradientBoostingClassifier all do the same job with different speed tricks. XGBoost is the veteran and the most tuned. LightGBM grows leaf by leaf and is often fastest on wide data. HistGradientBoostingClassifier is built into scikit-learn and needs no extra install.
The program below trains sklearn's gradient boosting on the iris data and scores 0.911. On tabular data, gradient boosting usually beats a random forest, and it is the first model to try in a competition. The pick between the three is usually about speed and habit, not accuracy.
from sklearn.datasets import load_iris
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=7)
model = HistGradientBoostingClassifier(random_state=7)
model.fit(X_train, y_train)
print("accuracy:", round(model.score(X_test, y_test), 3))
Output:
accuracy: 0.91126. How does k-nearest neighbours work, and what breaks it?
K-nearest neighbours stores every training example and answers by vote. A new point arrives, and the model finds the k closest training points. The majority label among them is the answer. There is no training step. The data is the model.
Two things break it. Unscaled features break it, because a feature measured in thousands drowns one measured in tenths. Distance is meaningless until the scales match. Large data breaks it too, because every prediction scans the whole training set.
The program below tries k values of 1, 3, and 11 on the iris data. The scores are 0.933, 0.933, and 0.911. A k of 1 is jumpy, because one noisy neighbour decides the answer. A k of 11 is smoother, but it starts to blur the borders between classes.
from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=7)
for k in (1, 3, 11):
model = KNeighborsClassifier(n_neighbors=k).fit(X_train, y_train)
print("k =", k, "accuracy:", round(model.score(X_test, y_test), 3))
Output:
k = 1 accuracy: 0.933
k = 3 accuracy: 0.933
k = 11 accuracy: 0.91127. How does a support vector machine work?
A support vector machine draws the line that separates the classes with the widest gap. The line sits as far as possible from the nearest points on both sides. Those nearest points are the support vectors. They alone decide where the line goes.
The kernel trick lets the same idea work on curved borders. A kernel measures similarity in a richer space without ever building that space. A linear kernel keeps straight borders. An RBF kernel bends the border around the data.
The program below tries both kernels on the iris data. The linear kernel scores 0.933 and the RBF kernel scores 0.889. The linear kernel wins here because the iris classes are nearly separable by straight lines. A kernel is a choice, not a magic upgrade.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=7)
for kernel in ("linear", "rbf"):
model = SVC(kernel=kernel).fit(X_train, y_train)
print(kernel, "accuracy:", round(model.score(X_test, y_test), 3))
Output:
linear accuracy: 0.933
rbf accuracy: 0.88928. How does naive Bayes work, and when is it a good pick?
Naive Bayes applies Bayes' rule with one bold assumption: the features are independent given the class. The model counts how often each feature value appears with each class, then multiplies those counts into a probability. Independent is the naive part, and the data rarely obeys it.
The assumption is wrong and the model still works. It works because classification needs the right ranking, not exact probabilities. It trains on tiny data, runs fast, and handles text well, where word counts are the features.
The program below trains a Gaussian naive Bayes model on the iris data and scores 0.889. It loses to the forest and the SVM on this data set. Its home is spam filtering and text classification, where its speed and small appetite for data matter more than a few points of accuracy.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=7)
model = GaussianNB().fit(X_train, y_train)
print("accuracy:", round(model.score(X_test, y_test), 3))
Output:
accuracy: 0.88929. How does k-means clustering work?
K-means splits data into k groups by moving centres. It starts with k centres placed at random points. Every point joins its nearest centre. Then each centre moves to the middle of its group. The two steps repeat until the centres stop moving.
The result depends on the starting centres, so the method runs several times and keeps the best run. Best means the smallest total distance from points to their centres. The method finds round groups well and fails on stretched or oddly shaped ones.
The program below runs k-means from scratch in NumPy on two clouds of 20 points each. After ten rounds the centres sit at (0.01, -0.11) and (4.04, 3.94), almost exactly where the clouds were made. Both clusters hold 20 points.
import numpy as np
rng = np.random.RandomState(7)
X = np.vstack([rng.normal(loc=[0, 0], scale=0.5, size=(20, 2)),
rng.normal(loc=[4, 4], scale=0.5, size=(20, 2))])
centres = X[[0, 20]]
for _ in range(10):
dist = np.linalg.norm(X[:, None, :] - centres[None, :, :], axis=2)
labels = dist.argmin(axis=1)
centres = np.array([X[labels == k].mean(axis=0) for k in range(2)])
print("centres:", [[round(float(v), 2) for v in c] for c in centres])
print("cluster sizes:", [int((labels == k).sum()) for k in range(2)])
Output:
centres: [[0.01, -0.11], [4.04, 3.94]]
cluster sizes: [20, 20]30. How do you pick the number of clusters?
The elbow method plots the total distance, called inertia, against k. Each extra cluster cuts the distance. The cut is large while real groups are still being found, then small once the groups are split for no reason. The bend in the curve is the elbow, and it marks the right k.
The elbow is a guide, not a proof. It is often a soft bend rather than a sharp corner. Silhouette scores give a second opinion: they measure how close each point sits to its own cluster against the nearest other cluster. A high average silhouette means tight, well-separated groups.
The program below measures inertia for k from 1 to 4 on three clouds. The values are 716.2, 286.5, 41.8, and 35.5. The drop from 2 to 3 is huge and the drop from 3 to 4 is tiny. The elbow is at 3, which is the true number of clouds.
import numpy as np
from sklearn.cluster import KMeans
rng = np.random.RandomState(7)
X = np.vstack([rng.normal(loc=[0, 0], scale=0.5, size=(30, 2)),
rng.normal(loc=[4, 4], scale=0.5, size=(30, 2)),
rng.normal(loc=[0, 4], scale=0.5, size=(30, 2))])
for k in (1, 2, 3, 4):
model = KMeans(n_clusters=k, n_init=10, random_state=7).fit(X)
print("k =", k, "inertia:", round(model.inertia_, 1))
Output:
k = 1 inertia: 716.2
k = 2 inertia: 286.5
k = 3 inertia: 41.8
k = 4 inertia: 35.531. What is PCA, and when do you use it?
PCA, principal component analysis, turns many correlated features into a few new ones that carry most of the spread. The new features are called components. The first component points along the widest spread in the data. The second points along the next widest, at a right angle to the first.
PCA is used to see high-dimensional data, to shrink it before a slow model, and to remove noise. It is not used to pick features: a component mixes all the original features, so the result is harder to explain than the inputs were.
The program below reduces the four iris measurements to two components. The first carries 0.925 of the variance and the second 0.053. Together they carry 0.978, so almost nothing is lost. The first flower lands at (-2.68, 0.32) in the new space.
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
X, y = load_iris(return_X_y=True)
model = PCA(n_components=2).fit(X)
print("explained variance:", [round(float(v), 3) for v in model.explained_variance_ratio_])
print("first point in 2D:", [round(float(v), 2) for v in model.transform(X[:1])[0]])
Output:
explained variance: [0.925, 0.053]
first point in 2D: [-2.68, 0.32]32. Why do you scale features, and which methods exist?
Features arrive in different units. Income runs in thousands, age in tens. A model that measures distance lets the big numbers decide everything. Scaling puts the features on shared ground so each one gets a fair hearing.
Standardisation subtracts the mean and divides by the spread, so each feature ends up with mean 0 and spread 1. Min-max scaling squeezes each feature into the range 0 to 1. Standardisation suits most models. Min-max suits models that need bounded inputs, like neural networks.
The program below scales the same three rows both ways. Standardised, the rows become (-1.22, -1.22), (0.0, 0.0), and (1.22, 1.22). Min-max, they become (0.0, 0.0), (0.5, 0.5), and (1.0, 1.0). Tree models do not need scaling. Distance models and gradient models do.
import numpy as np
from sklearn.preprocessing import MinMaxScaler, StandardScaler
X = np.array([[1000.0, 2.0], [2000.0, 4.0], [3000.0, 6.0]])
print("standardised:", [[round(float(v), 2) for v in row]
for row in StandardScaler().fit_transform(X)])
print("min-max:", [[round(float(v), 2) for v in row]
for row in MinMaxScaler().fit_transform(X)])
Output:
standardised: [[-1.22, -1.22], [0.0, 0.0], [1.22, 1.22]]
min-max: [[0.0, 0.0], [0.5, 0.5], [1.0, 1.0]]33. What is the curse of dimensionality?
The curse of dimensionality is what happens as features pile up. The data thins out, because the volume of the space grows far faster than the number of points. Every point ends up far from every other point, and near stops meaning anything.
Distance-based methods suffer first. K-nearest neighbours loses its neighbours. Clustering loses its clusters. Even the idea of a typical point breaks down, because the centre of a high-dimensional space is empty.
The cures are to cut features or compress them. Feature selection drops the useless columns. PCA compresses the rest into fewer components, which is the subject of question 31. More data helps too, but the volume grows so fast that data alone rarely saves a very wide table.
34. How do you choose features: filter, wrapper and embedded methods?
Filter methods score each feature on its own, before any model trains. A statistical test ranks the features, and the top few are kept. The method is fast and simple, but it cannot see how features work together.
Wrapper methods train a model on many feature sets and keep the set that scores best. The method sees combinations, but it is slow: every set needs a fresh training run. Embedded methods choose features while the model trains. Lasso is the classic example, because it drives useless weights to zero.
The program below uses a filter method, SelectKBest, on the iris data. It keeps petal length and petal width, with scores of 1180.2 and 960.0, ahead of sepal length at 119.3 and sepal width at 49.2. The petals carry the signal, which matches questions 22 and 23.
from sklearn.datasets import load_iris
from sklearn.feature_selection import SelectKBest, f_classif
X, y = load_iris(return_X_y=True)
sel = SelectKBest(f_classif, k=2).fit(X, y)
print("kept:", [load_iris().feature_names[i]
for i in sel.get_support(indices=True)])
print("scores:", [round(float(s), 1) for s in sel.scores_])
Output:
kept: ['petal length (cm)', 'petal width (cm)']
scores: [119.3, 49.2, 1180.2, 960.0]35. What is an sklearn Pipeline, and why does it matter?
A Pipeline chains preparation and modelling into one object. The data flows through scaling, then encoding, then the model, in order. One call fits the whole chain. One call predicts with it.
The chain matters for two reasons. It stops leakage, because each step is fitted on training data only, inside the cross-validation folds. And it stops mistakes, because the same steps run in training and in production, with no step forgotten in between.
The program below chains a scaler and a logistic regression, then scores it on held-out iris flowers. The accuracy is 0.911. The pipeline is one object, so it can be saved, loaded, and tuned as a whole, which questions 38 and 39 use.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=7)
pipe = Pipeline([("scale", StandardScaler()),
("model", LogisticRegression(max_iter=500))])
pipe.fit(X_train, y_train)
print("accuracy:", round(pipe.score(X_test, y_test), 3))
Output:
accuracy: 0.91136. How do you handle missing values?
Missing values are gaps in the table, and most models refuse them. Three responses exist. Drop the rows with gaps, when the gaps are few. Fill the gaps, when they are many. Or use a model that accepts gaps natively, like gradient boosting.
Filling is usually better than dropping. A common fill is the median for numbers and the most common value for words. The median resists outliers better than the mean. The fill value must come from the training data only, never from the whole table.
The program below fills a small table with the SimpleImputer. The missing age becomes 35, the median of 25, 35, and 40. The missing city becomes York, the most common value. The Finding Missing Values lesson shows how gaps are found, and the Fixing Missing Values lesson shows how they are repaired.
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
df = pd.DataFrame({"age": [25, np.nan, 35, 40],
"city": ["York", "Leeds", np.nan, "York"]})
num = SimpleImputer(strategy="median").fit_transform(df[["age"]])
cat = SimpleImputer(strategy="most_frequent").fit_transform(df[["city"]])
print("ages filled:", [int(v) for v in num.flatten()])
print("cities filled:", list(cat.flatten()))
Output:
ages filled: [25, 35, 35, 40]
cities filled: ['York', 'Leeds', 'York', 'York']37. How do you encode categorical variables?
Categorical variables are words, like a colour or a city. Most models need numbers, so the words must be turned into numbers first. The choice of encoding changes what the model can learn.
One-hot encoding makes one column per value, holding 1 or 0. It suits words with no order, like colours. Ordinal encoding numbers the values in order, like small, medium, large. It suits words that rank. Label encoding numbers the values without order, which misleads most models and should be avoided for features.
The program below one-hot encodes four colours. The columns come out as colour_blue, colour_green, and colour_red. Red becomes (0, 0, 1), blue becomes (1, 0, 0), and green becomes (0, 1, 0). Each row has exactly one 1.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({"colour": ["red", "blue", "red", "green"]})
enc = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
out = enc.fit_transform(df[["colour"]])
print("columns:", list(enc.get_feature_names_out()))
print("encoded:", [[int(v) for v in row] for row in out])
Output:
columns: ['colour_blue', 'colour_green', 'colour_red']
encoded: [[0, 0, 1], [1, 0, 0], [0, 0, 1], [0, 1, 0]]38. How do you tune hyperparameters with GridSearchCV?
Hyperparameters are the settings chosen before training, like the k in k-nearest neighbours or the depth of a tree. They are not learned from data. They are picked by trying values and measuring the result.
GridSearchCV tries every combination in a grid and measures each one with cross-validation. It keeps the combination with the best average score. The grid is the list of values to try. Cross-validation is what keeps the choice honest.
The program below searches k values of 1, 3, and 5 for a nearest-neighbour model on the iris data. The best k is 3, with a cross-validation score of 0.981 and a test score of 0.933. Grid search is slow on big grids, so random search often replaces it there.
from sklearn.datasets import load_iris
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.neighbors import KNeighborsClassifier
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=7)
grid = GridSearchCV(KNeighborsClassifier(),
{"n_neighbors": [1, 3, 5]}, cv=3)
grid.fit(X_train, y_train)
print("best k:", grid.best_params_["n_neighbors"])
print("best CV score:", round(grid.best_score_, 3))
print("test score:", round(grid.score(X_test, y_test), 3))
Output:
best k: 3
best CV score: 0.981
test score: 0.93339. How do you save a trained model and load it later?
A trained model is an object in memory, and it vanishes when the program ends. Saving writes it to a file. Loading reads it back, ready to predict. The file holds the weights, the settings, and the learned state.
Scikit-learn models are usually saved with joblib, which handles the large number arrays well. Pickle works too, but joblib is faster for models. A saved model must be loaded with the same library versions that saved it, or the file may not open.
The program below trains a logistic regression on iris flowers, saves it to iris_model.joblib, and loads it back. The loaded model predicts 0 for the first flower, and the true label is 0. The PyTorch Saving and Loading Models lesson shows the same idea for a neural network.
import joblib
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
model = LogisticRegression(max_iter=500).fit(X, y)
joblib.dump(model, "iris_model.joblib")
loaded = joblib.load("iris_model.joblib")
print("prediction for first flower:", int(loaded.predict(X[:1])[0]))
print("true label:", int(y[0]))
Output:
prediction for first flower: 0
true label: 040. What error do you get when you fit on raw text, and how do you fix it?
Fitting a model on raw words fails. Scikit-learn models need numbers, and a column of colour names is not numbers. The fit call raises an error instead of training. The error names the first value it could not convert.
The program below fits a logistic regression on a small table with a colour column holding red and blue. It fails with one line: ValueError: could not convert string to float: 'red'. The fix is to encode the words first, as question 37 shows, or to build a pipeline that encodes them, as question 35 shows.
The error is useful, because it fails loudly at training time. The dangerous version of this bug is a column that looks numeric but holds words in a few rows. That fails the same way, but only when those rows are reached. The Python Errors & Tracebacks lesson shows how to read an error like this one.
import pandas as pd
from sklearn.linear_model import LogisticRegression
df = pd.DataFrame({"colour": ["red", "blue", "red", "blue"],
"size": [1, 2, 3, 4]})
y = [0, 1, 0, 1]
model = LogisticRegression(max_iter=500)
model.fit(df, y)
Output:
ValueError: could not convert string to float: 'red'41. How would you design a recommendation system?
A recommendation system answers one question: what should this person see next. Start with the signal: clicks, purchases, and ratings are the usual ones. Then pick the approach. Collaborative filtering learns from what similar people liked. Content filtering learns from what the item is like. Most real systems mix both.
The design has four parts. Candidate generation picks a few hundred items from millions. Ranking orders those few hundred by predicted interest. Serving returns the top few in under a tenth of a second. Feedback closes the loop, because every click and skip becomes tomorrow's training data.
Two traps deserve naming. The cold start: a new user or item has no history, so the system falls back to popularity or content. The filter bubble: the system only shows more of the same, so a little randomness is added on purpose. The Recommendation and Ranking lesson in the System Design ML course walks through the same design.
42. How would you design a fraud detection system?
A fraud system answers one question: is this transaction genuine. The data is imbalanced, with honest transactions outnumbering fraud by hundreds to one. Accuracy is useless here, as question 14 shows. Recall on the fraud class is the number that matters.
The design has three layers. Rules catch the known patterns at once: a card used in two countries within an hour. A model scores the rest: amount, merchant, device, and history feed a classifier. A review queue holds the uncertain cases for a human, because a wrong block costs a customer.
Speed matters as much as accuracy. The score must return before the payment clears, usually in well under a second. That rules out slow models and heavy features. The features must be computable in real time, from data already in hand.
43. What is training-serving skew, and how do you stop it?
Training-serving skew is when the model sees different data in production from the data it trained on. The features are computed differently, or the live data has shifted. The model behaves worse live than its test score promised, and nobody knows why until the gap is found.
A common cause is two code paths: one that builds features for training, another that builds them live. They drift apart quietly. Another cause is time: a feature that uses the future during training, like a label recorded after the event, is missing live.
The fix is one shared path. The same code builds features for training and for serving. A feature store holds that shared code and the stored values. The Training, Serving and Evaluation lesson in the System Design ML course covers the same split.
44. How do you spot that a model has degraded in production?
A model degrades when the world moves under it. People change, products change, and the data follows. The model's predictions get worse, often slowly, and the drop is easy to miss if nobody watches.
Three watches catch it. Input monitoring tracks the features: means, spreads, and missing rates, against the training values. Prediction monitoring tracks the outputs: the share of each class, and the average score. Outcome monitoring tracks the truth where it arrives, even late: chargebacks, clicks, or churn.
The program below is the simplest input watch: compare the mean of one feature before and after. The mean moves from 24.87 to 28.02, a shift of 3.15. A shift that size means the live data no longer matches the training data, and the model needs a look.
import numpy as np
rng = np.random.RandomState(7)
before = rng.normal(loc=25.0, scale=2.0, size=500)
after = rng.normal(loc=28.0, scale=2.0, size=500)
print("mean before:", round(before.mean(), 2))
print("mean after:", round(after.mean(), 2))
print("shift:", round(after.mean() - before.mean(), 2))
Output:
mean before: 24.87
mean after: 28.02
shift: 3.1545. What is a feature store, and when does a team need one?
A feature store is a shared home for features. It stores the code that builds each feature, the values already computed, and the history of both. Training and serving read from the same store, so the features match on both sides.
A team needs one when features are rebuilt in several places, or when training and serving disagree. The first sign is a model that scores well offline and badly live. The second sign is two teams building the same feature twice, differently.
A small team with one model does not need a feature store. A shared module with one function per feature does the same job at that size. The store earns its keep when many models share many features, and the cost of a mismatch grows with every model.
46. How would you design a RAG pipeline?
RAG, retrieval-augmented generation, answers a question by first finding the relevant documents, then letting a language model write the answer from them. The model does not rely on its memory. It reads the retrieved text and answers from that.
The pipeline has four parts. Chunking splits documents into short passages. Embedding turns each passage into a vector. Retrieval finds the passages closest to the question. Generation hands those passages to the model with the question and asks for an answer grounded in them.
Two details decide quality. Chunk size: too big and the passage drowns the answer, too small and the context breaks. Retrieval depth: too few passages and the answer misses facts, too many and the model ignores the best ones. The Data, Features and Embeddings lesson in the System Design ML course covers the embedding half of this design.
47. When do you fine-tune, use RAG, or just prompt?
Prompting is first when the knowledge already sits in the model. Write a clear instruction, give a few examples, and the model answers. It costs nothing to set up and nothing to maintain. It fails when the knowledge is private, new, or changing.
RAG is first when the knowledge lives in documents the model never saw. The documents are retrieved at answer time, so new facts need no retraining. It fails when the answer needs deep reasoning across many documents, or when retrieval keeps missing the right passage.
Fine-tuning is first when the behaviour must change: a new tone, a new format, or a narrow task done the same way every time. It costs data, compute, and upkeep, and it does not add facts reliably. The rule of thumb is prompt first, RAG second, fine-tune last.
48. What is LoRA, and how do you judge whether RAG answers are good?
LoRA, low-rank adaptation, fine-tunes a large model by training two small matrices instead of the whole model. The base model stays frozen. The small matrices learn the change, and they are added back at run time. The result trains on one graphics card instead of a cluster, and the adapter file stays small enough to swap.
Judging RAG answers needs more than a single score. Faithfulness asks whether every claim in the answer appears in the retrieved passages. Answer relevance asks whether the answer addresses the question asked. Context recall asks whether the retrieval found the passages the answer needed.
These three are the core of the RAGAS evaluation set. They are measured by a second model judging the first, which is imperfect but practical. A RAG system also needs a guard against prompt injection: retrieved text can carry instructions, and the model must treat it as data, never as orders.
49. Coding task: build a full classification pipeline end to end.
Build one pipeline that does everything: scale the features, train a random forest, tune the number of trees, and score the result on held-out data. The data is synthetic, made with make_classification: 200 rows, 6 features, 4 of them carrying signal.
The pipeline chains a scaler and a forest. Grid search tries 50 and 100 trees with 3-fold cross-validation. The best choice is 50 trees, with a cross-validation score of 0.887. The held-out test accuracy is 0.84.
The test score sits below the cross-validation score, which is normal: the test set is one fresh draw, and fresh draws vary. The gap is small, so the model is steady. The Python Project: A Data Cleaning Pipeline lesson builds the same shape of pipeline on real messy data.
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(n_samples=200, n_features=6,
n_informative=4, random_state=7)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=7)
pipe = Pipeline([("scale", StandardScaler()),
("model", RandomForestClassifier(random_state=7))])
grid = GridSearchCV(pipe, {"model__n_estimators": [50, 100]}, cv=3)
grid.fit(X_train, y_train)
print("best trees:", grid.best_params_["model__n_estimators"])
print("best CV score:", round(grid.best_score_, 3))
print("test accuracy:", round(grid.score(X_test, y_test), 3))
Output:
best trees: 50
best CV score: 0.887
test accuracy: 0.8450. Coding task: run a tiny neural network forward pass by hand.
A neural network is layers of weighted sums passed through a curve. This task runs one forward pass on the XOR problem, with hand-set weights that solve it. The hidden layer has two units: the first acts as OR, the second as AND. The output takes the first minus the second.
The program multiplies the four inputs by the first weight matrix, adds the bias, and applies the sigmoid curve. Then it multiplies the hidden values by the second weight matrix, adds its bias, and applies the sigmoid again. No training happens here. The weights were chosen by hand.
The predictions come out as 0.0, 1.0, 1.0, and 0.0, which round to 0, 1, 1, and 0. The true labels are 0, 1, 1, and 0. The network gets all four right. Training is the process that finds weights like these automatically, one small step at a time. The PyTorch A Model by Hand lesson builds the same idea with real tensors.
import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([0, 1, 1, 0])
# Hand-set weights that solve XOR: hidden unit 1 is OR,
# hidden unit 2 is AND, the output is unit 1 minus unit 2.
W1 = np.array([[20.0, 20.0], [20.0, 20.0]])
b1 = np.array([-10.0, -30.0])
W2 = np.array([[20.0], [-20.0]])
b2 = np.array([-10.0])
h = sigmoid(X @ W1 + b1)
out = sigmoid(h @ W2 + b2).flatten()
print("predictions:", [round(float(v), 3) for v in out])
print("rounded:", [int(v > 0.5) for v in out])
print("true labels:", [int(v) for v in y])
Output:
predictions: [0.0, 1.0, 1.0, 0.0]
rounded: [0, 1, 1, 0]
true labels: [0, 1, 1, 0]Questions readers ask
How do I plan my week around this sheet?
Take one group per day and keep them in order. Try each answer yourself first, then run its program. Hold the coding tasks for the final day, along with any questions that gave you trouble. A steady hour each day teaches more than one long session the night before.
Do I need Python and scikit-learn before I begin?
Only if you want to run the programs. Python comes from python.org, and scikit-learn installs with pip install scikit-learn. The versions used here are Python 3.12.3 and scikit-learn 1.9.1. Reading needs no setup at all, but the programs are where the ideas turn concrete.
What is the next step after this sheet?
Pandas Beginner builds the data skills behind the answers. PyTorch Beginner builds the deep learning and the training loop. The System Design ML course builds the production half of the design questions. A Machine Learning Beginner course is still missing. This sheet is the first piece of it.
Can I use this sheet with no Python background?
Yes. Python Beginner starts from a first program and explains each idea when it first appears. A background in another language makes loops and functions easier, but the sheet never counts on it. The statistics ideas are explained where they show up, so no reader meets them unprepared.