Docsity

Appunti di Machine Learning | prof. Restelli, Dispense di Machine learning

Anteprima parziale del testo

Scarica Appunti di Machine Learning | prof. Restelli e più Dispense in PDF di Machine learning solo su Docsity!

Machine Learning

Gabriele Giusti

Politecnico di Milano a.a. 2022/

ii

  • 1 Introduction to Machine Learning
    • 1.1 Types of Machine Learning
  • 2 Supervised Learning
    • 2.1 The idea behind supervised learning
    • 2.2 Regression
      • 2.2.1 Linear Regerssion
      • 2.2.2 Discriminative vs Generative
      • 2.2.3 Minimizing Least Squares
      • 2.2.4 Gradient optimization
      • 2.2.5 Maximum Likelihood
      • 2.2.6 Gauss-Markov Theorem
      • 2.2.7 Multiple Outputs
      • 2.2.8 Ridge Regression
      • 2.2.9 Lasso
      • 2.2.10 Bayesian approach
      • 2.2.11 Bayesian linear regression
      • 2.2.12 Predictive distribution
    • 2.3 Classification
      • 2.3.1 Linear classification
      • 2.3.2 Discriminant function
      • 2.3.3 Multiple classes
      • 2.3.4 Least squares classification
      • 2.3.5 Perceptron
      • 2.3.6 Logistic regression
      • 2.3.7 Naive Bayes
      • 2.3.8 K-Nearest Neighbors
      • 2.3.9 Kernel Methods
      • 2.3.10 Kernel trick
      • 2.3.11 Construction Kernels
      • 2.3.12 Support Vector Machines
      • 2.3.13 Maximum margin classifiers
      • 2.3.14 Dual representation
      • 2.3.15 Curse of Dimensionality and SVMs
      • 2.3.16 Handling noisy data
  • 3 Model selection - 3.0.1 “No Free Lunch” Theorem - 3.0.2 Bias-Variance decomposition - 3.0.3 Curse of dimensionality - 3.0.4 Feature selection - 3.0.5 Direct estimation of Test Error - 3.0.6 Adjustment Techniques - 3.0.7 Shrinkage Methods - 3.0.8 Dimension reduction - 3.0.9 Improve the Bias-Variance tradeoff
  • 4 PAC method - 4.0.1 Probably Approximately Correct bound - 4.0.2 PAC learning - 4.0.3 Agnostic learning - 4.0.4 Shattering a Set of Instances
  • 5 Reinforcement Learning
    • 5.1 Markov Decision Processes
      • 5.1.1 Sequential Decision Making
      • 5.1.2 The Agent-Environment Interface
      • 5.1.3 Markov Assumption
      • 5.1.4 Discrete-time Finite Markov Decision Processes
    • 5.2 Dynamic Programming
      • 5.2.1 Policy Evaluation
      • 5.2.2 Policy Improvement
      • 5.2.3 Policy iteration
      • 5.2.4 Value Iteration
      • 5.2.5 Infinite Horizon Linear Programming
    • 5.3 Reinforcement Learning algorithms
      • 5.3.1 Multi-armed Bandit
      • 5.3.2 Action-Value methods
      • 5.3.3 Multi-armed Bandit setting
      • 5.3.4 Monte Carlo methods
      • 5.3.5 Temporal Difference Learning
      • 5.3.6 TD Prediction
      • 5.3.7 n-Step TD Prediction
      • 5.3.8 The forward view of TD(λ)
      • 5.3.9 The Backward View of TD(λ)
      • 5.3.10 SARSA: On-Policy TD Control
      • 5.3.11 Q-Learning: Off-Policy TD Control

Chapter 1

Introduction to Machine

Learning

To understand what is machine learning we have to firstly understand what is learning. According to Mitchell we have the following definition: ”A computer is said to learn from experience E with respect to some class of tasks T and performance measure P , improveses with experience E ”. Machine learning is a sub-field of Artificial Intelligence, where the knowledge comes from two sources:

  • Experience -> Use previously recognized patterns to extract informations from new data according to a specific one
  • Induction -> Is used to learn patterns and generalize knowledge from specific examples.

Machine learning inverts the traditional paradigm of programming where a computer, that runs a program, receive in input some data and produces an output according to how the program elaborate that data. The new paradigm, instead, take in input some data and the desired output and extract the algo- rithm that matches both the inputs.

