Docsity

Appunti Quantitative Methods, Appunti di Analisi Statistica

Toggle sidebar
bg1
2.1 What is statistical learning?................................................................................................................1
2.2 Assessing Model Accuracy..................................................................................................................3
K-Nearest Neighbors algorithm................................................................................................................7
3.1. Simple Linear Regression.................................................................................................................12
3.2 Multiple Linear Regression................................................................................................................15
3.3 Other Considerations in the Regression Model..................................................................................17
4.3 Logistic Regression............................................................................................................................26
4.6 Generalized linear models (GLMs).....................................................................................................28
5.1 Cross-Validation................................................................................................................................35
6.2.1. Ridge Regression...........................................................................................................................42
6.2.2. Lasso Regression...........................................................................................................................43
6.3 Dimension reduction methods...........................................................................................................44
8.1 Thee basics of Decision Trees............................................................................................................47
8.2.1 Bagging.........................................................................................................................................53
8.3 Lab: Decision Trees............................................................................................................................57
12.2 Principal Components Analysis – Unsupervised Learning.................................................................62
12.4 Clustering Methods - Unsupervised learning...................................................................................66
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d

Anteprima parziale del testo

Scarica Appunti Quantitative Methods e più Appunti in PDF di Analisi Statistica solo su Docsity!

  • 2.1 What is statistical learning?................................................................................................................
  • 2.2 Assessing Model Accuracy..................................................................................................................
  • K-Nearest Neighbors algorithm................................................................................................................
  • 3.1. Simple Linear Regression.................................................................................................................
  • 3.2 Multiple Linear Regression................................................................................................................
  • 3.3 Other Considerations in the Regression Model..................................................................................
  • 4.3 Logistic Regression............................................................................................................................
  • 4.6 Generalized linear models (GLMs).....................................................................................................
  • 5.1 Cross-Validation................................................................................................................................
  • 6.2.1. Ridge Regression...........................................................................................................................
  • 6.2.2. Lasso Regression...........................................................................................................................
  • 6.3 Dimension reduction methods...........................................................................................................
  • 8.1 Thee basics of Decision Trees............................................................................................................
  • 8.2.1 Bagging.........................................................................................................................................
  • 8.3 Lab: Decision Trees............................................................................................................................
  • 12.2 Principal Components Analysis – Unsupervised Learning.................................................................
  • 12.4 Clustering Methods - Unsupervised learning...................................................................................

2.1 What is statistical learning?

Assume that there is some relationship between Y and X^ =( x 1

, x 2

, ... , x p

), which can be written in the very

general form y = f ( x )+ ε

f represents some fixed but unknown function of X.

ε random error term, it’s independent from X and has 0-mean.

In essence, statistical learning refers to a set of approaches for estimating f.

2.1.1. Two reasons why we may want to estimate f

a) Prediction

In many situations, a set of inputs X are readily available, but the output Y cannot be easily obtained. In

this setting, since the error term averages to zero, we can predict Y using

^

Y =

^

f ( X )

In this setting,

^

f is often treated as a black box, in the sense that one is not typically concerned with the

exact form of f, provided that it yields accurate predictions for

^

Y.

The accuracy of

^

Y as a prediction for Y depends on two quantities, which we will call the reducible

error and the irreducible error.

 In general,

^

f will not be a perfect estimate for f, and this^ inaccuracy^ will introduce some error. This

error is reducible because we can potentially improve the accuracy of

^

f by using the most

appropriate statistical learning technique to estimate f^.

 The variability associated with ε also affects the accuracy of our predictions. This is known as the

irreducible error because no matter how well we estimate f, we should not be able to reduce the

error introduced  E ( Y −

^

Y )

2

≥ σ ε

2

However, for some specific databases we may be able to reduce

the irreducible errorthis is not a good as it will lead to overfitting and our model won’t be able

to predict new data in an accurate way. (See below)

The quantity ε may contain unmeasured variables that are useful in predicting Y or unmeasurable

variation.

E ( Y −

^

Y )

2

= E ( f ( X ) + ε −

^

f ( X ))

2

¿( f ( X ) −

^

f ( X ) )

2

  • Var ( ε )

