Docsity

MACHINE LEARNING COMPREHENSIVE COURSE NOTES ALGORITHMS, PYTHON IMPLEMENTATIONS, AND PRACTI, Exams of Computer Science

Partial preview of the text

Download MACHINE LEARNING COMPREHENSIVE COURSE NOTES ALGORITHMS, PYTHON IMPLEMENTATIONS, AND PRACTI and more Exams Computer Science in PDF only on Docsity!

MACHINE LEARNING COMPREHENSIVE COURSE NOTES ALGORITHMS, PYTHON IMPLEMENTATIONS, AND PRACTICE PROBLEMS LATEST VERSION 2026/

Machine Learning

Comprehensive Course Notes

Algorithms, Python Implementations, and Practice Problems

1. What Is Machine Learning?

Machine learning (ML) is the study of algorithms that improve their performance on a task through experience, typically expressed as data, rather than through explicit hand- written rules. Formally, following Tom Mitchell's definition: a program learns from experience E with respect to task T and performance measure P if its performance on T, as measured by P, improves with E. ML problems are usually grouped into three broad categories. Supervised learning uses labeled examples (input-output pairs) to learn a mapping from inputs to outputs; this covers regression (continuous output) and classification (discrete output). Unsupervised learning works with unlabeled data to discover structure, such as clusters or lower- dimensional representations. Reinforcement learning trains an agent to choose actions in an environment to maximize cumulative reward. A typical supervised pipeline: collect and clean data, split into training/validation/test sets, choose a model class and loss function, fit parameters by minimizing loss on the training set, tune hyperparameters using the validation set, and finally report performance on the held-out test set. The central tension throughout is the bias-variance tradeoff: a model that is too simple underfits (high bias), while a model that is too complex overfits (high variance) and fails to generalize to new data. A minimal supervised-learning workflow with scikit-learn from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error

X: feature matrix (n_samples, n_features), y: targets

X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42) model = LinearRegression() model.fit(X_train, y_train) predictions = model.predict(X_test) mse = mean_squared_error(y_test, predictions) print(f"Test MSE: {mse:.4f}")

2. Linear Regression

Linear regression models the relationship between input features x and a continuous target y as a linear function: y_hat = w^T x + b, where w is a weight vector and b is a bias (intercept) term. Learning means choosing w and b that minimize a loss function over the training data, almost always the mean squared error (MSE): L(w, b) = (1/n) * sum( (y_i - y_hat_i)^2 ).

threshold (commonly 0.5) is applied to p to produce a hard 0/1 label; the threshold can be moved to trade off precision against recall. Despite the name, logistic regression is a classifier, not a regression method in the sense of predicting a continuous quantity — the 'regression' refers to regressing the log-odds, log(p / (1-p)), which is exactly the linear function z. Multiclass problems are handled either with one-vs-rest logistic regression or with its natural generalization, softmax regression. Logistic regression with scikit-learn, including the decision boundary from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train_s = scaler.fit_transform(X_train) X_test_s = scaler.transform(X_test) clf = LogisticRegression() clf.fit(X_train_s, y_train) probabilities = clf.predict_proba(X_test_s)[:, 1] predictions = (probabilities >= 0.5).astype(int) print('Weights:', clf.coef_, 'Bias:', clf.intercept_)

4. k-Nearest Neighbors (k-NN)

k-NN is a non-parametric, instance-based method: it stores the entire training set and, to classify a new point, finds the k closest training points (by some distance metric, usually Euclidean) and predicts the majority label among them (for classification) or the average value (for regression). There is no explicit training phase beyond storing the data — all the computation happens at prediction time, which is why k-NN is sometimes called a 'lazy learner'. The choice of k controls the bias-variance tradeoff directly: small k (e.g., k=1) makes the decision boundary very flexible and sensitive to noise (low bias, high variance); large k smooths the boundary and can underfit (high bias, low variance). k is typically chosen via cross-validation. Because k-NN relies on distance, feature scaling is essential — an unscaled feature with a large numeric range will dominate the distance calculation. k-NN suffers from the curse of dimensionality: as the number of features grows, all points tend to become roughly equidistant from each other, which erodes the meaningfulness of 'nearest'. It also scales poorly at prediction time for large training sets unless paired with spatial indexing structures such as KD-trees or ball trees. k-NN classification and choosing k via cross-validation