The main scope of machine learning is to make informed decisions on new, unseen data because ofte it is too difficult to design a set of rules ”by hand”. Machine learning allows to automatically extract relevant information from data applying it to analize new data. The objective is to get computers to program themselves, writing software in a bottleneck and let the data do the work.

There are many fields in which machine learning is very usful, such as:

  • Computer vision and robotics
  • Speech recognition
  • Biology and medicine
  • Finance
  • Information retrieval, Web search, ...

Overall, unsupervised learning is a powerful tool for exploring and under- standing complex datasets, and it is commonly used in fields such as computer vision, natural language processing, and bioinformatics.

Reinforcement learning is a type of machine learning where an agent learns to take actions in an environment to maximize a cumulative reward signal. The training set is defined as follows:

D = {⟨x, u, x′, r⟩} =⇒ π∗(x) = argmaxu{Q∗(x, u)}

where x is the state, u is the action, x’ is the new state after the action, r is the result. The goal is to learn a policy that maps states to actions that maxi- mize the long-term reward and to maximize the utility. The main problems to solve include exploration-exploitation tradeoff, credit assignment, and balancing short-term and long-term rewards. Techniques used include Q-learning, policy gradient methods, and actor-critic methods.

2.1 The idea behind supervised learning

Given a space F , which is the space of all possible functions that match a specific input with its given output, the goal of supervised learning is to approximate a specific function f belonging to F given the dataset D. Any supervised learning algorithm needs to specify three things:

  • Define the loss function L
  • Choose the hypothesis sapce H
  • Optimize to find an approximation model h

But if we know ”a priori” the loss function we are not talking about super- vised learning but of functional approximation. So the idea is to find the right size of the hypothesis space in order to efficiently find the right approximation of the loss function L and of the function f.

We can summarize saying that every machine learning algorithm has three components which are Representation (Hypothesis space), Evaluation (Loss function), Optimization (Find an approximate model).

2.2 Regression

2.2.1 Linear Regerssion

Regression is a type of supervised learning in machine learning where the goal is to predict a continuous output variable based on one or more input variables. The aim of regression is to establish a relationship between the input variables (also known as features or predictors) and the output variable (also known as the target variable) by fitting a mathematical model to the data.

The primary goal of regression is to estimate the relationship between the input and output variables accurately. The resulting model can then be used to make predictions about the output variable for new, unseen data.

Regression models can be used for a wide variety of applications, including prediction, forecasting, and analysis of trends. For example, a regression model can be used to predict the sales of a product based on factors such as price, advertising spend, and competitor activity. It can also be used to forecast the weather based on historical data, or to analyze the relationship between a per- son’s age, weight, and blood pressure.

In functional terms, regression involves finding the best-fitting line or curve that passes through the data points. The most commonly used regression tech- niques include linear regression, polynomial regression, logistic regression, and ridge regression. These models differ in terms of the mathematical functions used to fit the data and the assumptions made about the relationship between the input and output variables. Once the model is trained on the training data, it can be used to make predictions on new data by inputting the values of the input variables into the model. The output of the model will be the predicted

value of the output variable.

Many real processes can be approximated with linear models. Linear regres- sion often appears as a module of larger systems. A linear model is a model linear with respect to the input. It is not constrained to be approximated by a linear function. Linear problems can be solved analytically. Linear regression could be augmented with kernels, so it can model non-linear relationships.

Linear regression follows the linear function in the parameter w :

y(x, w) = w 0 +

D∑− 1

j=

wj xj = wT^ x

where x is the input set of features x = (1, x 1 , ..., xD− 1 ) and w 0 is the offset.

In order to quantify what it means to do well or poorly on a task we need to define a loss (error) function:

L(t, y(x))

and we can say that the average, or expected, loss is given by:

E[L] =

L(t, y(x))p(x, t)dxdt

where p(x, t) is the process that defined the dataset D, with input x and output t. A common choice is the squared loss function :

E[L] =

(t − y(x))^2 p(x, t)dxdt

The optimal solution (if we assume a completely flexible function) is the con- ditional average , or the expected value of the target given the input:

y(x) =

tp ( t | x )dt = E[t|x]

We can generalize again the loss function in a simple way in the so called Minkowski loss:

E[L] =

|t − y(x)|q^ p(x, t)dxdt

The minimum of E[L] is given by:

  • the conditional mean for q = 2
  • the conditional median for q = 1
  • the conditional mode for q → 0

To consider non-linear functions we can use non-linear basis function, the important thing is that w remains linear:

y(x, w) = w 0 +

M∑ − 1

j=

wj ϕj (x) = wT^ ϕ(x)

2.2.3 Minimizing Least Squares

Given the dataset with N samples, I can consider the following error (loss) function:

L(w) =

∑^ N

n=

(y(xn, w) − tn)^2

This is the (half) residual sum of squares, also known as sum of squared errors. This function can also be written as the sum of the ℓ 2 -norm of the vector of residual errors:

RSS(w) = ||ϵ||^22 =

∑^ N

i=

ϵ^2 i

Let’s write RSS in matrix form with ￿ = (ϕ(x 1 ), ..., ϕ(xN ))T^ , where ￿ is the dataset. The number of rows equals the number of samples, the number of columns equals the number of features (or records), and t = (t 1 , ..., tN ), which is the target vector. The new loss function is:

L(w) =

(t − ￿w)T^ (t − ￿w)

which is exactly the function L(w) previously obtained.

If we compute the first and second derivative we obtain:

∂L(w) ∂w = −￿T^ (t − ￿w)

∂^2 L(w) ∂w∂wT^

= ￿T^ ￿

The gradient is the first derivative, the second derivative is the diation. All the eigen values of the diation are non-negative, and is always semidefinite positive. We can compute the optimal wights, assuming that ￿T^ ￿ is non-singular:

w ˆOLS = (￿T^ ￿)−^1 ￿T^ t

The complexity is O(N M 2 + M 3 ).

2.2.4 Gradient optimization

The closed form identified earlier is not practical with big amounts of data because it’s too costly, so we use the gradient optimization. To actually implement this method we can use sequential (online) updates thanks the stochastic gradient descent , in which the gradient is computed for each individual data point and the coefficients are updated after each data point. We can define the loss function as a sum over samples

(L(x) =

n

L(xn))

Than the stochastic gradient descent algorithm updates the parameter w using

w(k+1)^ = w(k)^ − α(k)∇L(xn) =⇒ w(k+1)^ = w(k)^ − α(k)(w(k)

T ϕ(xn) − tn)ϕ(xn)

The ”-” sign means that the objective is that of minimizing the outcome. The α(k)^ term is called the learning rate , and k is the k-th iteration. To have convergence, the learning rate must satisfy two constraints:

∑^ ∞

k=

α(k)^ = +∞

∑^ ∞

k=

α(k)

2 < +∞

This two conditions provides two boundaries in which the learning rate has to be.

2.2.5 Maximum Likelihood

The error function could be motivated as the maximum likelihood solution under an assumed Gaussian noise model. Assume that the target variable t is given by a deterministic function y( x , w ) with additive Gaussian noise so that

t = y(x, w) + ϵ

where ϵ is a zero mean Gaussian random variable (∼ N (O, σ^2 )) with precision (inverse variance) β. Thus can we write

p(t|x, w, β) = N (t|y(x, w), β−^1 )

Given N samples, with inputs X = x 1 , ..., xN and outputs t = ( t 1 , ..., t N )T^ , and making the assumption that these data points are drawn independently from the distribution p(t|x, w, β), the likelihood function is

p(t|X, w, σ^2 ) =

∏^ N

n=

N

tn|wT^ ϕ(xn), σ^2

Assuming the samples to be independent and identically distributed ( iid ), we consider the log-likelihood

ℓ(w) = ln p(t|X, w, σ^2 ) =

∑^ N

n=

ln p(tn|xn, w, σ^2 ) = −

N

ln(2πσ^2 ) −

2 σ^2

RSS(w)

To find the maximum likelihood, we equal the gradient to zero

∇ℓ(w) =

∑^ N

n=

tnϕ(xn)T^ − wT