Reducible Irreducible

Example. A company is interested in conducting a direct-marketing campaign. The goal is to identify

individuals who are likely to respond to a mailing, based on observations of demographic variables. The

company wants to accurately predict the response using the predictors.

b) Inference

In this situation we wish to estimate f, but our goal is not necessarily to make predictions for Y.

Now

^

f cannot be treated as a black box: we need to know its exact form.

In this setting, one may be interested in answering the following questions:

  • Which predictors are associated with the response? Often only a small fraction of the available

predictors is substantially associated with Y; identify them can be very useful, depending on the

application.

  • What is the relationship between the response and each predictor? Some may have a positive

relationship with Y, other a negative one.

Depending on the complexity of f, the relationship between the response and a given predictor may also

depend on the values of the other predictors.

  • Can the relationship between Y and each predictor be adequately summarized using a linear equation, or

is the relationship more complicated? Historically, most methods for estimating f have taken a linear

form. But often the true relationship is more complicated.

Seen during lectures

interpretability, using different statistical learning methods.

2.1.4 Supervised Versus Unsupervised Learning

Two main families:

a) Supervised learning methods  requires us to make some choice deciding the variable to predict and

the ones to be predicted.

a. Classification methods  qualitative variables

b. Regression methods  quantitative variables

b) Unsupervised learning methods  all the variables have the same role. We observe a vector of

measurements xi but no associated response yi. In this setting, we are in some sense working blind; we

lack a response variable that can supervise our analysis.

a. Cluster analysis or clustering  ascertain, on the basis of

X

1

, ... , X

n , whether the observations fall

into relatively distinct groups. If there are p variables in our data set, then p

( p − 1 )

distinct

scatterplots can be made, and visual inspection is not a viable way to identify clusters.

Sometimes saying if a method should be considered supervised or unsupervised is less clear-cut. In the case

where for m^ of the observations, where m < n, we have both predictor measurements and a response

measurement. For the remaining n − m observations, we have predictor measurements but no response

measurement. Such a scenario can arise if the predictors can be measured relatively cheaply but the

corresponding responses are much more expensive to collect. We refer to this setting as a semi-supervised

learning problem.

2.1.5 Regression Versus Classification Problems

Variables can be characterized as either quantitative or qualitative. We tend to refer to problems with a

quantitative response as regression problems, while qualitative response is often referred to as

classification problems. However, the distinction is not always that crisp.

Some statistical models, i.e. KNN and boosting , can be used in the case of either quantitative or qualitative

response.

2.2 Assessing Model Accuracy..................................................................................................................

There is no free lunch in statistics: no one method dominates all others over all possible data sets. Hence it is

an important task to decide for any given set of data which method produces the best results.

In this section, some of the most important concepts that arise in selecting a statistical learning procedure

for a specific data set are discussed.

2.2.1. Measuring the Quality of Fit

In order to evaluate the performance of a statistical learning method on a given data set, we need some way

to measure how well its predictions actually match the observed data.

The most commonly used measure is the mean squared error (MSE):

MSE =

n

∑

i = 1

n

( y i

^

f (^) ( x i

) )

2

where

^

f ( x i

) is the prediction that f gives for the i th observation.

The MSE will be small if the predicted responses are very close to the true responses  The lower the

MSE the better is the performance (the approximation).

MSE ≥ 0 always.

Is there a reference level? the MSE of the mean of the dependent variable  MSE^ (^ ^ μ )^ = var^ (^ y ), better if the

MSE is lower than this value. Blue line

Seen during lectures

In some cases, the root squared error (RMSE) may be convenient due to high values  RMSE^ (^ ^ μ )= sd^ (^ y^ ),

If the MSE is computed using the training data that was used to fit the model it should more accurately be

referred to as the training MSE. However, we are interested in the accuracy of the predictions that we

obtain when we apply our method to previously unseen test data  we want to choose the method that gives

the lowest test MSE , as opposed to the lowest training MSE.

So, if we have a large number of observations, we can compute the average squared prediction error for the

test observations (x 0 , y 0 ).

Ave (^) ( y o

^

f (^) ( x 0

) )

2