from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import cross_val_score import numpy as np best_k, best_score = None, - np.inf for k in range(1, 21): knn = KNeighborsClassifier(n_neighbors=k) scores = cross_val_score(knn, X_train_s, y_train, cv=5) if scores.mean() > best_score: best_k, best_score = k, scores.mean() print(f"Best k = {best_k}, CV accuracy = {best_score:.3f}") final_model = KNeighborsClassifier(n_neighbors=best_k) final_model.fit(X_train_s, y_train)

5. Decision Trees

A decision tree makes predictions by recursively splitting the feature space into regions, following a series of if/else tests on individual features (e.g., 'is petal length < 2.5?'). Each internal node represents a test, each branch a possible outcome, and each leaf a predicted label or value. Trees are built greedily, top-down: at each node the algorithm searches over features and thresholds for the split that most increases 'purity' of the resulting child nodes. For classification, purity is commonly measured with the Gini impurity, Gini = 1 - sum(p_k^2) over classes k, or with entropy, H = - sum(p_k * log2(p_k)). A split is chosen to maximize information gain: the reduction in impurity from parent to weighted-average of children. For regression trees, splits instead minimize the variance (or MSE) of the target within each child node. Left unconstrained, a decision tree will keep splitting until every leaf is pure, which almost always overfits. Practical control is exercised via hyperparameters: max_depth, min_samples_split, min_samples_leaf, and cost-complexity pruning. Trees have the major advantage of being directly interpretable and requiring no feature scaling, but a single tree is unstable — small changes in the data can produce a very different tree, which motivates ensemble methods. Fitting and pruning a decision tree classifier from sklearn.tree import DecisionTreeClassifier, export_text tree = DecisionTreeClassifier( criterion='gini', max_depth=4, min_samples_leaf=5, random_state=0) tree.fit(X_train, y_train) print(export_text(tree, feature_names=feature_names)) print('Test accuracy:', tree.score(X_test, y_test))

separating hyperplane) tends to produce better generalization. The optimization problem is: minimize (1/2)||w||^2 subject to y_i(w^T x_i + b) >= 1 for all i, for linearly separable data. For data that is not perfectly separable, the soft-margin SVM introduces slack variables and a regularization parameter C, trading off margin width against classification error: a small C allows more misclassification for a wider margin (more regularization, less overfitting), while a large C penalizes misclassification heavily (less regularization, closer fit to training data). The kernel trick allows SVMs to learn non-linear decision boundaries without explicitly mapping data into a higher-dimensional space. Instead of computing features phi(x) directly, a kernel function K(x_i, x_j) = phi(x_i)^T phi(x_j) is computed directly from the original inputs. Common kernels include the polynomial kernel and the RBF (Gaussian) kernel, K(x_i, x_j) = exp(-gamma * ||x_i - x_j||^2), whose gamma parameter controls how far the influence of a single training example reaches. SVM with an RBF kernel and a small grid search over C and gamma from sklearn.svm import SVC from sklearn.model_selection import GridSearchCV param_grid = {'C': [0.1, 1, 10, 100], 'gamma': [0.001, 0.01, 0.1, 1 ]} grid = GridSearchCV(SVC(kernel='rbf'), param_grid, cv=5) grid.fit(X_train_s, y_train) print('Best params:', grid.best_params_) best_svm = grid.best_estimator_ print('Test accuracy:', best_svm.score(X_test_s, y_test))

8. Naive Bayes

