Exam practice
Machine Learning — Practice
Past-exam questions, filterable by chapter, year and difficulty. Answer for instant grading, reveal the worked solution, and watch your accuracy climb.
Seen 0 / 126 · 0 correct · 0% accuracy
Chapter
Year
Difficulty
- 2026-01-q1Explain the bias–variance trade-off in supervised learning. Define bias and variance, describe their relation to model complexity, and explain how they lead to underfitting and overfitting.
- 2026-02-q1Explain what the Kernel Trick is, what it is used for, and in which ML methods it can be used.
- 2026-06-q1Consider binary logistic regression with weights $\mathbf{w}$, where $p(y=1\mid\mathbf{x}) = \sigma(\mathbf{w}^\top\mathbf{x})$ and $\sigma(z) = \frac{1}{1+e^{-z}}$. 1. Write the per-sample cross-entropy (negative log-likelihood) loss $\ell(\mathbf{w})$ for a labelled example $(\mathbf{x}, y)$ with $y \in \{0, 1\}$. 2. Derive the gradient $\nabla_\mathbf{w}\,\ell(\mathbf{w})$. (You may use $\sigma'(z) = \sigma(z)(1 - \sigma(z))$.) 3. Explain in one or two sentences why the cross-entropy loss is preferred over the squared error $(y - \sigma(\mathbf{w}^\top\mathbf{x}))^2$ for training this model.
- 2026-01-q2Compare logistic regression and support vector machines. Discuss their loss functions, output interpretation, margin, regularization, and mention one scenario where each method is preferable.
- 2026-02-q2Explain the key idea behind Boosting and its main purpose. Describe how training and inference work in Boosting. Finally, give one example of a problem where Boosting is likely to be beneficial and one where it could be harmful or ineffective.
- 2026-06-q2Consider temporal-difference control with learning rate $\alpha$ and discount factor $\gamma$, in a transition $(s_t, a_t, r_{t+1}, s_{t+1})$ where the agent next selects action $a_{t+1}$. 1. Write the update rule of SARSA and of Q-learning for $Q(s_t, a_t)$, highlighting the only term in which they differ (the TD target). 2. Define on-policy and off-policy; classify SARSA and Q-learning, and identify precisely which element of the update rule makes each on- or off-policy. 3. Give one concrete example in which SARSA and Q-learning may converge to different policies, and say what the difference is and why it arises.
- 2026-01-q3Consider the Python snippet below. 1. Describe briefly what the code does and what learning task it is solving. 2. Explain the effect of the parameter `C=0.01` in this context. 3. Is computing the accuracy on `X_scaled` appropriate to evaluate performance? Why or why not?
X = dataset[['feature1', 'feature2']].values y = dataset['label'].values scaler = StandardScaler() X_scaled = scaler.fit_transform(X) model = LogisticRegression(C=0.01) model.fit(X_scaled, y) predictions = model.predict(X_scaled) accuracy = (predictions == y).mean() - 2026-02-q3Consider the Python code snippet below. 1. Describe the purpose of the snippet and explain what it does line by line. 2. What is the role of `C` in the SVM model used in the snippet? 3. Identify any methodological issues in the snippet. For each issue, propose a concrete fix (in words or pseudo-code).
1 X = dataset.drop(columns=["label"]).values 2 y = (dataset["label"].values == "spam") 3 4 Xtr, Xtest, ytr, ytest = train_test_split(X, y, test_size=0.3) 5 6 best_acc = -np.inf 7 best_clf = None 8 9 for C in [0.1, 1.0, 10.0]: 10 clf = SVC(C=C, kernel="rbf", gamma=0.5) 11 clf.fit(Xtr, ytr) 12 acc = accuracy_score(ytr, clf.predict(Xtr)) 13 if acc > best_acc: 14 best_acc = acc 15 best_clf = clf 16 17 print(f"Chosen C: {best_clf.C}, training accuracy: {best_acc:.3f}") 18 print(f"Test accuracy: {accuracy_score(ytest, best_clf.predict(Xtest)):.3f}") - 2026-06-q3Consider the code snippet below, where `X` contains numerical features (such as `is_holiday`, `temperature`, `visibility_meters`) and `y` is a continuous target. 1. Describe line by line what the snippet does and which learning task is solved. 2. What is the role of the hyperparameter `alpha`, and what impact can it have on the model? 3. There is a methodological flaw in this procedure. Identify it and propose a fix.
1 from sklearn.linear_model import Lasso 2 from sklearn.model_selection import train_test_split 3 4 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) 5 model = Lasso(alpha=0.1) 6 model.fit(X_train, y_train) 7 8 importances = np.abs(model.coef_) 9 most_important = np.argmax(importances) 10 test_mse = mean_squared_error(y_test, model.predict(X_test)) - 2026-01-q4Decide whether each of the following statements about kernel methods is true or false, and briefly motivate your answer.
- 2026-02-q4Indicate whether the following statements about Linear Regression and regularization are true or false. Motivate your answers.
- 2026-06-q4Tell whether the following statements about ensemble methods are true or false. Motivate your answers.
- 2026-01-q5Decide whether each of the following statements about the VC dimension is true or false, and briefly motivate your answer.
- 2026-02-q5Indicate whether the following statements about RL methods are true or false. Motivate your answers.
- 2026-06-q5Tell whether the following statements about SVMs and kernels are true or false. Motivate your answers.
- 2026-01-q6You are a data scientist for a bike-sharing service. For each user and week you have aggregated activity (number of rides, total minutes, average distance, typical time-of-day, city, subscription tier) and service-quality indicators (average nearby-bike availability, reported issues, support contacts). Model each problem below as an ML problem — state the key elements (features and target, or states, actions and reward) and name a suitable method. 1. Predict whether a user will make zero rides in the next 30 days. 2. Every Monday, send each user one offer among $K$ alternatives (discount, free minutes, temporary upgrade, or no offer).
- 2026-02-q6You are an ML consultant for a national park authority wanting to improve visitor experience and environmental protection. 1. The authority wants to forecast how crowded each park area will be over the next hour, from historical data and contextual information, to plan staff allocation and give timely recommendations. 2. On peak days the park can apply different access rules (reservation requirements, time-slot limits, dynamic entry caps). The authority wants an adaptive system that, throughout the day, chooses which rule to apply to keep overcrowding low while maximizing visitor satisfaction. Model each problem (classification, regression, RL, etc.), specifying the input/state, the target/action space, and the loss/reward, and propose a suitable method.
- 2026-06-q6You are an ML specialist at an online food-delivery company. For each sub-problem, explain how you would frame it as an ML problem, specifying the input, the output / action space, the loss or reward, and a suitable method. 1. From features of an order (distance, time of day, restaurant preparation time, weather, courier load), predict the delivery time in minutes. 2. For each new user, the app must choose which one of five promotional banners to display; the only feedback is whether the shown banner is clicked, and each banner's click probability is unknown.
- 2026-01-q7Train a binary perceptron classifier with bias, starting from $w^{(0)} = (1, 1, 0)^\top$ (the first component is the bias) with learning rate $\alpha = 1$. Use the dataset below, in the given order: $x_1 = (2, 2)^\top,\ t_1 = 1$; $x_2 = (2, -2)^\top,\ t_2 = -1$; $x_3 = (-2, 2)^\top,\ t_3 = -1$; $x_4 = (-2, -2)^\top,\ t_4 = 1$. 1. Compute $w$ after one full pass of the online perceptron algorithm. 2. With that $w$, which training points are misclassified? 3. Will the perceptron training procedure eventually converge on this dataset? Motivate your answer.
- 2026-02-q7We train two binary classifiers $\hat h_1 \in \mathcal{H}_1$ and $\hat h_2 \in \mathcal{H}_2$ on $N = 120$ samples, with $|\mathcal{H}_1| = e^5$, $|\mathcal{H}_2| = +\infty$, and $VC(\mathcal{H}_2) = 3$. Compute an upper bound on the true classification error with confidence $1 - \delta = 1 - e^{-3}$ in each scenario. 1. Both classifiers are consistent learners. 2. The classifiers have training errors $\hat L(\hat h_1) = 0.25$ and $\hat L(\hat h_2) = 0.15$. Useful bounds: finite consistent $L \le \frac{\ln|\mathcal{H}| + \ln(1/\delta)}{N}$; finite agnostic $L \le \hat L + \sqrt{\frac{\ln|\mathcal{H}| + \ln(1/\delta)}{2N}}$; infinite $L \le \hat L + \sqrt{\frac{VC(\mathcal{H})\ln\frac{2eN}{VC(\mathcal{H})} + \ln\frac{4}{\delta}}{N}}$.
- 2026-06-q7A learning algorithm selects a hypothesis from a finite class $H$ with $|H| = 150$, trained on $N = 400$ i.i.d. samples, and the chosen $h$ has training error $\hat L(h) = 0.20$. We want a guarantee holding with probability at least $1 - \delta$, $\delta = 0.05$. 1. Write the agnostic generalization bound for a finite hypothesis class, upper-bounding $L(h)$ in terms of $\hat L(h)$, $|H|$, $N$, $\delta$. 2. Compute the resulting numerical upper bound on $L(h)$. (Use $\ln 150 \simeq 5$ and $\ln 20 \simeq 3$.) 3. How many samples $N$ would guarantee that the gap between true and training error is at most $0.05$ (same $|H|$ and $\delta$)? 4. Qualitatively, how does the bound change if $|H|$ grows? Briefly justify.
- 2026-01-q8An agent interacts with an MDP with states $\mathcal{S} = \{A, B, C\}$ and actions $\mathcal{A} = \{l, r\}$, producing the episode $$(A, l, 0) \to (B, r, 4) \to (C, l, -2) \to (B, l, -1) \to (A, r, 2) \to (B, r, 0) \to (A, l, 1) \to (C, l).$$ All state-action values start at $Q(s, a) = 0$, the learning rate is $\alpha = 0.5$ and the discount is $\gamma = 1$; break ties using the first action in the action set. Motivate each answer. 1. Execute the Q-learning algorithm on this episode. 2. Execute the SARSA algorithm on this episode. 3. Give the best deterministic policy according to SARSA. Does it differ from the one given by Q-learning?
- 2026-02-q8Consider a MAB with binary rewards and two arms $\{a_1, a_2\}$ over a horizon $T = 12$. The table shows the reward $R_t$ obtained each round (only the played arm's reward is revealed): ``` t 1 2 3 4 5 6 7 8 9 10 11 12 Reward from a1 1 0 1 0 1 1 0 Reward from a2 0 1 1 0 1 ``` 1. Knowing the expected rewards $\mu_1 = 0.65$ and $\mu_2 = 0.35$, compute the expected regret over $T$. 2. Which arm would UCB1 play in the next round $t = 13$? Motivate your answer. 3. Which arm would Thompson Sampling (uniform prior at $t=0$) more likely play at $t=13$? Explain in terms of the posterior distributions.
- 2026-06-q8Consider a MAB with binary rewards and two arms $\{a_1, a_2\}$ over a horizon $T = 8$. The table reports the reward $R_t$ each round (only the played arm's reward is revealed): ``` t 1 2 3 4 5 6 7 8 Reward from a1 1 1 0 1 1 Reward from a2 0 1 0 ``` 1. Knowing the expected rewards $\mu_1 = 0.75$ and $\mu_2 = 0.25$, compute the expected regret over $T$. 2. Which arm would UCB1 play in round $t = 9$? Use $\sqrt{\frac{2\ln 8}{5}} \simeq 0.91$ and $\sqrt{\frac{2\ln 8}{3}} \simeq 1.18$. Motivate your answer. 3. Which arm is Thompson Sampling (uniform Beta prior at $t=0$) more likely to play at $t = 9$? Give the two posterior distributions.
- 2024-01-q1Define PAC-Learning in the context of supervised learning and explain how it is related to the concept of sample complexity. Make sure to define also each relevant term introduced in your answer.
- 2024-02-q1Write the pseudocode of the perceptron algorithm and prove that the update rule decreases the error for the currently processed sample at each iteration.
initialise w = 0 repeat until no mistakes (or max epochs): for each sample (x_i, y_i), with y_i in {-1, +1}: if y_i * (w . x_i) <= 0: # sample is misclassified w <- w + y_i * x_i # perceptron update - 2024-06-q1Discuss at least three methods used for feature selection and compare their advantages and disadvantages.
- 2024-07-q1Illustrate the Bias-Variance decomposition of the expected error of a regression model. Provide its complete derivation, the meaning of each term of the decomposition, and the practical significance of this decomposition.
- 2024-01-q2Explain the principles behind boosting, how does it work and when it is useful.
- 2024-02-q2Provide an overview of the feature selection methods that you know and explain their pros and cons.
- 2024-06-q2Explain the concept of bagging (Bootstrap Aggregating) in machine learning. Describe a scenario where bagging would be particularly beneficial.
- 2024-07-q2Explain what a Gram Matrix is and its role in Kernel Methods within Machine Learning.
- 2024-01-q3Consider the snippet of code below. 1. Tell which procedure is performed in the previous lines of code. Detail line-by-line the operations used. Do you think there are some errors in the code? 2. Which problem are we solving with this procedure? Are there other methods that can solve the same problem? List at least 3 other methods suitable for such a problem. 3. Which kind of metrics would you use to evaluate the performance of the previous method? Describe the metrics and the procedure you would use to understand if the adopted approach is effective.
1 X = zscore(dataset[['sepal-length', 'sepal-width']].values) 2 t = dataset['class'].values == 'Iris-setosa' 3 4 model = LogisticRegression(penalty='none') 5 model.fit(X, t) - 2024-02-q3Consider the snippet of code below. 1. What algorithm is the snippet of code above implementing? What problem is it trying to solve? 2. Is the code snippet above correct? If not, list the mistakes and provide a fix for each of them. 3. Is the `while` loop guaranteed to stop after a finite number of iterations (if `gamma < 1`)? If yes, provide an upper bound on the maximum number of iterations. If not, provide a counterexample.
1 Q = np.zeros(nS * nA) 2 Q_old = np.ones(nS * nA) 3 V = np.zeros(nS) 4 5 while np.any(Q != Q_old): 6 Q_old = Q 7 for s in range(nS): 8 V[s] = np.max(Q_old[s*nA:(s+1)*nA]) 9 Q = R_sa + gamma * P_sas @ V - 2024-06-q3Consider the snippet of code above. 1. Describe what the code does from lines 1 to 9. What kind of machine-learning problem is it solving, and which techniques are used? 2. Are lines 7-9 correct? If not, identify the mistake and propose a correction. 3. What happens to $w_2$ and $w_3$ as $\lambda$ increases? Describe the role of $\lambda$ in terms of the bias-variance trade-off.
X = dataset[['sepal-length', 'sepal-width', 'petal-length']].values t = dataset['petal-width'].values N, M = X.shape lambda_ = 0.1 Phi = np.hstack((np.ones((N, 1)), zscore(X))) w1 = inv(Phi.T @ Phi) @ (Phi.T @ t) w2 = inv(Phi.T @ Phi - lambda_ * np.eye(M + 1)) @ (Phi.T @ t) w3 = (np.abs(w1) > 1 / lambda_) * 1 / lambda_ + (np.abs(w1) <= 1 / lambda_) * w1 - 2024-07-q3Consider the snippet of code above. 1. What kind of problem is this code trying to solve? What methods are being used? 2. What is being printed in the last line, and what could we conclude from this output? 3. Are there any problems with the solution implemented here (that are visible from this code fragment)? If so, propose a fix.
SVM_model_1 = svm.SVC(kernel="linear") SVM_model_1.fit(X_train, t_train) prediction_1 = SVM_model_1.predict(X_test) def custom_kernel(X_1, X_2): A = np.array([[-0.5, 0], [0, 2]]) return np.dot(np.dot(X_1, A), X_2.T) SVM_model_2 = svm.SVC(kernel=custom_kernel) SVM_model_2.fit(X_train, t_train) prediction_2 = SVM_model_2.predict(X_test) print(accuracy_score(t_test, prediction_1), accuracy_score(t_test, prediction_2)) - 2024-01-q4Tell if the following statements about Multi-Armed Bandit (MAB) are true or false. Provide adequate motivations.
- 2024-02-q4Tell whether the following statements hold for the logistic regression and KNN methods. Provide motivations for your answers. 1. There exists a closed-form solution for the optimization procedure required to train the model. 2. They are methods used for classification, but can be easily adapted to solve regression problems. 3. The prediction phase for the model is computationally light. 4. They allow the use of regularization methods for model selection purposes.
- 2024-06-q4Mark each statement about Markov Decision Processes (MDPs) as true or false.
- 2024-07-q4Tell if the following statements about reinforcement learning are true or false. Motivate your answers.
- 2024-01-q5Indicate whether the following statements are true or false. Justify your answers.
- 2024-02-q5Tell whether the following statements are true or false. Justify your answers.
- 2024-06-q5Consider the parametric classification model $f_w(x) = \mathrm{sign}\!\left(\sum_{i=0}^{d} w_i x_i\right)$, with $w = [w_0, \dots, w_d]$, trained on a dataset $D = \{(x_i, t_i)\}_{i=1}^{N}$ of $N$ samples. Mark each statement as true or false.
- 2024-07-q5Consider a regression problem in two variables $x_1, x_2$ with features $\phi_1(x_1,x_2)=x_1$, $\phi_2(x_1,x_2)=x_2$, $\phi_3(x_1,x_2)=x_1x_2$ and a single output, solved with Ordinary Least Squares (OLS). Tell if the following statements are true or false. Motivate your answers.
- 2024-01-q6General anesthesia induces a reversible unconsciousness by administering drugs. Consider the following problems. 1. Predicting whether the patient's blood pressure goes below a fixed known threshold as an effect of the concentration levels of the administered drugs. 2. Learning the interventions (increase or decrease the amount of drugs administered) the anesthesiologist should perform to keep the patient's blood pressure within a certain known range during the whole surgical procedure. Classify the problems and, for each, specify all the elements needed to fully characterize it (input, output, states, actions, reward, ...). Furthermore, propose one technique to solve it.
- 2024-02-q6Consider designing an autonomous driving agent for a car. The system's performance is evaluated on both the time to reach a destination and the safety of the driver and of anyone the car meets. The system should replace the driver in the decisions/actions for a car with automatic gearbox. 1. Model the problem as an MDP and provide a technique to learn the best driving policy. Motivate your decisions. 2. If the learning is performed on a real car in the real world, would you prefer an off-policy or an on-policy approach? (If off-policy, specify the policy the agent should follow.)
- 2024-06-q6An online bookstore shows each visitor a single book on the homepage and wants to display the one that maximises the probability the visitor buys it. For each case, briefly discuss how the problem could be modelled and solved with techniques seen in class. 1. The bookstore has no previous purchase data and no information about the current visitor. 2. The bookstore has detailed information (age, location, ...) and the purchase history of registered users.
- 2024-07-q6You are the CTO of a trading startup, and you are requested to address the following scenarios using machine learning techniques. For each scenario, classify it as a machine learning problem, specify the data (features and target, or states, actions, and reward), and a specific method to solve it. 1. Predict the price of multiple stocks for the next day, given historical data of the price of the same stocks in the past. 2. Decide the amount of money to invest in each stock, given the current price of the same stocks and a limited investment budget.
- 2024-01-q7Given the dataset below (each $\mathbf{x}_i \in \mathbb{R}^3$ with label $y_i$): - Classify the point $\mathbf{x}_{11} = (0, 1, 2)^\top$ according to a k-NN classifier trained on the dataset with $K = 3$, using the Manhattan distance $d(\mathbf{x}_i, \mathbf{x}_j) = \sum_h |x_{ih} - x_{jh}|$. - What happens if we use $K = 2$ instead? Do you think it is a good idea to choose such a value for $K$? - What would you do if you wanted to apply regularization to this classifier?
x1 = (2, 3, 4) y1 = 1 x2 = (0, 1, 2) y2 = 0 x3 = (1, 2, 5) y3 = 1 x4 = (1, 4, 3) y4 = 0 x5 = (0, 3, 1) y5 = 0 x6 = (1, 2, 2) y6 = 0 x7 = (3, 1, 4) y7 = 1 x8 = (4, 2, 5) y8 = 1 x9 = (1, 3, 3) y9 = 0 x10 = (1, 2, 4) y10 = 1 - 2024-02-q7Consider an initial parameter $\mathbf{w}^{(0)} = [1\ 2\ 0]^\top$ and the loss function $$J(\mathbf{w}) = \frac{1}{2N}\sum_{n=1}^N (\mathbf{w}^\top\mathbf{x}_n - t_n)^2 + \frac{\lambda}{2}\mathbf{w}^\top\mathbf{w}.$$ 1. Derive the gradient-descent update for a generic input. 2. Apply the formula to the input $\mathbf{x}_1 = [2\ 1\ 1]^\top$, $t_1 = 2$, with learning rate $\alpha = 0.3$ and regularization coefficient $\lambda = 0.5$. 3. Assuming we iteratively run this procedure over the entire dataset, do we have any convergence guarantee?
- 2024-06-q7A binary classifier outputs $1$ if $\sigma(w^\top x) \ge \tau$ and $0$ otherwise, where $\sigma$ is the sigmoid. The weights $w$ are trained with logistic regression on $N = 100$ samples and the threshold is set to $\tau = 1/2$. 1. Given Accuracy $= 0.4$, Recall $= 0.5$, and 20 positive samples correctly classified, draw the confusion matrix. 2. Compute the $F_1$ score. 3. Suppose we lower the threshold to $\tau = 1/4$ and find that the number of samples wrongly classified as positive is unchanged. What can we conclude about the Precision? Provide a formal justification.
- 2024-07-q7Consider a Multi-Armed Bandit (MAB) algorithm selecting among $K=2$ actions for $n=10$ rounds. The reward distributions for arms $a_1$ and $a_2$ are Bernoulli with parameters $p_1=0.6$ and $p_2=0.4$ respectively. The realisation of arm pulls and rewards up to round 8 is the table below — only the **bold** reward (the arm actually selected that round) is observed by the learner; the other column is the hypothetical reward that arm would have given. | Round | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |---|---|---|---|---|---|---|---|---| | Reward $a_1$ | **0** | 1 | 1 | 1 | **1** | 0 | **1** | **0** | | Reward $a_2$ | 1 | **0** | **0** | **1** | 0 | **1** | 0 | 1 | | Selected arm | $a_1$ | $a_2$ | $a_2$ | $a_2$ | $a_1$ | $a_2$ | $a_1$ | $a_1$ | 1. What is the (random) regret of the algorithm at the end of round 8? And the expected pseudo-regret? 2. Suppose the algorithm was Thompson Sampling, initialised with uniform priors. What are the posterior distributions for the two arms at the end of round 8? What can we say about the probability of Thompson Sampling selecting arm $a_1$ at round 9? You can assume ties are broken in favour of arm $a_1$. 3. Instead, assume the algorithm was UCB1, and it also played $a_1$ at round 9, observing a reward of 1. What arm would it play next, at round 10? *Hint: $\sqrt{0.4\ln(10)} < 0.96$ and $\sqrt{0.5\ln(10)} > 1.07$. Motivate all answers and report all necessary computations.*
- 2024-01-q8Consider the following Markov reward process (an MDP with a fixed policy) on states $\{A, B, C, D\}$. From the start the agent enters $A$. From each of $A$, $B$, $C$ it either stays (self-loop, probability $1/2$) or moves to the next state ($A\to B$, $B\to C$, $C\to D$, each probability $1/2$); state $D$ is absorbing (self-loop with probability $1$). The discount factor is $\gamma \in [0,1)$ and the reward function is $R(A)=R(B)=R(C)=0$ and $R(D)=\dfrac{1-\gamma}{1-\gamma/2}$. 1. Compute the value function $V^\pi(s)$ for every state $s \in \{A,B,C,D\}$. 2. Suppose the agent observes the infinite episode $A \to B \to B \to C \to C \to C \to C \to D \to D \to \dots$. Compute the probability that such an episode occurs. 3. Say whether Monte Carlo (first-visit and every-visit) and Temporal Difference evaluation can be used to estimate the value function. If yes, give the estimate the technique delivers on the episode of question 2, with $\hat V$ initialized to zero and learning rate $\alpha > 0$. Motivate your answers.
- 2024-02-q8We train two binary classifiers $\hat h_1 \in \mathcal{H}_1$ and $\hat h_2 \in \mathcal{H}_2$ on $N = 100$ samples, with $|\mathcal{H}_1| = e^6$ and $|\mathcal{H}_2| = +\infty$, $VC(\mathcal{H}_2) = 2$. Compute the upper bound on the classification error with confidence $1 - \delta = 1 - e^{-2}$ for the two classifiers in each scenario, and say which classifier you would deploy. 1. Both classifiers are consistent learners (training error $0$). 2. The classifiers have training errors $\hat L(\hat h_1) = 0.3$ and $\hat L(\hat h_2) = 0.1$. Useful bounds: finite consistent $L \le \frac{\ln|\mathcal{H}| + \ln(1/\delta)}{N}$; finite agnostic $L \le \hat L + \sqrt{\frac{\ln|\mathcal{H}| + \ln(1/\delta)}{2N}}$; infinite $L \le \hat L + \sqrt{\frac{VC(\mathcal{H})\ln\frac{2eN}{VC(\mathcal{H})} + \ln\frac{4}{\delta}}{N}}$; and $\sqrt{\frac{\ln(40000e^3)}{100}} \approx 0.37$.
- 2024-06-q8A linear binary SVM classifier has, after training, weights $w = [-1, 2]$ and bias $b = -3$, so its decision function is $f(x) = w^\top x + b$. Motivate all answers and write down any necessary computation. 1. How is the point $[0.5, 1]$ classified? 2. Provide an example of a support vector. 3. The point $[1, 1]$ is added to the dataset with a negative label. Do we need to retrain the SVM? 4. If all we care about is predicting the class of new points, can we discard the point $[-3, 2]$ from the dataset?
- 2024-07-q8Suppose you train a logistic regression classifier for binary classification with a training set composed of $N=1000$ samples and using $M=29$ features. The training classification error is $0.1$, while the test classification error is $0.4$. You know that in the true data-generating process the positive and negative classes are generated with equal probability. Answer the following questions, reporting all steps and calculations: 1. Looking at the training classification error only, what is the maximum probability $1-\delta$ that the trained classifier is better than a random-guess classifier? 2. Looking at the test classification error only, what is the minimum number of samples in the test set to ensure that the trained classifier is better than a random-guess classifier, with probability at least $1-\delta = 1-e^{-8}$? *Hint. The VC dimension of a linear classifier in $d$ dimensions is $d+1$. Recall the VC bound $L_\text{true}\le L_\text{train}+\sqrt{\dfrac{VC(H)\bigl(\ln\frac{2N}{VC(H)}+1\bigr)+\ln\frac{4}{\delta}}{N}}$ and the single-hypothesis Hoeffding bound $L_\text{true}\le \hat L+\sqrt{\dfrac{\ln(1/\delta)}{2J}}$. If needed, $30\ln\!\left(\frac{200e}{3}\right)\approx 156$.*
- 2023-07-q1Beginning with the expected squared error of a regression model, outline the steps that lead to the Bias-Variance Decomposition of this error, providing the resulting equations. Then, briefly discuss the intuitive meaning behind each term in the final decomposition.
- 2023-08-q1Describe and compare the Monte Carlo and Temporal Difference approaches to policy evaluation.
- 2023-07-q2Explain what is an $\varepsilon$-greedy policy and why it is useful in Reinforcement Learning.
- 2023-08-q2Describe the role of regularization in managing the bias-variance trade-off. Discuss the difference between L1 and L2 regularization techniques and their respective effects on model complexity and feature selection.
- 2023-06-q3Consider the following snippet of code (it operates on an Iris-style `dataset`). 1. Describe the operations executed and the purpose (which problem, and which method has been used) of the snippet above. 2. Do you think the method used is appropriate for the considered problem? If not, propose an alternative approach. If yes, propose other approaches to solve the same problem. 3. Are there any issues intrinsic to Line 7? Describe the issue and propose a method to deal with it.
1 x = zscore(dataset['petal-length'].values).reshape(-1, 1) 2 y = zscore(dataset['class'].values) 3 4 n_samples = len(x) 5 Phi = np.ones((n_samples, 2)) 6 Phi[:, 1] = x.flatten() # the second column is the feature 7 w = inv(Phi.T @ Phi) @ (Phi.T.dot(y)) - 2023-07-q3Consider the snippet of code below. 1. Describe the operations executed and the purpose (which problem and which method has been used) of the snippet reported above. 2. Interpret the operation that is performed at line 13. Can you say something about the recall of `pred3` compared to the recall of `pred1`? Motivate your answer. 3. Can any of the two models employed in the snippet be used for augmenting the available data with artificially generated samples? Motivate your answer.
1 X = zscore(dataset[['sepal-length', 'sepal-width']].values) 2 t = dataset['class'].values == 'Iris-setosa' 3 X, t = shuffle(X, t, random_state=0) 4 5 c1 = LogisticRegression(penalty='none') 6 c1.fit(X, t) 7 8 c2 = GaussianNB() 9 c2.fit(X, t) 10 11 pred1 = c1.predict(X) 12 pred2 = c2.predict(X) 13 pred3 = pred1 * pred2 - 2023-08-q3Consider the snippet of code below. 1. What algorithm is the snippet of code above implementing? What problem is it trying to solve? 2. Is the code snippet above correct? If not, list the mistakes and provide a fix for each of them. 3. Is the `while` loop guaranteed to stop after a finite number of iterations (if `gamma < 1`)? If yes, provide an upper bound on the maximum number of iterations. If not, provide a counterexample.
1 Q = np.zeros(nS * nA) 2 Q_old = np.ones(nS * nA) 3 4 pi = np.zeros((nS, nS * nA)) 5 for s in range(nS): 6 pi[s, s*nA:(s+1)*nA] = 1 / nA 7 8 while np.any(Q != Q_old): 9 Q_old = Q 10 Q = (np.eye(nS * nA) - gamma * P_sas @ pi) @ R_sa 11 pi = np.zeros((nS, nS * nA)) 12 for s in range(nS): 13 ga = np.argmax(Q[s*nA:(s+1)*nA]) 14 pi[s, s*nA+ga] = 1 - 2023-06-q4The figure above shows how a model's train error and test error change as a single hyperparameter is varied along the x-axis (left to right) on a fixed training/test split. For each method below — together with the described direction of the hyperparameter change — say whether it could have produced this picture, and justify. 1. Ridge regression, increasing the regularisation parameter $\lambda$. 2. k-nearest-neighbour classifier, decreasing the number of neighbours $k$. 3. Logistic regressor, increasing the number of principal components extracted from the dataset. 4. SVM, decreasing the number of features selected by a filtering method.

- 2023-07-q4Tell if the following properties are typical of filter feature selection, PCA, Lasso, or none of them. Motivate your answers. 1. It increases the bias of the model. 2. It provides features that are different from the original ones. 3. It is embedded into the training loss. 4. It can be applied in combination to linear regression only.
- 2023-08-q4Assume a regression model $y = \mathbf{w}^\top\mathbf{x}$ over a dataset of inputs $\mathbf{x}_i$ and targets $t_i$, $i \in \{1,\dots,N\}$. Indicate whether the following statements are true or false and motivate your answers.
- 2023-06-q5For each expression, state whether it is a valid kernel and justify your answer. Recall that a valid kernel must satisfy Mercer's conditions — it must be a continuous, symmetric, positive semi-definite function. 1. $k(x,x') = a\,k_1(x,x') + b\,k_2(x',x)$, where $k_1(\cdot,\cdot)$ and $k_2(\cdot,\cdot)$ are valid kernels. 2. $k(x,x') = \|x\|_2^2 + \|x\|_2\,\|x'\|_2$. 3. $k(x,x') = \dfrac{|x\,x'|}{x\,x'} + 2$ for $x,x' \in [-1,1]$. 4. $k(x,x') = x^\top A\,x'$ with $A = \begin{bmatrix} 3 & 1 \\ 1 & -4 \end{bmatrix}$ and $x,x' \in \mathbb{R}^2$.
- 2023-07-q5We are the manager of a football team and we are planning the players to buy and sell to create next year's team. The process of bargaining between teams to conclude a purchase is a process where, in a sequence, we propose an offer (a mix of money and other players for a specific player) and the counterpart decides to accept the offer, refuse it and continue bargaining, or refuse and stop the bargaining process. 1. Define the type of data one might consider when modeling this process (input, output, state, action, reward, etc.). 2. Tell which problem is the one of evaluating the performance of the bargaining strategy of the previous season. Suggest a method to solve this problem. 3. Can we use the same approach if we want to find the most appropriate way to maximize the value obtained from the bargaining process? If not, tell which problem we are facing and propose a method to solve it.
- 2023-08-q5Indicate whether the following statements are true or false. Justify your answers. 1. A training error significantly smaller than the test error is a symptom of underfitting. 2. A training loss close to the test error but significantly larger than the desired loss is a symptom of underfitting. 3. A small-variance model is prone to overfitting. 4. A small-bias model is prone to overfitting.
- 2023-06-q6An automatic manipulator collects objects in a 2D environment. Model each of the following as an ML problem — specifying the data (features and target, or states, actions, and reward), the problem class, and a concrete method to solve it. 1. Estimate the time the manipulator needs to collect a specific object from its location, given a dataset of the manipulator's past executions. 2. Learn the manipulator's control policy that minimises the total time to collect all objects, with the possibility of interacting with the real system.
- 2023-07-q6Tell if the following statements are true for the UCB1 and/or Thompson Sampling (TS) algorithms. Properly motivate your answers. 1. It is able to include prior information on the MAB problem we are solving. 2. Can be applied if the rewards provided by pulling arms are unbounded. 3. Effectively solves online RL problems with a single state. 4. Solves the exploration/exploitation dilemma using the optimism in the face of uncertainty principle.
- 2023-08-q6You own a software house and want to estimate how much effort and income you get from developing new software. You have historical data about the characteristics of each past software, the duration of its development, and the profits it provided. 1. Model the problem of estimating the duration and profits of a new software's development. Specify the data, the class of problem, and the methodology you would adopt. 2. What if, instead, you do not have a dataset, and you must decide sequentially which type of software to develop, choosing from a set of categories (e.g., game, business analytics, finance, sport)? Provide a modeling (class of methods and data to process) and a method to solve it.
- 2023-06-q7A perceptron is trained starting from $\mathbf{w}^{(0)} = (1,\,0)^\top$ with learning rate $\alpha = 1$, on the dataset $x_1=(2,\,1)^\top,\ t_1=1$; $x_2=(1,\,-2)^\top,\ t_2=-1$; $x_3=(1,\,3)^\top,\ t_3=-1$; $x_4=(-3,\,2)^\top,\ t_4=1$. 1. Compute $\mathbf{w}$ after running the (online) gradient-descent perceptron update once over the dataset. 2. Do you think the computed $\mathbf{w}$ is optimal for the given dataset? 3. Can you tell whether the perceptron training procedure would converge eventually? 4. In general, given 4 distinct points with arbitrary labels in a 2D space, can they always be correctly classified by a perceptron?
- 2023-07-q7Consider a soft-margin linear SVM classifier trained on a non-linearly separable dataset, leading to the weight vector $\mathbf{w} = (-2, 1)^\top$ and constant $b = -1$. Address the following questions motivating your answers. 1. Describe the decision boundary and the margins. 2. Let $\mathbf{x} = (-3, 1)^\top$ be a training point belonging to the negative class. Is it correctly classified? Tell which of the following conditions on the slack variable $\xi$ of point $\mathbf{x}$ is correct: $\xi = 0$, $\xi > 1$, or $0 < \xi < 1$. Why? 3. Can you suggest a method to reduce the number of points misclassified by the SVM?
- 2023-08-q7Consider the two-class logistic regression classifier $y_\mathbf{w}(\mathbf{x}) = \dfrac{1}{1 + \exp(-\mathbf{w}^\top\mathbf{x})}$. 1. Given a training dataset $\{(\mathbf{x}_i, t_i)\}_{i=1}^N$, write the loss function $L(\mathbf{w})$ for training the classifier. 2. Derive the gradient of the loss function $L(\mathbf{w})$. 3. Starting from $\mathbf{w}_0 = (0, 0, 0)^\top$, apply the gradient update with $\alpha = 1$ and the data points $\mathbf{x}_1 = (1, 0, -1)^\top,\ t_1 = 1$ and $\mathbf{x}_2 = (0, 2, -3)^\top,\ t_2 = 0$.
- 2023-06-q8An agent interacts with an MDP over states $\mathcal{S}=\{A,B,C\}$ and actions $\mathcal{A}=\{l,r\}$, producing the episode $(A,l,1)\to(C,l,2)\to(A,r,0)\to(B,r,5)\to(B,l,0)\to(C,l,0)\to(B,l,-2)\to(A,r)$, where each tuple $(s,a,r)$ means action $a$ was taken in state $s$ and reward $r$ was received. Start from $Q(s,a)=0$ for every state–action pair, with learning rate $\alpha=0.5$ and discount factor $\gamma=1$. 1. Run the Q-learning algorithm on this episode (break ties using the first action listed in $\mathcal{A}$). 2. Run the SARSA algorithm on this episode. 3. Give the greedy policy according to SARSA's output. Does it differ from the one given by Q-learning?
- 2023-07-q8Consider the hypothesis space $\mathcal{H}$ made of the union of two closed intervals on $\mathbb{R}$, i.e. $[a,b]\cup[c,d]$. Address the following questions motivating your answers. 1. If $VC(\mathcal{H}) = 4$, provide a PAC bound for the true error holding with probability $1 - 4e^{-5}$, knowing that the training loss is $L_{\text{train}} = 0.3$ obtained with $N = 100$ samples. (Note that $\log(200/4) \approx 4$.) 2. Prove that $VC(\mathcal{H}) \ge 4$. 3. Prove that $VC(\mathcal{H}) < 5$.
- 2023-08-q8Consider a stochastic Multi-Armed Bandit (MAB) with 10 arms whose real expected rewards are, respectively, $\mu = (0.5,\ 0.2,\ 0.1,\ 0.0,\ 0.2,\ 0.4,\ 0.6,\ 0.1,\ 0.1,\ 0.3)$. 1. Which arm will Thompson Sampling converge to as $T \to \infty$ (starting from a uniform prior)? 2. Assuming the arms have been pulled $T_1 = 5,\ T_2 = 50,\ T_3 = 10,\ T_4 = 5,\ T_5 = 10,\ T_6 = 10,\ T_7 = 5,\ T_8 = 10,\ T_9 = 2,\ T_{10} = 10$ times, compute the pseudo-regret accumulated so far. Motivate your answers.
- 2022-06-q3You have been given a dataset with input matrix $X$ and target vector $y$. Consider the PCA snippet below. 1. Describe the procedure and the purpose of the code. Is it correct? 2. Line 6 performs a selection procedure. Explain the rationale behind it and suggest other viable options for the selection. 3. Does this code require any preliminary operations on `X` and `y` before being executed? If so, which ones and why; if not, motivate your answer.
pca = PCA() pca.fit(X, y) explained = pca.explained_variance T = pca.transform(X) explained_variance = np.cumsum(explained) / sum(explained) T_tilde = T[:, explained_variance < 0.95] - 2022-06-q4The following statements concern classification algorithms. Mark each as true or false.
- 2022-06-q5The following statements concern the VC dimension. Mark each as true or false.
- 2022-06-q6You are the head of the data science department of the F1 team Beta Giulietta and face two problems. 1. Find how the configuration of the car (flap incidence, tyre choice, aerodynamic profile) provides information about the lap time. 2. Determine the best strategy to enter the pit and change tyres during the race — on each lap, choosing whether to pit or not. Model these two problems using ML, specifying the data (input, output, state, action, reward) required, the problem class, and a specific method to solve each.
- 2022-06-q7Consider a K-NN model for regression and the training dataset below, with one-dimensional feature $x$, target $t$, and the real function $f(x)$ (unknown to the model). 1. Compute the model's prediction for each element of the dataset with $K = 3$. 2. Compute the mean squared error on the dataset. 3. Provide an estimate of the model variance from the available data. What happens to the variance as $K$ increases? 4. Provide an estimate of the squared bias from the available data. What happens to the bias as $K$ increases?
x 1 1.5 3 4.5 5.5 6.5 t 2.5 2.5 6 10 10.5 12 f(x) 2 3 6 9 11 13 - 2022-06-q8Consider the trajectory below, obtained while running the SARSA algorithm in an MDP with three states $S=\{A,B,C\}$, two actions $A=\{u,d\}$, and discount factor $\gamma=1$. $$(A, u, 2) \to (B, d, -2) \to (A, d, -2) \to (A, u, -1) \to (B, u, -3) \to (C, d, 4) \to (B)$$ 1. Provide a consistent guess of the policy $\pi$ used to draw this trajectory. Is it a reasonable policy? 2. Provide the policy-evaluation step according to SARSA, assuming zero initial values $Q(s,a)=0$ for every state-action pair and learning rate $\alpha=0.5$. 3. Provide the policy-improvement step, i.e. the policy $\pi'$ the algorithm deploys at the next iteration.
- 2021-06-q3Consider the Python snippet below. 1. Describe the operations performed by the code. Provide a detailed description of the lines of code provided. 2. Which kind of problem are we solving? What is the technique we are using? 3. Do you think there are some problems with the procedure described above? Do you think there exists a better way to perform it?
1 train_accuracy = [] 2 test_accuracy = [] 3 for k in np.arange(1, 11): 4 knn = neighbors.KNeighborsClassifier(k) 5 knn.fit(X_train, y_train) 6 accuracy = sum(knn.predict(X_train) == y_train) / len(y_train) 7 train_accuracy.append(accuracy) 8 accuracy = sum(knn.predict(X_test) == y_test) / len(y_test) 9 test_accuracy.append(accuracy) 10 selected = np.argmax(test_accuracy) - 2021-06-q4Are the following statements about Linear Regression true or false? Motivate your answers.
- 2021-06-q5You want to apply RL to train an AI agent to play a single-player videogame. The state of the game is fully observable and, at each step, the agent has to select an action from a discrete set of possibilities. The interaction ends as soon as the agent reaches the end of the level or fails. To optimise the policy for your AI, you have a set of recorded trajectories (i.e. sequences of state, action, and reward) of the AI agent playing the game following a suboptimal policy. Unfortunately, most of these trajectories are not complete (i.e. they do not run from the beginning of the level to either the end of it or a game-over state). Indicate whether each of the following methods can be applied to this problem, motivating your answer.
- 2021-06-q6Tell which of the following methods is a parametric method and which is not. Motivate your answers. 1. Gaussian Processes 2. Logistic Regression 3. Ridge Regression 4. K-Nearest Neighbors
- 2021-06-q7Consider a linear, hard-margin, two-class SVM classifier defined by parameters $\mathbf{w}=[-2,\ 1]$, $b=-3$. Answer the following questions providing adequate motivations. 1. Provide the analytical formula of the boundary and the margins. 2. How is the point $x_1=[9/10;\ 9/2]$ classified according to the trained SVM? 3. Assume to collect a new sample $x_2=[1/2;\ 37/10]$ in the negative class. Do you need to retrain the SVM? 4. Which additional information would you require to classify the point $x_1$ in the case we have a Kernel SVM classifier?
- 2021-06-q81. Show that the VC dimension of the class $H$ of axis-aligned rectangles is $VC(H)=4$. Provide a proof resorting to textual and/or visual explanations. 2. How many samples do you need to guarantee that this classifier provides you with an error larger than $\varepsilon=0.1$ with probability smaller than $\delta=0.2$? *Hint. For a hypothesis space of finite VC dimension the sample-complexity bound is $N\ge\frac{1}{\varepsilon}\left(4\log_2\frac{2}{\delta}+8\,VC(H)\log_2\frac{13}{\varepsilon}\right)$.*
- adaboostIllustrate the AdaBoost algorithm, explain its purpose and in which cases it is useful.
- baggingExplain the concept of Bagging (Bootstrap Aggregating) in machine learning. Describe a scenario where bagging would be particularly beneficial.
- bagging-vs-boostingCompare Bagging and Boosting in terms of how they combine models and their impact on bias and variance.
- bayesian-linear-regression-vs-lsDescribe the Bayesian Linear Regression approach and compare it to the Least-Squares (LS) method.
- bayesian-linear-regression-vs-ridgeDescribe the Bayesian Linear Regression method and how it compares to Ridge Regression.
- bayesian-ridge-interpretationIllustrate and explain the Bayesian interpretation of ridge regression.
- bias-variance-decompositionIllustrate the bias–variance decomposition of the expected error of a regression model. Provide its complete derivation, the meaning of each term, and the practical significance of the decomposition.
- bias-variance-tradeoffExplain the bias–variance trade-off in supervised learning. Define bias and variance, describe their relation to model complexity, and explain how they lead to underfitting and overfitting.
- boostingExplain the idea behind boosting and its main purpose. Describe how training and inference work in boosting. Finally, give one example of a problem where boosting is likely to be beneficial and one where it could be harmful or ineffective.
- cross-validationIntroduce the concept of cross-validation for model evaluation and describe at least two common strategies for implementing it, including their advantages and disadvantages.
- epsilon-greedyExplain what an eps-greedy policy is and why it is useful in RL.
- exploration-exploitationIn RL, explain the exploration–exploitation trade-off and discuss how the discount factor gamma influences an agent's long-term behaviour.
- feature-selectionDiscuss at least three methods used for feature selection and compare their advantages and disadvantages.
- gram-matrixExplain what a Gram matrix is and its role in kernel methods within machine learning.
- kernel-trickExplain what the kernel trick is, what it is used for, and in which ML methods it can be used.
- logistic-regressionDescribe the logistic regression model and how it is trained.
- mc-vs-tdCompare Monte Carlo (MC) and Temporal Difference (TD) methods for model-free prediction / policy evaluation. Discuss their advantages and disadvantages.
- pac-bound-consistentIllustrate the PAC bound for consistent learners (training error equal to zero) and its applications.
- pac-learning-definitionDefine PAC-learning in the context of supervised learning and explain how it is related to the concept of sample complexity. Make sure to define each relevant term you introduce.
- pcaDescribe the PCA technique, how it works and what its purpose is.
- perceptronDescribe the perceptron model and how it is trained.
- perceptron-pseudocode-proofWrite the pseudocode of the perceptron algorithm and prove that the update rule decreases the error for the currently processed sample at each iteration.
initialise w = 0 repeat until no mistakes (or max epochs): for each sample (x_i, y_i), with y_i in {-1, +1}: if y_i * (w . x_i) <= 0: # sample is misclassified w <- w + y_i * x_i # perceptron update - perceptron-vs-logisticCompare the perceptron algorithm and logistic regression in terms of the update rule, loss functions, and convergence properties.
- q-learning-vs-sarsaDescribe and compare Q-learning and SARSA.
- regularization-l1-l2Describe the role of regularization in managing the bias–variance trade-off. Discuss the difference between L1 and L2 regularization techniques and their respective effects on model complexity and feature selection.
- ridge-vs-lassoDescribe and compare Ridge regression and Lasso regression.
- rl-prediction-control-mcDescribe the two problems tackled by RL — prediction and control — and describe how Monte Carlo RL techniques can be used to solve these two problems.
- svm-overviewDescribe the SVM for supervised classification problems. In particular explain how they work and their strengths and weaknesses.
- svm-training-generalization-boundDescribe the SVM algorithm for classification problems. Which algorithm can we use to train an SVM? Provide an upper bound to the generalization error of an SVM.
- svm-vs-logisticCompare Logistic regression and SVM. Discuss their loss functions, output interpretation, margin, regularization, and mention one scenario where each method is preferable.
- thompson-samplingDescribe the Thompson Sampling algorithm for multi-armed bandit (MAB) problems.
- train-validation-testDescribe the processes of training, validation and testing in supervised learning. Explain how to manage the dataset and what common mistakes should be avoided.
- valid-kernelsDescribe what a valid kernel function is and describe how valid kernels can be built.
- value-iterationDescribe the value iteration algorithm and its properties.
- value-vs-policy-iterationDescribe and compare value iteration and policy iteration.
- vc-dimensionWhat is the VC dimension of a hypothesis space? What can it be used for?