There is no guarantee that the method with the lowest training MSE will also have the lowest test MSE.

 the problem is that many statistical methods specifically estimate coefficients so as to minimize the

training set MSE. For these methods, the training set MSE can be quite small, but the test MSE is often

much larger.

 As model flexibility increases, the training MSE will decrease, but the test MSE may not. More

specifically, when a given method yields a small training MSE but a large test MSE , we are said to be

overfitting the data. In this case, our statistical learning procedure is working too hard to find patterns in

the training data and may be picking up some patterns that are just caused by random chance rather than

by true properties of the unknown function f , the test MSE will be very large because the supposed

patterns that the method found in the training data simply don’t exist in the test data.

Note. Regardless of whether or not overfitting has occurred, we almost always expect the training MSE to

be smaller than the test MSE because most statistical learning methods either directly or indirectly seek to

minimize the training MSE.

One important method for estimating the test MSE using the training data is cross-validationdifferent

datasets (samples) for training the model and for fitting it.

2.2.2 The Bias-Variance Trade-Off (book)

It is possible to show that the expected test MSE , for a given value x 0 , can always be decomposed into the

sum of three fundamental quantities :

  1. Variance of

^

f (^) ( x 0 )

  1. Squared bias pf

^

f ( x 0

)

  1. Variance of the error term ε.

E

(

y 0

^

f (^) ( x 0

) (^) )

2

= Var (

^

f (^) ( x 0

) (^) )+[ Bias^

^

f (^) ( x 0

) (^) ]

2

  • Var ( ε )

 E

(

y 0

^

f (

x 0 )^ )

2

defines the expected test MSE at x 0

, it refers to the average MSE that we would obtain if

we repeatedly estimated f using a large number of training sets, and tested each

x 0

 in order to minimize the expected test error , we need to select a statistical learning method that

simultaneously achieves low variance and low bias.

For the example data, the Bayes error rate is 0.133. It is greater than zero, because the classes overlap in

the true population, which implies that

max jPr(Y = j|X =^

x 0 ) < 1 for some values of^

x 0_._

The Bayes error rate is analogous to the irreducible error, discussed above.

For real data, we do not know the conditional distribution of Y given X, and so computing the Bayes

classifier is impossible, so it’s mostly used as a standard against which compare other methods.

K-Nearest Neighbors algorithm................................................................................................................

Works both for classification and regression

KNN Regression

Given a value for K^ and a prediction point x 0 , KNN regression first identifies the K^ training observations

that are closest to x 0

represented by N 0

. It then estimates f (x 0 ) using the average of all the training

responses in N 0

^

f (^) ( x 0

) =^

K

∑

x i

∈ N 0

y i

A small value for K provides the most flexible fit, which will have low bias but high variance.

Decrease in performance as the dimension increases is a common problem for KNN, and results from the

fact that in higher dimensions there is effectively a reduction in sample size.

KNN Classifier

Given a positive integer K^ and a test observation

x 0 , the KNN classifier first identifies the^

K (^) points in the

training data that are closest to x 0

, represented by N 0

. It then estimates the conditional probability for

class j as the fraction of points in N 0

whose response values equal j :

Pr (^) ( Y = j | X = x 0 )

K

∑

xi∈ N (^) 0

I (¿ y i

= j )¿

KNN classifies the test observation

x 0

to the class with the largest probability according to the formula.

Just as in the regression setting, there is not a strong relationship between the training error rate and the test

error rate.

K=3, simple situation with 6

blue observations and 6

orange ones.

Left Right

The test observation tot which a predicted class

label is desired is shown as a black cross. The three

closest points to the test observation are identified,

and it is predicted that the test observation belongs

to the most commonly occurring class (blue).

The KNN decision boundary for this example is

shown in black. The blue grid indicates the region

in which a test observation will be assigned to the

blue class, and the orange grid indicates the region

in which it will be assigned to the orange class.

The Bayes decision

boundary is shown

as a purple dashed

line.

This time we pass only a subset of our data (square). They find a function that is too simpleunderfitting.

Three issues to be addressed

a) Choice of kExtreme options: k=1 vs k=n, this last option considers all the variables in the dataset,

select the most representative one, hence not useful.