Naive Bayes classifiers apply Bayes' theorem, P(y | x) proportional to P(y) * P(x | y), with the 'naive' simplifying assumption that features are conditionally independent given the class: P(x | y) = product over features of P(x_j | y). This assumption is almost never exactly true in practice, but the resulting classifier is often surprisingly effective, especially for high-dimensional, sparse data such as text. For continuous features, Gaussian Naive Bayes assumes each feature is normally distributed within each class and estimates a per-class mean and variance. For discrete count data, Multinomial Naive Bayes is standard for text classification with bag-of-words or TF-IDF features, while Bernoulli Naive Bayes handles binary (present/absent) features. Training is extremely fast, since it only requires estimating simple per-class statistics (means, variances, or counts) in a single pass over the data, with no iterative optimization. Naive Bayes is a strong, cheap baseline for text classification tasks such as spam filtering and sentiment analysis.

Multinomial Naive Bayes for text classification from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB vectorizer = TfidfVectorizer(stop_words='english', max_features=5000) X_train_tfidf = vectorizer.fit_transform(train_texts) X_test_tfidf = vectorizer.transform(test_texts) nb = MultinomialNB() nb.fit(X_train_tfidf, y_train) print('Accuracy:', nb.score(X_test_tfidf, y_test))

9. k-Means Clustering

k-Means is an unsupervised algorithm that partitions n points into k clusters, each represented by a centroid, so as to minimize the within-cluster sum of squared distances (inertia): sum over clusters of sum over points in that cluster of ||x - centroid||^2. It is an iterative, two-step algorithm: (1) assignment step — assign each point to its nearest centroid; (2) update step — recompute each centroid as the mean of the points assigned to it. These steps repeat until assignments stop changing (or change negligibly). k-Means is guaranteed to converge (inertia never increases), but only to a local optimum, and the result depends on the initial centroid positions. In practice, k-means++ initialization (choosing initial centroids that are spread out, probabilistically favoring points far from existing centroids) substantially improves results over purely random initialization, and running the algorithm multiple times with different seeds (n_init) and keeping the best result is standard practice. Choosing k is not determined by the algorithm itself. The elbow method plots inertia against k and looks for the point where additional clusters yield diminishing returns; the silhouette score measures how similar each point is to its own cluster versus other clusters and can be computed for a range of k values to pick the one that maximizes average silhouette. k-Means with the elbow method for choosing k from sklearn.cluster import KMeans import numpy as np inertias = [] k_values = range(1, 11) for k in k_values: km = KMeans(n_clusters=k, init='k-means++', n_init=10, random_state=0) km.fit(X) inertias.append(km.inertia_)

Plot k_values vs inertias and look for the 'elbow'

final_km = KMeans(n_clusters=4, init='k-means++', n_init=10, random_state=0) labels = final_km.fit_predict(X)

