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
  1. 2026-01-q12026Q01Bias–variance trade-offmedium7 pts
    Explain 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.
  2. 2026-02-q12026Q01Kernel trickmedium7 pts
    Explain what the Kernel Trick is, what it is used for, and in which ML methods it can be used.
  3. 2026-06-q12026Q01Logistic regression — cross-entropyhard7 pts
    Consider 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.
  4. 2026-01-q22026Q02Logistic regression vs SVMmedium7 pts
    Compare logistic regression and support vector machines. Discuss their loss functions, output interpretation, margin, regularization, and mention one scenario where each method is preferable.
  5. 2026-02-q22026Q02Boostingmedium7 pts
    Explain 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.
  6. 2026-06-q22026Q02SARSA vs Q-learninghard7 pts
    Consider 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.
  7. 2026-01-q32026Q03Logistic regression in practicemedium2 pts
    Consider 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()
    
  8. 2026-02-q32026Q03SVM — model selectionmedium2 pts
    Consider 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}")
    
  9. 2026-06-q32026Q03Lasso & feature scalingmedium2 pts
    Consider 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))
    
  10. 2026-01-q42026Q04Valid kernelsmedium2 pts
    Decide whether each of the following statements about kernel methods is true or false, and briefly motivate your answer.
    • If the feature mapping $\phi(x)$ is explicitly known, there is no point in using a kernel (dual) representation.
    • The function $k(x, x') := \exp(-\lVert x - x' \rVert^2)$ is a valid kernel.
    • The function $k(x, x') := x^\top A x'$ with $A = \begin{pmatrix} 1 & 2 \\ 2 & 1 \end{pmatrix}$ and $x, x' \in \mathbb{R}^2$ is a valid kernel.
    • Knowing only the Gram matrix $K$ of the training set is enough to compute predictions on a new test point $x^*$ with a dual kernel method.
  11. 2026-02-q42026Q04Linear regression & regularizationmedium2 pts
    Indicate whether the following statements about Linear Regression and regularization are true or false. Motivate your answers.
    • If the design matrix $\Phi$ is singular, Ridge Regression (with $\lambda > 0$) and Ordinary Least Squares (OLS) yield the same solution.
    • For unregularized OLS, adding additional features to the model cannot increase the training mean squared error.
    • When outputs are corrupted by noise, adding regularization can reduce the MSE on the test set compared to OLS.
    • Lasso admits a solution that can be computed by inverting $(\Phi^\top\Phi + \lambda I)$.
  12. 2026-06-q42026Q04Ensemble methods — bagging & boostingmedium2 pts
    Tell whether the following statements about ensemble methods are true or false. Motivate your answers.
    • Bagging reduces variance mainly by averaging models trained on bootstrap samples, and is most effective with high-variance, low-bias base learners.
    • In boosting, the base learners are trained independently and in parallel.
    • In bagging, each base model is trained on a bootstrap sample — a dataset of the same size $N$ obtained by sampling the training set with replacement.
    • Boosting can reduce the bias of weak learners, but if run for too many rounds it may overfit the training data.
  13. 2026-01-q52026Q05VC dimensionmedium2 pts
    Decide whether each of the following statements about the VC dimension is true or false, and briefly motivate your answer.
    • Even if a hypothesis space $H$ contains infinitely many hypotheses, its VC dimension is always finite.
    • The VC dimension of $H$ is at least $k$ if and only if $H$ shatters at least one subset of the instance space of cardinality $k$.
    • The VC dimension of a logistic-regression classifier on features $(x_1, x_2)$ is smaller than that of a logistic-regression classifier on $(x_1, x_2, x_1^2, x_2^2, x_1 x_2)$.
    • The VC dimension of a hypothesis space depends on the size of the training set.
  14. 2026-02-q52026Q05TD / MC / Q-learning / SARSAmedium2 pts
    Indicate whether the following statements about RL methods are true or false. Motivate your answers.
    • In TD(0) policy evaluation, the update target for $V(S_t)$ uses the one-step bootstrap.
    • In Monte Carlo policy evaluation, first-visit and every-visit MC converge to the same value function $V^\pi$ (given sufficiently many visits).
    • In Q-learning, updating $Q(S_t, A_t)$ does not require sampling the next action $A_{t+1}$ to compute the TD target.
    • SARSA can be applied to non-Markovian tasks, since it does not rely on the Markov property.
  15. 2026-06-q52026Q05SVM & kernelsmedium2 pts
    Tell whether the following statements about SVMs and kernels are true or false. Motivate your answers.
    • In a soft-margin SVM, removing a training point that is not a support vector leaves the decision boundary unchanged.
    • The function $k(\mathbf{x}, \mathbf{z}) = (\mathbf{x}^\top\mathbf{z} + 1)^2$ is a valid kernel.
    • The function $k(\mathbf{x}, \mathbf{z}) = \mathbf{x}^\top\mathbf{z} - 1$ is a valid kernel.
    • For the Gaussian (RBF) kernel $k(\mathbf{x},\mathbf{z}) = \exp(-\gamma\|\mathbf{x}-\mathbf{z}\|^2)$, decreasing the bandwidth (making $\gamma$ large) tends to increase the risk of overfitting.
  16. 2026-01-q62026Q06Modelling real problemsmedium2 pts
    You 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).
  17. 2026-02-q62026Q06Problem modeling — regression & RLmedium2 pts
    You 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.
  18. 2026-06-q62026Q06Problem modeling — regression & MABmedium2 pts
    You 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.
  19. 2026-01-q72026Q07Perceptron algorithmhard4 pts
    Train 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.
  20. 2026-02-q72026Q07Finite & VC generalization boundshard4 pts
    We 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}}$.
  21. 2026-06-q72026Q07Finite-class generalization boundmedium4 pts
    A 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.
  22. 2026-01-q82026Q08Q-learning vs SARSAhard4 pts
    An 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?
  23. 2026-02-q82026Q08Multi-armed bandits — UCB1 & Thompson Samplingmedium4 pts
    Consider 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.
  24. 2026-06-q82026Q08Multi-armed bandits — UCB1 & Thompson Samplingmedium4 pts
    Consider 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.
  25. 2024-01-q12024Q01PAC-learning & sample complexityhard7 pts
    Define 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.
  26. 2024-02-q12024Q01Perceptron — pseudocode & proofhard7 pts
    Write 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
    
  27. 2024-06-q12024Q01Feature selectionhard7 pts
    Discuss at least three methods used for feature selection and compare their advantages and disadvantages.
  28. 2024-07-q12024Q01Bias-variance decompositionhard7 pts
    Illustrate 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.
  29. 2024-01-q22024Q02Boostingmedium7 pts
    Explain the principles behind boosting, how does it work and when it is useful.
  30. 2024-02-q22024Q02Feature selection — overviewmedium7 pts
    Provide an overview of the feature selection methods that you know and explain their pros and cons.
  31. 2024-06-q22024Q02Baggingmedium7 pts
    Explain the concept of bagging (Bootstrap Aggregating) in machine learning. Describe a scenario where bagging would be particularly beneficial.
  32. 2024-07-q22024Q02Gram matrixmedium7 pts
    Explain what a Gram Matrix is and its role in Kernel Methods within Machine Learning.
  33. 2024-01-q32024Q03Classification — logistic regression & evaluationmedium2 pts
    Consider 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)
    
  34. 2024-02-q32024Q03Value iterationmedium2 pts
    Consider 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
    
  35. 2024-06-q32024Q03Ridge regression & regularisationmedium2 pts
    Consider 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
    
  36. 2024-07-q32024Q03SVM kernels & validitymedium2 pts
    Consider 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))
    
  37. 2024-01-q42024Q04Multi-armed banditsmedium2 pts
    Tell if the following statements about Multi-Armed Bandit (MAB) are true or false. Provide adequate motivations.
    • After pulling an arm, the learner gets feedback on the reward from all the available arms.
    • An algorithm designed for the MAB setting should minimize the regret suffered during the learning procedure.
    • A problem modeled as an MDP with a single state and an infinite number of actions can be handled with MAB techniques.
    • UCB1 and TS are designed to solve the same class of problems.
  38. 2024-02-q42024Q04Logistic regression vs k-NNmedium2 pts
    Tell 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.
  39. 2024-06-q42024Q04Markov Decision Processesmedium2 pts
    Mark each statement about Markov Decision Processes (MDPs) as true or false.
    • If the MDP has stochastic rewards, it may not admit a deterministic optimal policy.
    • $V^*(s) \ge Q^*(s, a)$ for all states $s$ and actions $a$, where $V^*$ is the optimal value function and $Q^*$ the optimal state-action value function.
    • A larger discount factor assigns more importance to the long-term effects of actions.
    • Value iteration is guaranteed to converge to the optimal value function in a finite number of steps.
  40. 2024-07-q42024Q04RL — model-based vs sample-based, on/off-policymedium2 pts
    Tell if the following statements about reinforcement learning are true or false. Motivate your answers.
    • When the model of the environment is known, it is never convenient to use sample-based reinforcement learning methods.
    • SARSA and Q-learning are both off-policy algorithms for control.
    • Q-learning can be considered the sample-based version of value iteration.
    • SARSA necessitates playing an $\varepsilon$-greedy policy with a vanishing $\varepsilon$ in order to converge to the optimal policy.
  41. 2024-01-q52024Q05Feature selectionmedium2 pts
    Indicate whether the following statements are true or false. Justify your answers.
    • Backward feature selection evaluates a number of models that is at most quadratic in the number of features.
    • Forward feature selection is guaranteed to deliver the best subset of features.
    • Wrapper methods should use the training error to guide the selection of the features.
    • Filter methods are more appropriate than wrapper methods when training the underlying model is expensive.
  42. 2024-02-q52024Q05SARSA vs Q-learningmedium2 pts
    Tell whether the following statements are true or false. Justify your answers.
    • SARSA is a prediction method since it makes use of the Bellman expectation equation for updating the value function.
    • Q-learning is based on Temporal Difference learning while SARSA is based on Monte Carlo estimation.
    • Both SARSA and Q-learning need to update the policy used to collect samples with the $\varepsilon$-greedy policy improvement.
    • Differently from SARSA, Q-learning does not need to wait for the action played in the next state to update the value function.
  43. 2024-06-q52024Q05Bias-variance trade-offmedium2 pts
    Consider 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.
    • Keeping $N$ fixed and increasing $d$, the variance of the model reduces.
    • Keeping $d$ fixed and increasing $N$, the bias of the model reduces.
    • Increasing both $N$ and $d$, the variance of the model increases.
    • Decreasing both $N$ and $d$, the bias of the model increases.
  44. 2024-07-q52024Q05OLS with nonlinear featuresmedium2 pts
    Consider 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.
    • The learned function is a hyperplane in input space.
    • OLS admits a closed-form solution.
    • The learned model has 3 parameters.
    • The overall significance of the model can be established with a single Student's t-test.
  45. 2024-01-q62024Q06Problem modeling — classification & RLmedium2 pts
    General 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.
  46. 2024-02-q62024Q06MDP modeling — on/off-policymedium2 pts
    Consider 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.)
  47. 2024-06-q62024Q06Bandits & RL modellingmedium2 pts
    An 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.
  48. 2024-07-q62024Q06Framing ML problemsmedium2 pts
    You 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.
  49. 2024-01-q72024Q07k-NN classificationmedium4 pts
    Given 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
    
  50. 2024-02-q72024Q07Regularised regression — gradient descentmedium4 pts
    Consider 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?
  51. 2024-06-q72024Q07Classification metricshard4 pts
    A 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.
  52. 2024-07-q72024Q07Multi-armed banditshard4 pts
    Consider 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.*
  53. 2024-01-q82024Q08Markov reward process & TDhard4 pts
    Consider 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.
  54. 2024-02-q82024Q08Finite & VC generalization boundshard4 pts
    We 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$.
  55. 2024-06-q82024Q08Linear SVMmedium4 pts
    A 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?
  56. 2024-07-q82024Q08VC dimension & Hoeffding boundshard4 pts
    Suppose 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$.*
  57. 2023-07-q12023Q01Bias–variance decompositionhard7 pts
    Beginning 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.
  58. 2023-08-q12023Q01Monte Carlo vs Temporal Differencehard7 pts
    Describe and compare the Monte Carlo and Temporal Difference approaches to policy evaluation.
  59. 2023-07-q22023Q02ε-greedy policymedium7 pts
    Explain what is an $\varepsilon$-greedy policy and why it is useful in Reinforcement Learning.
  60. 2023-08-q22023Q02Regularization — L1 vs L2hard7 pts
    Describe 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.
  61. 2023-06-q32023Q03Least-squares regressionmedium2 pts
    Consider 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))
    
  62. 2023-07-q32023Q03Generative vs discriminative, recallmedium2 pts
    Consider 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
    
  63. 2023-08-q32023Q03Policy iterationmedium2 pts
    Consider 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
    
  64. 2023-06-q42023Q04Overfitting & model complexitymedium2 pts
    The 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.
    Line chart of train error and test error versus a hyperparameter varied left to right. Train error (green triangles) starts near 0.16, dips slightly across the middle, then drops sharply to about 0 at the far right. Test error (orange circles) starts near 0.22, falls to a minimum around 0.15 in the middle, then rises back toward 0.21 at the far right.
  65. 2023-07-q42023Q04Feature selection, PCA, Lassomedium2 pts
    Tell 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.
  66. 2023-08-q42023Q04Linear regression — assumptionsmedium2 pts
    Assume 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.
    • Using Maximum Likelihood Estimation to compute the optimal parameter vector $\mathbf{w}^*$ has a closed-form solution, regardless of the noise distribution on the targets $t_i$.
    • The least squares estimator $\mathbf{w}^*$ is the one with the lowest Mean Squared Error among all linear unbiased estimators.
    • Introducing nonlinear basis functions increases the model flexibility at the cost of reducing its explainability.
    • We can use a regression model even if the targets $(t_1,\dots,t_N)$ form a time series (not independent, distribution depending on the index $i$).
  67. 2023-06-q52023Q05Valid kernelshard2 pts
    For 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$.
  68. 2023-07-q52023Q05MDP modeling — prediction vs controlmedium2 pts
    We 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.
  69. 2023-08-q52023Q05Overfitting vs underfittingmedium2 pts
    Indicate 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.
  70. 2023-06-q62023Q06Problem framing (supervised vs RL)medium2 pts
    An 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.
  71. 2023-07-q62023Q06UCB1 vs Thompson Samplingmedium2 pts
    Tell 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.
  72. 2023-08-q62023Q06Problem modeling — regression & MABmedium2 pts
    You 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.
  73. 2023-06-q72023Q07Perceptronhard4 pts
    A 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?
  74. 2023-07-q72023Q07Soft-margin SVM — slackmedium4 pts
    Consider 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?
  75. 2023-08-q72023Q07Logistic regression — loss & gradienthard4 pts
    Consider 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$.
  76. 2023-06-q82023Q08Q-learning & SARSAhard4 pts
    An 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?
  77. 2023-07-q82023Q08VC dimension & PAC boundhard4 pts
    Consider 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$.
  78. 2023-08-q82023Q08Multi-armed bandits — regretmedium4 pts
    Consider 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.
  79. 2022-06-q32022Q03PCA in practicemedium2 pts
    You 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]
    
  80. 2022-06-q42022Q04Perceptron & logistic regressionmedium2 pts
    The following statements concern classification algorithms. Mark each as true or false.
    • The perceptron classifier and the logistic regression classifier are both generalized linear models.
    • The logistic regression loss function is convex, therefore it admits a closed-form solution of the optimal weights.
    • If the training set is linearly separable, the logistic regression classifier and the perceptron classifier converge to the same solution.
    • The logistic regression classifier converges to a solution even when the training set is not linearly separable.
  81. 2022-06-q52022Q05VC dimensionmedium2 pts
    The following statements concern the VC dimension. Mark each as true or false.
    • If the VC dimension of a hypothesis space $\mathcal{H}$ is infinite, then $\mathcal{H}$ contains infinitely many hypotheses.
    • The VC dimension of a hypothesis space $\mathcal{H}$ is at least $k$ if and only if $\mathcal{H}$ shatters every subset of cardinality $k$ of the instance space.
    • The VC dimension of the logistic regression classifier with features $x_1, x_2$ is smaller than that of the logistic regression classifier with features $x_1, x_2, x_1^2, x_2^2, x_1 x_2$.
    • The VC dimension of a hypothesis space is affected by the size of the training set, but not by the size of the test set.
  82. 2022-06-q62022Q06Modelling ML problemsmedium2 pts
    You 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.
  83. 2022-06-q72022Q07K-NN regression & bias–variancehard4 pts
    Consider 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
    
  84. 2022-06-q82022Q08SARSAhard4 pts
    Consider 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.
  85. 2021-06-q32021Q03Model selection for k-NNmedium2 pts
    Consider 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)
    
  86. 2021-06-q42021Q04Linear regressionmedium2 pts
    Are the following statements about Linear Regression true or false? Motivate your answers.
    • Linear regression can be used to model processes showing a non-linear behaviour.
    • In the case we have a small number of samples, the use of Bayesian Linear Regression is advised as a substitute for classical Linear Regression.
    • After performing Ridge Regression with regularisation parameter $\lambda=k$, the eigenvalues of the matrix $(\Phi^\top\Phi+\lambda I)$ are smaller than or equal to $k$.
    • A Gaussian Process can be reformulated as a specific case of Linear Regression over a specific set of features.
  87. 2021-06-q52021Q05Choosing an RL methodmedium2 pts
    You 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.
    • Monte Carlo Policy Iteration
    • Value Iteration
    • SARSA
    • Q-Learning
  88. 2021-06-q62021Q06Parametric vs non-parametric methodsmedium2 pts
    Tell 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
  89. 2021-06-q72021Q07Hard-margin SVM geometryhard4 pts
    Consider 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?
  90. 2021-06-q82021Q08VC dimension & sample complexityhard4 pts
    1. 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)$.*
  91. adaboostBoostinghard5 pts
    Illustrate the AdaBoost algorithm, explain its purpose and in which cases it is useful.
  92. baggingBaggingmedium4 pts
    Explain the concept of Bagging (Bootstrap Aggregating) in machine learning. Describe a scenario where bagging would be particularly beneficial.
  93. bagging-vs-boostingEnsemblesmedium4 pts
    Compare Bagging and Boosting in terms of how they combine models and their impact on bias and variance.
  94. bayesian-linear-regression-vs-lsBayesian linear regressionmedium5 pts
    Describe the Bayesian Linear Regression approach and compare it to the Least-Squares (LS) method.
  95. bayesian-linear-regression-vs-ridgeBayesian linear regressionmedium4 pts
    Describe the Bayesian Linear Regression method and how it compares to Ridge Regression.
  96. bayesian-ridge-interpretationBayesian ridgemedium4 pts
    Illustrate and explain the Bayesian interpretation of ridge regression.
  97. bias-variance-decompositionBias–variancehard6 pts
    Illustrate 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.
  98. bias-variance-tradeoffBias–variancemedium4 pts
    Explain 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.
  99. boostingBoostingmedium5 pts
    Explain 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.
  100. cross-validationCross-validationmedium4 pts
    Introduce the concept of cross-validation for model evaluation and describe at least two common strategies for implementing it, including their advantages and disadvantages.
  101. epsilon-greedyExplorationeasy3 pts
    Explain what an eps-greedy policy is and why it is useful in RL.
  102. exploration-exploitationExplorationmedium4 pts
    In RL, explain the exploration–exploitation trade-off and discuss how the discount factor gamma influences an agent's long-term behaviour.
  103. feature-selectionFeature selectionmedium5 pts
    Discuss at least three methods used for feature selection and compare their advantages and disadvantages.
  104. gram-matrixGram matrixeasy3 pts
    Explain what a Gram matrix is and its role in kernel methods within machine learning.
  105. kernel-trickKernel trickmedium4 pts
    Explain what the kernel trick is, what it is used for, and in which ML methods it can be used.
  106. logistic-regressionLogistic regressionmedium4 pts
    Describe the logistic regression model and how it is trained.
  107. mc-vs-tdMC vs TDmedium5 pts
    Compare Monte Carlo (MC) and Temporal Difference (TD) methods for model-free prediction / policy evaluation. Discuss their advantages and disadvantages.
  108. pac-bound-consistentPAC boundhard5 pts
    Illustrate the PAC bound for consistent learners (training error equal to zero) and its applications.
  109. pac-learning-definitionPAC learninghard5 pts
    Define 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.
  110. pcaPCAmedium4 pts
    Describe the PCA technique, how it works and what its purpose is.
  111. perceptronPerceptronmedium4 pts
    Describe the perceptron model and how it is trained.
  112. perceptron-pseudocode-proofPerceptronhard5 pts
    Write 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
    
  113. perceptron-vs-logisticPerceptron vs logisticmedium5 pts
    Compare the perceptron algorithm and logistic regression in terms of the update rule, loss functions, and convergence properties.
  114. q-learning-vs-sarsaQ-learning & SARSAmedium5 pts
    Describe and compare Q-learning and SARSA.
  115. regularization-l1-l2Regularisationmedium4 pts
    Describe 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.
  116. ridge-vs-lassoRidge vs Lassomedium4 pts
    Describe and compare Ridge regression and Lasso regression.
  117. rl-prediction-control-mcPrediction & controlmedium5 pts
    Describe the two problems tackled by RL — prediction and control — and describe how Monte Carlo RL techniques can be used to solve these two problems.
  118. svm-overviewSVMmedium5 pts
    Describe the SVM for supervised classification problems. In particular explain how they work and their strengths and weaknesses.
  119. svm-training-generalization-boundSVMhard5 pts
    Describe 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.
  120. svm-vs-logisticSVM vs logisticmedium5 pts
    Compare Logistic regression and SVM. Discuss their loss functions, output interpretation, margin, regularization, and mention one scenario where each method is preferable.
  121. thompson-samplingBanditshard4 pts
    Describe the Thompson Sampling algorithm for multi-armed bandit (MAB) problems.
  122. train-validation-testModel evaluationeasy4 pts
    Describe the processes of training, validation and testing in supervised learning. Explain how to manage the dataset and what common mistakes should be avoided.
  123. valid-kernelsValid kernelsmedium4 pts
    Describe what a valid kernel function is and describe how valid kernels can be built.
  124. value-iterationValue iterationmedium4 pts
    Describe the value iteration algorithm and its properties.
  125. value-vs-policy-iterationDP methodsmedium5 pts
    Describe and compare value iteration and policy iteration.
  126. vc-dimensionVC dimensionmedium4 pts
    What is the VC dimension of a hypothesis space? What can it be used for?