b) Distance computationin general, the Euclidian distance is the preferred one.

d ( A , B )

∑

i = 1

n

( X

1 A

− X

1 B

2

Sometimes is convenient to also consider a weight, this in order to assign different importance to the

different features.  if we don’t add it, we are basically assigning the same weight to all the features.

d ( A , B )

∑

i = 1

n

( X

1 A

− X

1 B

2

α i

Units of measure choice

If we have two variables, one expressed in dollars and the other expressed in thousand dollars we will

have that the one expressed in dollars is dominant as the number will be much larger.different

weights according to the unit of the featuresif I change units, I can completely change the outcome of

classification. Of course, this is not ideal.

We need to standardize the value of the variables when we work with algorithms based on distances.

→ z x

x − μ x

σ x

c) Performance measurement and evaluation

Example. Goodness of fit – classification problem

Predicted /Observed Non default Default Sum

Non default 9632 182 9814

Default 35 151 186

Sum 9667 333 10000

Ideal situation

Predicted /Observed Non default Default

Non default 9667 0

Default 0 333

Two alternative indicators for classification

  • Error rate

ER =

- Accuracy

ACC =

ACC = 1 – ER

Those need to be interpretated according to the proportion of the different features, the minimum

level of accuracy is given by the proportion of the biggest class. (see lab next pages)

for the problem seen above the accuracy should be higher than 98,14% (9667/10000).

Reference levels – thresholds:

Accuracy should be at least 40% and the error should be lower than 60%.

A 0,

B 0,

C 0,

D 0,

4.7.6 Lab: classification methods K-Nearest Neighbors

In R we use the knn() function, which is part of the class library.

4 inputs:

  1. A matrix containing the predictors associated with the training data ( train.X )
  2. A matrix containing the predictors associated with the data ( test ) for the which we wish to make

predictors (test.X)

  1. A vector containing the class labels for the training observations ( train.Direction ).
  2. A value for K , the number of nearest neighbors to be used by the classifier.

Smarket data

  • cbind(), short for column bind, to bing the two lags

variables together into two matrices (training and test

set)

  • set.seed(n)  set a random seed before

we apply knn() because if several

observations are tied as nearest

neighbors, then R will randomly break

the tie.

The results using K = 1 are not very good,

since only 50% of the observations are

correctly predicted

The results have improved

slightly. But increasing K further

turns out to provide no further

improvements.

Caravan dataset

Because the KNN classifier predicts the class of a given test observation by identifying the observations that

are nearest to it, the scale of the variables matters

 variables on a larger scale will have a larger effect on the distance between observation, hence on the

KNN classifier. i.e., the variables salary and age where a difference of $1,000 is huge compared to a

difference of 50 years.

To handle this problem, we need to standardize the data so that all variables are given a mean of zero and a

standard deviation of one  scale() function

Column 86 excluded as qualitative purchase

variable

If we use 0.5 as the predicted probability cut-off for the classifier, then we have a problem: only seven of the

test observations are predicted to purchase insurance. Even worse, we are wrong about all of these!

However, we are not required to use a cut-off of 0.5  If we predict a purchase any time the predicted

probability of purchase exceeds 0.25, we get much better results: we predict that 33 people will purchase

insurance, and we are correct for about 33% of these people. This is over five times better than random

guessing!

3.1. Simple Linear Regression.................................................................................................................

It’s a very straightforward approach for predicting a quantitative response Y on the basis of a single predictor

variable X. It assumes that there is approximately a linear relationship between X and Y. Mathematically, we

can write this linear relationship as

Y ≈ β 0

  • β 1

X

β 0 and^

β 1 are two unknown constants or parameters that represent the intercept and slope terms in the linear

model.

We can predict Y (^ y ) on the basis of X = x.

Estimating the coefficients

We must use data to estimate the coefficients, the goal is to find an intercept β 0

and a slope β 1

such that the

resulting line is as close as possible to the n data points. The most common approach involves minimizing

the least squares criterion.

^ y =

^

β 0

^

β 1

x 1

 prediction for Y on the basis of the ith value of X

e 1

= y 1

− ^ y 1 ^ the ith residual

residual sum of squares

RSS = e 1

2

  • e 2

2

  • … + e n

2

=( y 1

^

β 0

^

β 1

x 1

)

2

+( y 2

^

β 0

^

β 1

x 2

)

2

  • … +( y n

^

β 0

^

β 1

x n

)

2

Using some calculus, one can show that the minimizers are

The figure displays the simple linear regression fit to the

Advertising data, where βˆ0 = 7.03 and βˆ1 = 0.0475. In other

words, according to this approximation, an additional $1,000 spent

on TV advertising is associated with selling approximately 47.

additional units of the product.

Assessing the accuracy of the coefficient estimates

We assume that the true relationship between X and Y takes the form Y = f ( X )+ ε for some unknown

function f , where ε is a mean-zero random error term.

If f is to be approximated by a linear function, then we can write this relationship as

y = β 0

  • β 1

X + ε

The error term is a catch-all for what we miss with this simple model: the true relationship is probably not

linear, there may be other variables that cause variation in Y, and there may be measurement error. We

typically assume that the error term is independent of X.

In real applications, we have access to a

set of observations from which we can

compute the least squares line; however,

the population regression line is

unobserved. Fundamentally, the concept

of these two lines is a natural extension

of the standard statistical approach of

using information from a sample to

estimate characteristics of a large

population.

The RSE is an estimate of the standard deviation of ε. Roughly speaking, it is the average amount that the

response will deviate from the true regression line  measure of the lack of fit of the model to the data.

The lower the better the fit.

R

2

statistic.

R

2

=

∑

( y i

− y )

2

− RSS

∑

( y i

− y )

2

RSS

∑ (^

y i

− y (^) )

2

It provides an alternative measure of fit. It measures the proportion of variability in Y that can be explained

using X and so it always takes on a value between 0 and 1 and is independent of the scale of Y 

interpretational advantage over the RSE.

The closer to 1 the better the fit.

Note. Determine what is a good R

2

value depends on the application. I.e., in certain problems in physics we

expect to see an R

2 value that is extremely close to 1, and a substantially smaller R

2 value might indicate a serious

problem with the experiment in which the data were generated.

R

2 is 0.61: just under two-thirds of the variability in sales is explained by a linear

regression on TV.

RSE is 3.26: actual sales in each market deviate from the true regression line by

approximately 3,260 units, on average.

Analysis of residuals rmd

Multiple R-squared, measures how well our function is able to predict our expected variables, if the goal is

not prediction this value is not important. Don’t use this as a measure of reliability of our estimates!

Plots

  • Residuals vs fitted  mean should be around 0
  • Q-Q residuals  tells us whether the residuals are normally distributed, points should be more or less

aligned to the dashed line. In the plot bellow not normally distributed as there are 2 clear deviations.

This is important just for the prediction intervals.

- Scale-Location  when there is almost homoskedasticity the line should be flat  this issue can be

usually solved easily by log transformation. The point estimations are still reliable, while the standard

errors aren’t, hence is not possible to assess the significance.

- Residuals vs Leverage  allows us to find whether there are possible outliers, the leverage is a measure

of the influence of the outlier (high leverage – high effect on the predictions and estimates).

In order to quantify an observation’s leverage, we compute the leverage statistic. A large value of this

statistic indicates an observation with high leverage

Cook’s distance : when the cook’s distance is larger than 1, we have an outlier

(in the upper left corner in this case)

Not always removing the outlier is a wise solution

as it may be a useful information

In order to see the same relation seen in the

Residual vs Fitted plot we can use the following

plots to find out for which variable we have a

deviationalso formal “report” suggesting

which variable should be transformed.

After the transformation of LivingArea, LandValue and LotSize thigs seem to be better

3.2 Multiple Linear Regression................................................................................................................

Extend the simple linear regression model so that

it can directly accommodate multiple predictors.

suppose that we have p distinct predictors

y = β 0

  • β 1

X

1

  • … + β p

x p

  • ε

We interpret βj as the average effect on Y of a one unit increase in Xj, holding all other predictors fixed.

Estimating the regression coefficients

Given estimates

^

β 0

^

β 1

^

β p

, we can make predictions using the formula

^

Y =

^

β 0

^

β 1

, X

1

^

β p

x p

The parameters are estimated using the same least squares approach seen for simple linear regression.

Unlike the simple linear regression estimates, the multiple regression coefficient estimates have somewhat

complicated forms that are most easily represented using matrix algebra.

Using the formula

^

Y =

^

β 0

^

β 1

, X

1

^

β p

x p

there are three sorts of uncertainty associated with this

prediction.

  1. The

^

Y =

^

β 0

^

β 1

, X

1

^

β p

x p

least square plane is only an estimate for the true population regression

plane f^ (^ X^ )= β 0 +^ β 1 X 1 +^ … +^ β^ p x^ p.

The inaccuracy in the coefficient estimates is related to the reducible error , we can compute a

confidence interval in order to determine how close

^

Y will be to f ( X ).

  1. Of course, in practice assuming a linear model for f ( X ) is almost always an approximation of reality, so

there is an additional source of potentially reducible error which we call model bias.

  1. Even if we knew f^ (^ X^ )^ the response value cannot be predicted perfectly because of the random error ε in

the model. How much will Y vary from

^

Y? We use prediction intervals to answer this question.

3.3 Other Considerations in the Regression Model..................................................................................

Qualitative predictors

Predictors with only two levels

If a qualitative predictor (also known as a factor) only has two levels, or possible values, then we simply

create an indicator or dummy variable.

For example, based on the variable own variable, we can create a

new variable that takes the form

and use this variable as a predictor in the regression equation.

This results in the model

Now β 0 can be interpreted as the average credit card balance among those who do not own, β 0 + β 1 as the average

credit card balance among those who do own their house, and β 1 as the average difference in credit card balance

between owners and non-owners.

More than two levels

In this situation, we can create additional dummy variables.

I.e.,

In case of dummy variables

w = 3 −1,2 female +0,8 education + …

female = 1 female, female = 0 malefemale earn (w) 1,2 times less than males.

w = β 0

− β 1

female + β 2

education + … + ε

The effect of education is the same for male and female

What if we want to have one β for female and one for malesβ 2

=( α 0

  • α 1

fem )

w = β 0

− β 1

female +( α 0

  • α 1

fem ) education + … + ε

Interaction term

Is one way of extending a model. The interaction term is constructed by computing the product of X 1 and X 2.

This results in the model

Hierarchical principle

If the interaction between X 1 and X 2 seems important, then we should include both X 1 and X 2 in the model

even if their coefficient estimates have large p-values. The rationale for this principle is that if X 1 ×X 2 is

related to the response, then whether or not the coefficients of X 1 or X 2 are exactly zero is of little interest.

Also X 1 ×X 2 is typically correlated with X 1 and X 2 , and so leaving them out tends to alter the meaning of the

interaction.

3.3.3 Potential Problems

1.) Linearity in parameters