A multilayer perceptron (MLP) stacks layers of neurons: an input layer, one or more hidden layers, and an output layer. Because each layer is a linear transformation followed by a non-linearity, stacking layers lets the network represent non-linear functions that a single linear model cannot — this is the source of neural networks' expressive power. The output layer's activation depends on the task: linear (no activation) for regression, sigmoid for binary classification, softmax for multiclass classification. Training a neural network means minimizing a loss function over all the weights using backpropagation combined with gradient descent. Backpropagation is simply the chain rule applied systematically: it computes the gradient of the loss with respect to every weight by propagating the error backward from the output layer to the input layer, reusing intermediate computations layer by layer rather than recomputing them from scratch. In practice, variants of stochastic gradient descent such as Adam (which adapts the learning rate per-parameter using running estimates of the gradient's mean and variance) are used rather than plain gradient descent, because they converge faster and are less sensitive to the initial learning rate. A small feedforward network for classification, with scikit-learn's MLP from sklearn.neural_network import MLPClassifier mlp = MLPClassifier( hidden_layer_sizes=(64, 32), activation='relu', solver='adam', learning_rate_init=0.001, max_iter=500, random_state=0, ) mlp.fit(X_train_s, y_train) print('Test accuracy:', mlp.score(X_test_s, y_test)) The forward pass of a two-layer network, from scratch with NumPy import numpy as np def relu(z): return np.maximum(0, z) def sigmoid(z): return 1 / (1 + np.exp(-z)) def forward(X, W1, b1, W2, b2): z1 = X @ W1 + b a1 = relu(z1) z2 = a1 @ W2 + b a2 = sigmoid(z2) # output probability return a1, a

12. Evaluating Models: Metrics and Validation

Accuracy (fraction of correct predictions) is intuitive but can be misleading on imbalanced datasets — a classifier that always predicts the majority class can achieve high accuracy while being useless. The confusion matrix breaks predictions into true positives (TP), false positives (FP), true negatives (TN), and false negatives (FN), from which more informative metrics are derived: precision = TP / (TP + FP) answers 'of the items predicted positive, how many actually were?'; recall (sensitivity) = TP / (TP + FN) answers 'of the actual positives, how many did we find?'. The F1 score, the harmonic mean of precision and recall (F1 = 2 * precision * recall / (precision + recall)), summarizes both in a single number and is preferred over a simple average when one of the two is much worse than the other. The ROC curve plots the true positive rate against the false positive rate as the classification threshold varies, and the area under it (AUC) summarizes overall ranking quality independent of any single threshold choice. To estimate how a model will perform on unseen data, k-fold cross-validation splits the training data into k equal folds, trains on k- 1 folds and validates on the remaining fold, and repeats this k times so every fold serves as the validation set exactly once; the k scores are then averaged. This gives a much more reliable estimate of generalization performance than a single train/validation split, at the cost of k times the training time. Stratified k-fold, which preserves the class proportions in every fold, is preferred for classification with imbalanced classes. Full evaluation report: confusion matrix, precision/recall/F1, ROC-AUC from sklearn.metrics import (confusion_matrix, classification_report, roc_auc_score) y_pred = model.predict(X_test) y_proba = model.predict_proba(X_test)[:, 1] print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred)) print('ROC-AUC:', roc_auc_score(y_test, y_proba))

13. Overfitting, Regularization, and the Bias-Variance Tradeoff

Total prediction error can be decomposed into three parts: bias^2 (error from overly simplistic assumptions in the model), variance (error from sensitivity to the specific training sample), and irreducible noise. Simple models (e.g., low-degree polynomials, shallow trees, small k in k-NN) tend to have high bias and low variance — they underfit. Complex models (high-degree polynomials, deep trees, k=1 in k-NN) tend to have low bias and high variance — they overfit, memorizing noise in the training data rather than learning the general pattern.

running average of past gradients so that the optimizer keeps moving in a consistent direction rather than zig-zagging across a narrow valley. Adam combines momentum with an adaptive, per-parameter learning rate derived from running estimates of the first and second moments of the gradient, and is the most commonly used optimizer for training neural networks in practice. Mini-batch gradient descent from scratch import numpy as np def minibatch_gd(X, y, lr=0.01, epochs=50, batch_size=32): n_samples, n_features = X.shape w = np.zeros(n_features) b = 0. for epoch in range(epochs): perm = np.random.permutation(n_samples) X_shuffled, y_shuffled = X[perm], y[perm] for start in range(0, n_samples, batch_size): end = start + batch_size X_batch = X_shuffled[start:end] y_batch = y_shuffled[start:end] y_hat = X_batch @ w + b error = y_hat - y_batch m = X_batch.shape[0] dw = (2 / m) * (X_batch.T @ error) db = (2 / m) * np.sum(error) w - = lr * dw b - = lr * db return w, b

15. Putting It Together: Choosing an Algorithm