( N

n=

ϕ(xn)ϕ(xn)T

wM L = (￿T^ ￿)−^1 ￿T^ t

This is because the gradient of the logarithm of the likelihood function gives us the direction of steepest ascent, so setting it to zero corresponds to finding the maximum value of the likelihood function.

These two equations are called the normal equations for the least squares problem. There are some assumptions that have to be made:

LD (w) is the error on data, for example the RSS. LW (w) is the model complex- ity, or regularization term. The importance of these two terms is given by the regularization coefficient λ. By taking LW (w) = 12 wT^ w = 12 || w ||^22 we get

L(w) =

∑^ N

i=

(ti − wT^ ϕ(xi))^2 +

λ 2

|| w ||^22

This is called ridge regression (or weight decay), because it encourages weights to decay towards zero, unless supported by the data. It is a regularization (parameter shrinkage) method that helps to reduce the variance of the estimated coefficients, and thus avoids over-fitting. The loss function is still quadratic with w w ˆridge = (λI + ￿T^ ￿)−^1 ￿T^ t

w ˆridge is the vector of estimated coefficients for ridge regression. This equation shows that the ridge regression estimator is obtained by adding a multiple of the identity matrix to the ￿T^ ￿ matrix, which helps to regularize the estimated coefficients and avoid overfitting.

2.2.9 Lasso

Another popular regularization method is lasso , that has the property that if λ is sufficiently large, some of the coefficients wj are driven to zero, leading to a sparse model in which the corresponding basis functions play no role.

L(w) =

∑^ N

i=

(ti − wT^ ϕ(xi))^2 + λ 2

|| w || 1

where || w || 1 =

∑N

j=1 |wj^ |. Differently from ridge, lasso is nonlinear in the^ ti^ and no closed-form solution exists (quadratic programming problem). Nonetheless, it has the advantage of making some weight wj equal to zero for values of λ sufficiently large, leading to a sparse model in which the corresponding basis functions play no role.

2.2.10 Bayesian approach

Bayesian linear regression is a statistical technique used to model the relation- ship between a dependent variable and one or more independent variables. Un- like traditional linear regression, which estimates the coefficients of the model using maximum likelihood estimation, Bayesian linear regression uses Bayesian inference to estimate the parameters of the model. This approach allows for the incorporation of prior knowledge and uncertainty into the analysis, which can lead to more accurate predictions and better understanding of the underlying relationships in the data. We define the model that expresses our knowledge qualitatively and will have some unknown parameters. We capture our as- sumptions about unknown parameters by specifying the prior distribution over those parameters before seeing the data. Then we observe the data and compute the posterior probability distribution for the parameters of this data. The posterior distribution is used to:

  • Make predictions by averaging over the posterior distribution
  • Examine/Account for uncertainty in the parameter values
  • Make decisions by minimizing expected posterior loss

Posterior distribution

The posterior distribution for the model parameters can be found by combining the prior with the likelihood for the parameters given data. This is accom- plished using Bayes’ Rule

P (parameters|data) =

P (data|parameters)P (parameters) P (data)

where the parameters are our weights and the data are our dataset D. So the formula become

p(w|D) =

p(D|w)P (w) P (D) where:

  • p(w|D) is the posterior probability of parameters w given the training data D.
  • p(D|w) is the probability ( likelihood ) of observing D given w
  • P ( w ) is the prior probability over the parameters
  • P (D) is the marginal likelihood ( normalizing constant )

The marginal likelihood could be written as P (D) =

p(D|w)P (w) dw

The idea behind the Bayesian approach is to compute the posterior knowl- edge, given a prior, and then use the result as a prior to compute the nest pos- terior, iteratively. The Bayes’ rule states that posterior ∝ likelihood × prior, so the posterior has to be in the same class of prior. We want the most probable value of the w given the data: maximum a posteriori (MAP). It is the mode of the posterior.

2.2.11 Bayesian linear regression

Using Bayesian linear regression is another valid approach to avoid over- fitting in ML. In the Bayesian approach, the parameters of the model are considered as drawn from some distribution (random). Assuming a Gaussian likelihood model, the conjugate prior is Gaussian too. This is the probability distribution over the model w

p(w) = N (w|w 0 , S 0 )

where S 0 is the covariance matrix and w 0 is the mean.

Next, we compute the posterior distribution, which is proportional to the product of the likelihood function and the prior. Given the data D, the posterior is still Gaussian

p(w|t, ￿, σ^2 ) ∝ N (w|w 0 , S 0 )N (t|￿w, σ^2 IN ) = N (w|wN , SN )

2.3.1 Linear classification

In linear classification, the input space is divided into decision regions whose boundaries are called decision boundaries or decision surfaces. We will con- sider linear models for classification. In linear regression models, the model prediction y(x, w) was given by a linear function of parameters w. In the sim- plest case, the model is also linear in the input variables and therefore takes the form

y(x, w) = w 0 +

D∑− 1

j=

wj xj = xT^ w + w 0

For classification problems, however, we wish to predict discrete class labels, or more generally posterior probabilities that lie in the range (0, 1). To achieve this, we consider a generalization of this model in which we transform the linear function of w using a nonlinear function f (·) so that

y(x, w) = f (xT^ w) + w 0

f (·) is known as the activation function. The decision surfaces correspond to y(x, w) = const. It follows that xT^ w+w 0 and hence the decision surfaces are linear functions of x , even if the activation function is nonlinear. These class of models are called generalized linear models. They are no longer linear in parameters and have more complex analytical and computational properties than regression. We consider fixed nonlinear basis functions. in two-class problems, we have a binary target value t ∈ { 0 , 1 }, such that t = 1 is the positive class and t = 0 is the negative class. We can interpret the value of t as the probability of the positive class, with the values of probability taking only the extreme values of 0 and 1. The output of the model can be represented as the probability that the model assigns to the positive class. If there are K classes, we can use a 1-of-K encoding scheme in which t is a vector of length K such that if the class is Cj , then all the elements tk of t are 0 except element tj. For example if t = (0, 1 , 0 , 0 , 0)T

we can say that K = 5 and the output belongs to class 2. t is a vector of class probabilities. There are three different approaches to classification:

  • Discriminant function -> build a function that directly maps each input to a specific class
  • Probabilistic approach -> model the conditional probability distribu- tion p(Ck|x) and use it to make optimal decisions. Includes two different alternatives - Probabilistic discriminative approach -> model p(Ck|x) directly, for instance using parametric models (e.g. logistic regression) - Probabilistic generative approach -> model class conditional densities p(Ck|x) together with prior probabilities p(Ck) for the classes. Infer the posterior using Bayes’ Rule

P (Ck|x) = p(x|Ck)p(Ck) p(x)

2.3.2 Discriminant function

A discriminant is a function that takes an input vector x and assigns it to one of K classes, denoted Ck.

Two classes

The simplest representation of a linear discriminant function is obtained by taking a linear function of the input vector so that

y(x) = xT^ w + w 0

where w is called the weight vector and w 0 is a bias. An input vector x is assigned to class C 1 if y(x) ≥ 0 and to class C 2 otherwise. The corresponding decision boundary is therefore defined by the relation y(x) = 0, which corre- sponds to a (D − 1)-dimensional hyperplane within the D-dimensional input space. Given two points xA and xB on the decision surface

y(xA) = y(xB ) = 0 wT^ (xA − xB ) = 0

and hence the vector w is orthogonal to every vector lying within the decision surface, and so w determines the orientation of the decision surface. So, if x is on the decision surface, then the normal distance from the origin to the decision surface is given by wT^ x || w || 2

w 0 || w || 2

The bias parameter w 0 determines the location of the decision surface. In this case, the decision surfaces are D-dimensional hyperplanes passing through the origin of the (D + 1)-dimensional expanded input space.

2.3.3 Multiple classes

Consider the extension of linear discriminants to K > 2 classes. Consider the use of K - 1 classifiers, each of which solves a two-class problem of separating points in a particular class Ck from points not in that class. This is known as a one- versus-the-rest classifier. This approach could lead to regions of input space that are ambiguously classified. An alternative is to introduce K(K − 1)/2 binary discriminant functions, one for every possible pair of classes. This is known as a one-versus-one classifier. In this case, we can avoid ambiguous regions by considering a single K-class discriminant comprising K linear discriminant functions of the form yk(x) = xT^ wk + wk 0

where k = 1,... , K. Assign x to class Ck if yk(x) > yj (x) ∀j ̸= k. The resulting decision boundaries are singly connected and convex. For any two points that lie inside the region Rk

yk(xA) > yj (xA) and yk(xB ) > yj (xB )

implies that for positive α

yk(αxA + (1 − α)xB ) > yj (αxA + (1 − α)xB )

due to linearity of the discriminant functions.