The linear regression model assumes that there is a straight-line relation- ship between the predictors and

the response. If the true relationship is far from linear, then virtually all of the conclusions that we draw

from the fit are suspect. In addition, the prediction accuracy of the model can be significantly reduced.

linear in βs. No: (^) β n

2

yes: (^) y = β 0

  • β 1

x 1

2

and also y = β 0

  • β 1

x 1

x 2

Residual plots are a useful graphical tool for identifying non-linearity.

FIGURE 3.9. Plots of residuals versus predicted (or fitted)

values for the Auto data set. In each plot, the red line is a

smooth fit to the residuals, intended to make it easier to

identify a trend. Left: A linear regression of mpg on

horsepower. A strong pattern in the residuals indicates non-

linearity in the data. Right: A linear regression of mpg on

horsepower and horsepower2. There is little pattern in the

residuals.

2.) Randomness: random sample  very important! P-value reliable only if this is respected. Crucial for

all the methos we have seen/will see.

Why might correlations among the error terms occur? Such correlations frequently occur in the context

of time series data, which consists of observations for which measurements are obtained at discrete

points in time. In many cases, observations that are obtained at adjacent time points will have positively

correlated errors.

3.) No collinearityi.e., could happen if we include the same variable twice or explanatory variables that

are highly correlated.

There are ways to avoid this problem, but first it has to be reelevated  check correlation matrix.