No single algorithm is best for every problem — this is sometimes called the 'no free lunch' principle. In practice, the choice is driven by the nature of the data, the size of the dataset, the need for interpretability, and the acceptable amount of training and inference time. Linear and logistic regression are strong starting points for any tabular problem: they train almost instantly, are easy to explain, and provide a baseline against which more complex models should be measured. If a much more complex model does not clearly beat this baseline on held-out data, the added complexity usually is not worth it. For tabular data with a moderate to large number of examples, tree-based ensembles (random forests and gradient-boosted trees) are usually the strongest general-purpose choice, since they handle non-linear relationships and feature interactions automatically and require little feature engineering. Support vector machines with an RBF kernel

remain competitive on small-to-medium datasets, particularly when the number of features is high relative to the number of examples. k-NN and Naive Bayes are cheap, easy-to-implement baselines: k-NN often does well when the notion of 'similarity' between examples is meaningful and the feature count is modest, and Naive Bayes remains a strong, fast baseline specifically for text classification. Neural networks earn their added training complexity primarily when the data has a lot of structure to exploit that hand-crafted features cannot easily capture — images, audio, text, or very large tabular datasets where the sheer volume of data lets a flexible model avoid overfitting. For small tabular datasets, a well-tuned gradient-boosted tree ensemble often outperforms a neural network with comparable effort. As a final practical note, the specific choice of algorithm is frequently less important than the quality of the features, the amount of clean training data, and rigorous validation methodology — a simple model evaluated correctly beats a sophisticated model evaluated carelessly. A short comparison, from the perspective of interpretability versus typical predictive strength on tabular data: linear/logistic regression sits at the interpretable end and is a strong, transparent baseline; decision trees are similarly interpretable and handle non- linearity, but a single tree is unstable; random forests and gradient boosting trade some interpretability for typically higher accuracy on tabular problems; SVMs with non-linear kernels and neural networks sit at the least-interpretable end but can capture the most complex patterns given sufficient data.

averaging over a larger, more diverse neighborhood also blurs genuine local structure in the data, pulling predictions toward the global average behavior — this increases bias. At the extreme, k = n (all training points) predicts the same global average/majority class for every input, which is maximum bias and minimum (zero) variance.

6. A random forest with 500 trees achieves 99% training accuracy but only 82% test accuracy. Name two hyperparameters you could adjust to reduce this overfitting, and explain the effect of each. Solution: (1) max_depth: reducing the maximum depth of each individual tree limits how finely it can carve up the feature space, forcing each tree to capture broader, more generalizable patterns rather than memorizing individual training points. (2) min_samples_leaf (or min_samples_split): increasing this requires each leaf to be supported by more training examples before a split is allowed, which prevents the trees from creating tiny, noise-fitting leaves. Reducing max_features (the number of features considered at each split) can also help by further decorrelating the trees, and reducing n_estimators rarely causes overfitting in a random forest specifically, since averaging more independent trees only reduces variance further. 7. Contrast bagging and boosting in terms of how the base models are trained and what type of error each primarily reduces. Solution: Bagging trains many base models independently and in parallel, each on a different bootstrap sample of the data, then averages their predictions; because the models are trained independently, bagging primarily reduces variance. Boosting trains base models sequentially, where each new model is trained to correct the errors of the ensemble built so far (via reweighting, as in AdaBoost, or by fitting residuals, as in gradient boosting); this primarily reduces bias, since the sequential correction process lets the ensemble represent increasingly complex functions, though boosting can increase variance/overfitting if run for too many rounds. 8. Explain what the C hyperparameter controls in a soft-margin SVM, and describe the model's behavior at very small vs. very large C. Solution: C controls the tradeoff between maximizing the margin and minimizing classification error on the training data (the penalty on the slack variables). A very small C makes misclassification cheap, so the optimizer prioritizes a wide margin even if that means some training points are misclassified or fall inside the margin — this is a heavily regularized, potentially underfit model. A very large C makes misclassification very costly, so the optimizer shrinks the margin and fits the training data as closely as possible, which can lead to overfitting, especially with noisy data. 9. Why is the RBF kernel's gamma parameter analogous to '1/k' in k-NN, conceptually? Solution: A large gamma makes the RBF kernel K(x_i, x_j) = exp(-gamma * ||x_i - x_j||^2) decay very quickly with distance, meaning each training point only strongly influences predictions very close to it — this is analogous to small k in k-NN (very local, low-bias, high-variance decisions). A small gamma makes the influence of each point reach much

farther, producing a smoother, more global decision boundary — analogous to large k (more bias, less variance). Both parameters, in effect, control the 'locality' of the decision function.

10. A spam classifier built with Multinomial Naive Bayes assumes word occurrences are conditionally independent given the class. Is this assumption realistic? Why does the classifier still tend to work well? Solution: The assumption is not realistic — word occurrences are clearly correlated (e.g., 'free' and 'prize' co-occur far more often than chance in spam). However, Naive Bayes only needs to get the ranking of P(spam|x) vs. P(not spam|x) right, not the exact probability values; the independence assumption distorts the magnitude of the estimated probabilities but often leaves their relative ordering (and hence the final classification decision) correct, especially when there is a strong aggregate signal from many mildly- informative words. 11. In k-means, why is the algorithm sensitive to the initial placement of centroids, and how does k-means++ address this? Solution: k-means only guarantees convergence to a local minimum of the inertia (within-cluster sum of squares); the specific local minimum reached depends on where the centroids start. Poor initialization (e.g., two initial centroids landing in the same true cluster) can trap the algorithm in a bad local optimum. k-means++ initializes centroids sequentially, choosing each new centroid with probability proportional to its squared distance from the nearest already-chosen centroid — this actively spreads initial centroids across the data, making it far more likely that each true cluster gets its own centroid from the start. 12. You run k-means for k = 2 through 10 and plot inertia vs. k, seeing a smooth, gradually decreasing curve with no clear 'elbow.' What does this suggest, and what alternative technique could help? Solution: A smooth curve with no elbow suggests the data may not have well-separated, roughly spherical clusters of the kind k-means is designed to find — the data may have a more continuous or non-globular structure. The silhouette score is a useful alternative: computed for each k, it directly measures how well-separated and internally cohesive the resulting clusters are, and can sometimes reveal a clearer optimal k even when the elbow method is ambiguous. It may also be worth considering whether k-means is the right algorithm at all versus, e.g., a density-based method like DBSCAN. 13. Explain, in terms of eigenvalues, what 'explained variance ratio' means for a principal component. Solution: Each principal component corresponds to an eigenvector of the data's covariance matrix, and its associated eigenvalue equals the variance of the data along that component's direction. The explained variance ratio for a component is its eigenvalue divided by the sum of all eigenvalues (total variance in the data) — i.e., the fraction of the data's total variance captured by that single direction. Summing the ratios for the top k

18. Why is the F1 score preferred over simple accuracy or a plain average of precision and recall in many classification settings? Solution: Accuracy is misleading on imbalanced data, as in the previous problem. A plain arithmetic average of precision and recall can stay moderately high even if one of the two is very low and the other is very high (e.g., precision = 0.99, recall = 0.10 averages to 0.545, which looks acceptable but hides that the model misses 90% of positives). The F score, the harmonic mean, is pulled down much more sharply when either precision or recall is low (the same example gives F1 = 0.18), so it more honestly reflects a model that is failing on one dimension even if it excels on the other. 1 9. Explain why k-fold cross-validation gives a more reliable performance estimate than a single train/validation split, and name one cost of using it. Solution: A single train/validation split's performance estimate depends heavily on which examples happened to land in the validation set — an unlucky split can make a good model look bad, or vice versa. k-fold cross-validation averages performance over k different validation folds, each disjoint from the others, so the final estimate is less sensitive to the luck of any one particular split, and every example contributes to the validation score exactly once. The main cost is computational: the model must be trained k times instead of once, which can be expensive for slow-to-train models or very large datasets. 20. A ridge regression model's cross-validated performance keeps improving as lambda decreases toward zero. What does this suggest about the appropriate amount of regularization for this problem, and what would lambda = 0 correspond to? Solution: If performance keeps improving as lambda approaches zero, it suggests the model is not overfitting in the first place — the unregularized model already generalizes well, so the regularization penalty is only doing harm by needlessly shrinking useful weights (i.e., it is currently underfitting relative to what plain linear regression could achieve). Lambda = 0 removes the regularization term entirely, making ridge regression mathematically equivalent to ordinary least squares linear regression. 21. Why does L1 (lasso) regularization tend to produce exactly-zero coefficients, while L2 (ridge) regularization tends to shrink coefficients toward zero without eliminating them? Solution: Geometrically, the L1 penalty region (a diamond in 2D, defined by |w1| + |w2| <= t) has sharp corners located exactly on the coordinate axes, and the loss function's elliptical contours are likely to first touch this region at one of those corners — which corresponds to one of the coefficients being exactly zero. The L2 penalty region (a circle/sphere, w1^2 + w2^2 <= t) is smooth with no corners, so the point where the loss contour first touches it generally has both coordinates nonzero, only shrunk in magnitude. This is why lasso is often used for automatic feature selection, while ridge is used purely to control coefficient magnitude.

22. Why does mini-batch gradient descent generally train faster in wall-clock time than full batch gradient descent, even though it requires more parameter updates per epoch? Solution: Full batch gradient descent computes one gradient using the entire dataset, requiring a full pass over all n examples before making even a single update. Mini-batch gradient descent makes many small, cheap updates per epoch, so the model starts improving from very early in training rather than waiting for a full pass; it also benefits from vectorized, hardware-parallelized matrix operations on each batch, which is typically far more efficient per-example than either processing one example at a time (pure SGD) or one enormous matrix operation on the full dataset (which may not even fit in memory or cache). 23. Describe what would happen to gradient descent's convergence if the learning rate alpha were set far too large, and how you would detect this from the training loss curve. Solution: If alpha is too large, each parameter update can overshoot the minimum of the loss surface by a wide margin, causing the parameters to bounce back and forth (or diverge outward) rather than settling toward the minimum. On a training loss curve, this shows up as the loss oscillating wildly from epoch to epoch, or increasing without bound (sometimes to NaN due to numerical overflow), rather than the smooth, generally- decreasing curve expected with a well-chosen learning rate. 24. A neural network trained with dropout achieves lower training accuracy than the same network trained without dropout, but higher test accuracy. Explain why. Solution: Dropout randomly deactivates a fraction of neurons on each training step, which prevents the network from relying too heavily on any single neuron or narrow co- adapted group of neurons to memorize training-specific patterns; this acts as a regularizer. Because the network can no longer fit the training data as precisely (it is effectively training many overlapping sub-networks that must each work reasonably well on their own), training accuracy drops. But this same constraint prevents overfitting, so the network generalizes better to unseen data, which raises test accuracy — a direct illustration of the bias-variance tradeoff in action. 25. You must choose between logistic regression and a gradient-boosted tree ensemble for a tabular dataset with 200,000 rows, 15 features, and a requirement that the final model's decisions be easily explained to a non-technical regulator. Which would you choose, and what are you trading off? Solution: Logistic regression is the stronger choice here given the explainability requirement: its decision is a simple, fixed linear combination of features with fixed weights, so each feature's contribution to any individual prediction can be stated directly and consistently ('each additional year of X increases the log-odds by this much'). A gradient-boosted ensemble would very likely achieve higher raw accuracy, since it can capture non-linear relationships and feature interactions that logistic regression cannot, but its decision process (hundreds of sequential trees) is far harder to explain simply, requiring post-hoc explanation tools (e.g., SHAP values) that approximate rather than