Docsity

BIG DATA AND ANALYTICS - complete notes, Appunti di Analisi Dei Dati

Toggle sidebar
bg1
Statistics is the science of learning from data, and of measuring, controlling, and communicating uncertainty; and it
thereby provides the navigation essential for controlling the course of scientific and societal advances.
Statistics draws population inferences from a sample, and machine learning finds generalizable predictive
patterns.
Aspect
Statistics
Machine Learning
Main goal
Understand relationships and make
inferences
Make accurate predictions on new data
Question it
asks
Why does Y depend on X?
How well can we predict Y from X?
Example
How much does education increase
income, on average?
Inference and ML are complementary in pointing us to biologically meaningful conclusions.
Statistical learning (=machine learning) refers to a vast set of tools for understanding data.
These tools can be:
Supervised Statistical Learning involves building a statistical model for predicting, or estimating, an output
based on one or more inputs
-
In a typical scenario, we have:
1. an outcome measurement, usually quantitative (like the level of prostate specific antigen) or categorical (such
as heart attack/no heart attack), that we wish to predict;
2. a set of features that will be the basis of the prediction (such as diet and clinical measurements);
3. a training set of data, in which we observe the outcome and feature measurements for a set of objects (such
as people).
Using this data we build a prediction model, or learner, which will enable us to predict the outcome for new
unseen objects. A good learner is one that accurately predicts such an outcome.
Unsupervised Statistical Learning there is no outcome measure, and the goal is to describe the associations
and patterns among a set of input measures. (ex: cluster analysis: assess whether observations fall into distinct
groups)
-
We only have (X1,X2,…,Xn) and try to uncover structure without a known target.
What we will cover:
INTRODUCTION
Wednesday, November 12, 2025
16:21
FIRST PARTIAL Page 1
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
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Anteprima parziale del testo

Scarica BIG DATA AND ANALYTICS - complete notes e più Appunti in PDF di Analisi Dei Dati solo su Docsity!

Statistics is the science of learning from data, and of measuring, controlling, and communicating uncertainty; and it

thereby provides the navigation essential for controlling the course of scientific and societal advances.

Statistics draws population inferences from a sample, and machine learning finds generalizable predictive

patterns.

Aspect Statistics Machine Learning

Main goal Understand relationships and make

inferences

Make accurate predictions on new data

Question it

asks

Why does Y depend on X? How well can we predict Y from X?

Example How much does education increase

income, on average?

Given someone’s education and experience, what will

their income likely be?

Inference and ML are complementary in pointing us to biologically meaningful conclusions.

Statistical learning (=machine learning) refers to a vast set of tools for understanding data.

These tools can be:

Supervised Statistical Learning involves building a statistical model for predicting, or estimating, an output

based on one or more inputs

In a typical scenario, we have:

  1. an outcome measurement, usually quantitative (like the level of prostate specific antigen) or categorical (such

as heart attack/no heart attack), that we wish to predict;

  1. a set of features that will be the basis of the prediction (such as diet and clinical measurements);
  2. a training set of data, in which we observe the outcome and feature measurements for a set of objects (such

as people).

Using this data we build a prediction model, or learner , which will enable us to predict the outcome for new

unseen objects. A good learner is one that accurately predicts such an outcome.

Unsupervised Statistical Learning there is no outcome measure, and the goal is to describe the associations

and patterns among a set of input measures. (ex: cluster analysis: assess whether observations fall into distinct

groups)

We only have (X1,X2,…,Xn) and try to uncover structure without a known target.

What we will cover:

INTRODUCTION

Wednesday, November 12, 2025 16:

STEPS:

  • Data warehouse--> large and unstructured data
  • Data mining--> translate data to information (includes also data preparation--> from raw to structured)
  • Data science--> from information to knowledge (make it actionable to provide value)

Data analytics , which includes

○ customer segmentation (profile clusters) and retention (churn analysis: which customers are likely to drop)

○ Credit scoring--> default predictions

○ Market baskets analysis--> which products are likely to be purchased together

○ e-commerce--> cookies

○ Text mining--> social media: what are people thinking and talking about; sentiment analysis

○ DNA data mining--> gene therapy

The steps in data analytics are:

  1. Business understanding--> clearly know the KPI (what you want to maximize)

Data understanding --> depends on the company: data culture, data acquisition, data merge, data

preparation

  1. Data preparation
  2. Data modelling (our focus)

Model validation/evaluation--> provide valuable knowledge about the general patterns-->

deployment(selling the results obtained)

Data science is the art of extracting knowledge from data, and it revolves around statistics.

REMEMBER:

Variables can be categorized as

  • Quantitative--> numerical values. Problems with quantitative variables are called regression problems.

Qualitative--> fall into one of K classes or categories. Problems with categorical variables are called

classification problems.

However, the distinction is not always crisp.

FEATURES MODELS TYPE USED

FOR

Interpretation / Bias /

simplicity

Prediction / Variance /

Complexity

Linear model Parametric--> constant parameters across the

whole function

Inference

Prediction

Polynomial model

Local/non-parametric

model

Non parametric

Decision trees

Ensemble learning

Neural newtork

This table summarizes the BIAS-VARIANCE TRADE OFF, meaning that for a model if Variance decreases, Bias

increases and viceversa.

Our goal is to find the optimal balance between the two for the problem at hand, so that we can minimize the reudcible

error.

How do we estimate f?

We will always assume that we have observed a set of n different data points. These observations are called the training

data because we will use these observations to train, or teach, our method how to estimate f.

Our goal is to apply a statistical learning method to the training data in order to estimate the unknown function f ⇒ we

want to f ind a function such that Y ≈ for any observation (X,Y).

Parametric methods:

Parametric methods involve a two-step model-based approach:

First, we make an assumption on the functional form (linear, polynomial). This greatly simplifies the problem, so

that we now only need to estimate the specific coefficients.

  1. After the selection of model, we need a procedure that uses the training data to fit or train the model (ex: OLS)

The potential disadvantage of a parametric approach is that the model we choose will usually not match the true

unknown f, thus if the choosen model is too far form the true f, our estimate will be poor.

To address this problem we may choose a more flexible model. However, these more complex methods can lead to

overfitting data, meaning that we follow the errors/noise, too closely.

Non- Parametric methods:

Nonparametric methods do not make explicit assumptions about the functional form of f. Instead they seek an

estimate of f that gets as close to the data points as possible without being too rough or wiggly.

By avoiding the assumption of a particular form of f, they have the potential to accurately fit a wider range of possible

shapes for f , so they avoid the danger of a resulting that does not fit the data well. However, a very large number of

observations (more than parametric approach) is required.

Why would we ever choose to use a more restrictive method instead of a very flexible approach?

  • If we only are interested in inference , then restrictive nodels are much more interpretable

Even if we are only interested in prediction , overfitting is a great risk in flexible models--> undesirable situation

because the fit obtained will not yield accurate estimates of the response on new observations that were not part of

the original training data set.

Why is it necessary to introduce so many different statistical learning approaches, rather than just a single best method?

There is no free lunch in statistics --> no one method dominates all others over all possible data sets. On a particular

data set, one specific method may work best, but some other methods may work better on a similar but different data set.

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

Element Interpretability Flexibility

True f Simple--> linear Complex--> non-linear

Small Large

n(number of units) Small Large

p/n(number of variables) Large (variable selection) Small

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.

In the regression setting, the most commonly-used measure is the mean squared error (MSE), given by

The MSE will be small if the predicted responses are very close to the true responses, and will be large if for some of

the observations, the predicted and true responses differ substantially.

It is computed using the training data, used to fit the model, thus it is called traning MSE

However, we are interested in knowing whether our regression works in a previosuly unseen test observation not used

to train the statistical learning method.

Thus, we want to choose the method that gives the lowest test MSE, as opposed to the lowest training MSE, as

selecting a model based only on the lowest Training MSE doesn't guarantee the best performance on new data.

Average squared prediction error →

  • How can we select a method that minimizes the test MSE?

In some settings, we may have a test data set available and therefore we can select the learning method for which the

test MSE is smallest.

  • But what if no test observations are available?

Selecting a statistical learning method that minimizes the training MSE provides no guarantee that such method will

also have the lowest test MSE.

Furthermore, as model flexibility increases training MSE will de crease, but the test MSE may not. When a method

yields a small training MSE but a large test MSE, we are said to be overfitting the data.

Overfitting happens because 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.

--> An overfit model will have a very low Training MSE (because it perfectly fits the training data, noise and all) but

a very high Test MSE (because the patterns it learned from the noise don't exist in the new, unseen test data).

Note that 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.

Left: Data simulated from f, shown in black. Three estimates of f are shown: the linear regression line (orange

curve), and two smoothing spline f its (blue and green curves).

Right: Training MSE (grey curve), test MSE (red curve), and minimum possible test MSE over all methods

(dashed line). Squares represent the training and test MSEs for the three fits shown in the left-hand panel.

In practice, one important method to estimate the test MSE is cross-validation.

The MSE is the empirical measure of error

calculated on a specific dataset.

Test MSE

Training MSE

Threshold -->

Best (lowest)

NOTE: test MSE

has a U-shape

In the absence of a very large designated test set that can be used to directly estimate the test error rate, a number

of techniques can be used to estimate this quantity using the available training data:

Some methods make a mathematical adjustment to the training error rate in order to estimate the test error

rate. (Ex: R^2 and adjusted R^2). (chap 6)

We instead consider a class of methods that estimate the test error rate by holding out a subset of the

training observations from the fitting process, and then applying the statistical learning method to those

held out observations. Ex: Validation set approach

Validation set approach

The validation set approach is a very simple strategy to estimate the test error associated with fitting a particular

statistical learning method on a set of observations.

It involves randomly dividing the available set of observations into two parts

  • training set
  • validation set or hold-out set.

The model is fit on the training set, and the fitted model is used to predict the responses for the observations in the

validation set. The resulting validation set error rate provides an estimate of the test error rate.

The validation set approach is conceptually simple and is easy to implement.

But it has two potential drawbacks:

The validation estimate of the test error rate can be highly variable , depending on precisely which

observations are included in the training set and which observations are included in the validation set;

In the validation approach, only a subset of the observations those that are included in the training set

rather than in the validation set- are used to fit the model. Since statistical methods tend to perform

worse when trained on fewer observations, this suggests that the validation set error rate may tend to

overestimate the test error rate for the model fit on the entire data set.

In the coming subsections, we will present cross-validation, a refinement of the validation set approach that

addresses these two issues.

If we are in a data-rich situation, the best approach for both model selection and model assessment is to randomly

divide the dataset into three parts: a training set, a validation set, and a test set:

  • Training set used to fit the models

Validation set used to estimate prediction error for model selection (compare models and choose the best

one)

  • Test set is used for assessment of the generalization error of the final chosen model.

Ideally, the test set should be kept in a “vault”, and be brought out only at the end of the data analysis.

In fact, if we use the test-set repeatedly (→ choosing the model with smallest test-set error), then the test set error

of the final chosen model will underestimate the true test error, sometimes substantially.

A typical split might be:

  • 50% for training,
  • 25% each for validation and testing.

Another option is to resort to resampling methods.

  • Cross-validation--> without replacement
  • Bootstrap --> with replacement

The statistical learning method is f it

on the training set, and its

performance is evaluated on the

validation set.

RESAMPLING METHODS

Saturday, November 22, 2025 09:

RESAMPLING METHODS

Resampling methods are an indispensable tool in modern statistics. They involve repeatedly drawing samples from a

training set and refitting a model of interest on each sample in order to obtain addi tional information about the fitted

model.

They can be:

  • Without reintroduction--> a sample may only belong to a single fold
  • With reintroduction--> the same sample can be repeatedly used in subsequent subsamples

For example, in order to estimate the variability of a linear regression f it, we can repeatedly draw different samples

from the training data, f it a linear regression to each new sample, and then examine the extent to which the resulting

fits differ.

Such an approach may allow us to obtain information that would not be available from fitting the model only once

using the original training sample.

They can be computationally expensive, but generally not prohibitive (thanks to technology).

CROSS-VALIDATION

It is a resampling method that can be used to:

  • Model selection--> select the appropriate level of flexibility

Model assessment--> Estimate the test error associated with a given statistical learning method to evaluate its

performance

There are two types of cross-validation: Leave-One-Out CV and K-fold CV.

Leave-one-out cross validation (LOOCV)

It is closely related to the validation set approach. Similarly, it involves splitting the set of observations into two parts,

but not two subsets of comparable size:

  • Single observation (x1, y1)--> for the validation set
  • All remaining observations--> for the training set

The statistical learning method is fit on the n − 1 training observations, and a prediction ˆy1 is made for the excluded

observation, using its value x1. Since (x1,y1) was not used in the fitting process,

Provides an approximaately unbiased estimate for the test error.

Even though MSE1 is unbiased for the test error, it is a poor estimate because it is highly variable, since it is

based upon a single observation, (x1,y1).

But we can repeat this approach n times, producing n squared errors.

The LOOCV estimate for the test MSE is the average of these n test error estimates:

Advantages compared to validation set approach:

LOOCV has far less bias--> the learning

method is fit using n-1 observation compared to

around n/2 observations. Thus it does not

overestimate the test erro rate as much.

Performing LOOCV multiple times will always

yield the same results : there is no randomness

in the training/validation set splits.

Training samples are almost completely overlapped but

1 observation

CROSS-VALIDATION ON CLASSIFICATION PROBLEMS

As we have already said, when Y is qualitative, rather than using MSE to quantify test error, we use the number of

misclassified observations.

For instance, in the classification setting, the LOOCV error rate takes the form

The k-fold CV and validation set error rates are defined analogously.

Correct way to carry out cross-validation:

  1. Divide the samples into K cross-validation folds (groups).

For each fold k = 1,2,...,K

Find a subset of “good” predictors that show fairly strong (univariate) correlation with the class labels,

using all of the samples except those in fold k.

a.

Using just this subset of predictors, build a multivariate classifier, using all of the samples except those

in fold k.

b.

c. Use the classifier to predict the class labels for the samples in fold k.

The error estimates from step 2(c) are then accumulated over all K folds, to produce the cross-validation estimate of

prediction error.

BOOTSTRAP

The bootstrap is data-based simulation method for statistical inference, which can be used to produce inferences.

It is used when the underlying distribution is unknown or impossible to derive, thus intended specifically for

Big data.

It is a recent method (70s), which is now quite used for several inferencial problems, like point estimate, interval

estimate and hypothesis testing.

Specifically, the bootstrap is a widely applicable and extremely powerful statistical tool that can be used to quantify

the uncertainty associated with a given estimator or statistical learning method.

For example, the bootstrap can be used to estimate the standard errors of the coefficients from a linear regression fit.

The power of the bootstrap lies in the fact that it can be easily applied to a wide range of statistical learning

methods, including some for which a measure of variability is otherwise difficult to obtain and is not automatically

output by statistical software.

How it works:

The basic idea is to randomly draw datasets with

replacement from the training data, each sample the same

size as the original training set. Then we refit the model to

each of the bootstrap datasets, and examine the behavior

of the fits over the B replications.

  1. Z = (z1,z2,...,zN) is your original dataset of size N.

From this original dataset, you draw B new

samples , each of size N, with replacement.

For each bootstrap sample you compute your

statistic of interest S(Z)

Performing a bootstrap analysis in R is quite easy:

  1. First, we must create a function that computes the statistic of in terest, say the correlation coefficient ρ.

Second, we use the boot() function, which is part of the boot library, to perform the bootstrap by repeatedly

sampling observations from the data set with replacement.

The function then outputs the estimate for ρ based on the selected observations and an estimate of its standard

error.

The bootstrap approach can be used to assess the variability of the coefficient estimates and predictions from a

statistical learning method.

## The Validation Set Approach

library(ISLR2)

set.seed(1)

train <- sample(392, 196)

lm.fit <- lm(mpg ~ horsepower, data = Auto, subset = train)

Loads the library which contains the dataset.

The auto datatset has 392 rows. This comman randomly picks 196 numbers to serve as the training set (half dataset).

We now fit a standard linear model, predicting mpg (miles per gallon) using horsepower--> We take the data from the

datasets auto, but we fit the model only using the trainining set.

attach(Auto)

Convenience function that allows us to reference columns(like mpg) without typing auto$mpg

mean((mpg - predict(lm.fit, Auto))[-train]^2)

This outputs the Mean Squared Error (MSE) of the validation set.

  • predict(lm.fit, Auto): Uses the model (lm.fit) to predict mpg for all 392 cars in the dataset.
  • mpg - ...: Calculates the residuals (Actual MPG minus Predicted MPG).

[-train]: This creates the Validation Set. The minus sign means "exclude these rows." We are selecting only the

rows that were not used to train the model.

^2: Squares the errors (to prevent negatives canceling out positives).

  • mean(...): Calculates the average.

MSE= 23.

lm.fit2 <- lm(mpg ~ poly(horsepower, 2), data = Auto, subset = train)

mean((mpg - predict(lm.fit2, Auto))[-train]^2)

We compute the same thing different times but with some differences. In this case, we create a linear degression

which uses both horsepower and horsepower^2. This lowers the MSE to MSE=18.71.

lm.fit3 <- lm(mpg ~ poly(horsepower, 3), data = Auto,

subset = train)

mean((mpg - predict(lm.fit3, Auto))[-train]^2)

In this case, we add also the cubic power of horsepower, obtaining a MSE of 18.79 (slightly over).

So we can conclude that #2 is the optimal mode l as it has the lowest MSE.

However, the validation set is highly variable. In fact, since we are training the model on half the data, the error rate

changes significantly depending on which cars end up in the traning set. This can be proven by repeating the previous

steps using random seeds--> not always #2 is the best model.

set.seed(round(runif(1,0,1000)))

train <- sample(392, 196)

lm.fit <- lm(mpg ~ horsepower, subset = train)

mean((mpg - predict(lm.fit, Auto))[-train]^2)

lm.fit2 <- lm(mpg ~ poly(horsepower, 2), data = Auto,

subset = train)

mean((mpg - predict(lm.fit2, Auto))[-train]^2)

lm.fit3 <- lm(mpg ~ poly(horsepower, 3), data = Auto, subset = train)

mean((mpg - predict(lm.fit3, Auto))[-train]^2)

# Lab: Cross-Validation and the Bootstrap

Saturday, November 22, 2025 16:

## The Bootstrap --> Bootstrapping allows us to estimate the uncertainty (Standard Error) of any statistic by

resampling the data with replacement.

### Estimating the Accuracy of a Linear Regression Model

boot.fn <- function(data, index)

coef(lm(mpg ~ horsepower, data = data, subset = index))

First we create a function which creates a linear model on a resampled subset (subset = index) and extracts the

coefficients (Intercept and Slope) using coef().

boot.fn(Auto, 1:392)

We do this on the whole sample to verify the function works.

set.seed(1)

boot.fn(Auto, sample(392, 392, replace = T))

boot.fn(Auto, sample(392, 392, replace = T))

boot.fn(Auto, sample(392, 392, replace = T))

If I set the seed and and resample with replace=T, i get different samples with replacement. This is the bootstrap

logic, but we do not need to do this manually.

boot(Auto, boot.fn, 1000)

summary(lm(mpg ~ horsepower, data = Auto))$coef - -> extracts from the total summary of the linear regression the

coefficients to compare them with bootstrap

Runs 1000 bootstrap resamples , applying boot.fn to each.

The output:

How can I compare with bootstrap the first and second order regression(with horsepower^2)?

I change the inputs in boot.fn.

boot.fn <- function(data, index)

coef(

lm(mpg ~ horsepower + I(horsepower^2),

data = data, subset = index)

set.seed(1)

boot(Auto, boot.fn, 1000)

summary(lm(mpg ~ horsepower + I(horsepower^2), data = Auto))$coef

plot(lm(mpg ~ horsepower + I(horsepower^2), data = Auto))

plot(lm(mpg ~ horsepower, data = Auto))

plot(horsepower,mpg,data=Auto) --> simple plot of the total data. Even just with this simple plot we can see that the

relationship is not linear, there is an inverse parabola.

If you divide the first with the third the value is larger

than 10, this means that the p-value is almost zero.

Thus, the second coefficient is very statistically

significant. Thus, we must consider it. This also implies

that the first model is wrong.

This can also be seen by plotting the regression of the

first and second model.

Where:

  • 39 is the intercept
    • 0.15 is the slope of the first coefficient (horsepower)

The bias measures the distance from the bootstrap to the

standard ols estimate

Unsupervised learning

The unsupervised learning is a set of statistical tools intended for the setting in which we have only a set of features X1,

X2,... , Xp measured on n observations.

We are not interested in prediction, because we do not have an associated response variable Y.

The goal is to discover interesting things about the measurements on X1, X2, … , Xp.

For example:

  • Visaluzation--> Is there an informative way to visualize the data? (if p is too large)
  • Clustering --> Can we discover subgroups among the variables or among the observations?

So dimension reduction can refer to:

Variables --> from X(np) to Z(nr), Reducing the columns (features) to r new features (like Principal

Components). r < p.

Observations --> from X(np) to C(gp), Reducing the rows (observations) by dividing them into g groups (like

Clustering). g < n.

How do we choose r and g? we cannot apply resampling methods because Z and C do not exist. We need to develop

internal validation strategies to assess the perfect numbers. These are also called reconstruction techniques.

Unsupervised learning refers to a diverse set of techniques for answering questions like these.

Unsupervised learning is often performed as part of an exploratory data analysis--> r and g are arbitrary (based on human

judgement). Because the initial choice is arbitrary, we must rely on internal validation strategies to assess the perfect

numbers. It can be hard to assess the results obtained from unsupervised learning methods, since there is no universally

accepted mechanism for performing cross-validation or validating results on an independent data set.

In unsupervised learning, there is no way to check our work because we don’t know the true answer Y - the problem

is unsupervised.

PRINCIPAL COMPONENT ANALYSIS (variables)

In the context of principal component regression--> It takes the entire set of correlated variables and transforms them

into a new set of uncorrelated variables , called principal components. This is useful because often the first few

principal components explain most of the variability in the original data.

This reduces dimensionality, multicollinearity, and overfitting.

Principal component analysis (PCA) refers to the process by which principal components are computed, and the

subsequent use of these components in understanding the data(and visualizing it).

PCA is an unsupervised approach, since it involves only a set of features X1, X2,... , Xp, and no associated response Y.

PCA also serves as a tool for data visualization (visualization of the observations or visualization of the variables).

When principal component is used for regression we do have a Y, that is our model. Thus, we can select r by cross-

validation. (Chap 6)

PCA for data visualization

Suppose that we wish to visualize n observations with measurements on a set of p features, X1, X2,... , Xp, as part of

an exploratory data analysis.

We could do this by examining two-dimensional scatterplots of the data, each of which contains the n observations’

measurements on two of the features. However, there are = p(p − 1)/2 such scatterplots (Number of combinations

of p elements taken k by k.). If p is large, then it is unfeasible to look at all of them. Moreover, most likely none of

them will be informative since they each contain just a small fraction of the total information present in the data set.

Clearly, a better method is required to visualize the n observations when p is large.

In particular, we would like to find a low-dimensional representation of the data that captures as much of the

information as possible.

DIMENSION REDUCTION METHODS

Sunday, November 23, 2025 09:

The Covariance Matrix ∑

The Covariance Matrix is the engine room of PCA. It's a square table (matrix) that summarizes the variance and

relationships between all your original features.

Imagine you have two features, Weight (X1) and Height (X2).

The Covariance Matrix for these two features looks like this:

  • Diagonal Entries (Variance): These tell you how much a single feature spreads out on its own.

Off-Diagonal Entries (Covariance): These tell you how two features change together.

○ Positive Covariance (like for Weight and Height) means they increase together.

○ Zero Covariance means they have no linear relationship.

PCA needs to know the total "shape" and "spread" of your data. The Covariance Matrix is the best mathematical

description of that shape, which is why PCA must calculate it first.

The Eigenvector φ

The Eigenvector is the direction in your data space that captures the most information. In PCA, the eigenvectors are the

Principal Component Loadings.

The eigenvector is the vector (an arrow pointing from the origin) that defines the direction.

For the first principal component, the eigenvector points in the direction of maximum variance.

9

For the second principal component, the eigenvector points in the direction of the second-largest variance and is

perpendicular to the first one.

The eigenvector defines the weights (or loadings) for the linear combination. It tells you how much to multiply each

original feature by to create the new principal component.

The Eigenvalue λ

The Eigenvalue is a scalar (a single number) that is intrinsically linked to its corresponding eigenvector.

If the eigenvector is the direction (the arrow), the eigenvalue is the length of that arrow as it defines the spread of the

data.

In PCA: The eigenvalue is the variance (spread) of the data when projected onto the eigenvector

The Purpose: Eigenvalues tell you how important each principal component is. We rank the components by the size of

their eigenvalues and then use them for the Proportion of Variance Explained (PVE) to decide how many components

to keep.

How many principal components to use?

The question is inherently ill-defined, and will depend on the specific area of application and the specific data set.

In practice, we tend to look at the first few principal components in order to find interesting patterns in the data. If no

interesting patterns are found in the first few principal components, then further principal components are unlikely to

be of interest.

Conversely, if the first few principal components are interesting, then we typically continue to look at subsequent

principal components until no further interesting patterns are found.

Dimension reduction methods

Subset selection and regularization methods control variance in two different ways:

  • either by using a subset of the original variables, (principal component regression / partial least squares)
  • or by shrinking their coefficients toward zero (lasso/ridge)

All of these methods are defined using the original predictors, X1, X2, ..., Xp.

We now explore a class of approaches that transform the predictors and then fit a least squares model using the

transformed variables. We will refer to these techniques as dimension reduction methods.

Let Z1,Z2, ..., ZM represent M < p linear combinations of our original p predictors. That is,

for some constants ϕ1m, ϕ2m,..., ϕpm | m = 1,...,M.

We can then fit the linear regression model

using least squares.

If the constants ϕ1m, ϕ2m,..., ϕpm are chosen wisely, then such dimension reduction approaches can often outperform

least squares regression.

The term dimension reduction comes from the fact that this approach reduces the problem of estimating the p + 1

coefficien ts β0,β1,...,βp to the simpler problem of estimating the M + 1 coefficients ,..., , where M < p.

The risk is that if M is too small, is biased (too simple), consequenly y^ is predicted badly (bias-variance trade off).

However, in situations where p is large relative to n, selecting a value of M ≪ p can significantly reduce the variance of

the fitted coefficients.

How to choose ’s? --> the loaders/weights of each original variable.

PCA chooses to maximize variance in X; PLS chooses to maximize covariance between X and Y.

When faced with a large set of correlated variables, principal components allow us to summarize this set with a smaller

number of representative variables that collectively explain most of the variability in the original set.

The principal component directions can be presented as directions in feature space along which data are highly variable.

To perform principal component regression, we simply use principal components as predictors in a regression model in

place of the original larger set of variables.

As we have said Principal Component Analysis (PCA) is an unsupervised approach, since it involves only a set of

features X1, X2, ..., Xp, and no associated response Y. PCA finds a low-dimensional representation of a data set that con

tains as much as possible of the variation. The idea is that each of the n observations lives in p-dimensional space, but

not all of these dimensions are equally interesting. Each dimension found by PCA is a linear combination of the p

features.

How are principal components found?

The first principal component of a set of features X1,X2,...,Xp is the normalized linear combination of the features

= + +···+ , that has the largest variance.

By normalized, we mean that

2

We refer to the elements 11,..., p1 as the loadings of the first principal loading component; together, the loadings make

up the principal component loading vector , 1 =( 11, 21, …, φp1)T.

We constrain the loadings so that their sum of squares is equal to one, since otherwise setting these elements to be

arbitrarily large in absolute value could result in an arbitrarily large variance.

This means that to find the direction with the largest variance , we simply look for the largest eigenvalue λ1 of the

covariance matrix, and its corresponding eigenvector gives us the loading vector

.

The loading vector ϕ1 with elements ϕ11,ϕ21,...,ϕp1 defines a direction in feature space along which the data vary the

most. If we project the n data points x1,...,xn onto this direction, the projected values are the principal component

scores z11,...,zn1 themselves.

After the first principal component Z1 of the features has been determined, we can find the second principal

component Z2.

The second principal component is the linear combination of X1,... , Xp that has maximal variance out of all linear

combinations that are orthogonal to Z1, therefore

This is the dot product (internal product of the two), it can be discribed as a measure of how much two vectors point

in the same direction. When the result is zero, it means they share absolutely no common direction.

In other words, the constrained maximization problem now consists in maximizing, with respect to ϕ2, the following

function:

When solving a constrained optimization problem using Lagrange Multipliers , a separate λ term is introduced for

every single constraint.

λ2 is associated with the Unit Norm constraint ϕ

2

T

  • ϕ

λ3 is associated with the Orthogonality constraint ϕ

2

T

  • ϕ

We take the first derivative w.r.t. ϕ2 and set it equal to zero:

By multiplying both sides by ϕ we obtain

As ϕ is an eigenvector of Σ, ϕ Σ = λ1ϕ. ⇒ λ3 = 0

The problem we need to solve is then Σϕ λ ϕ = 0 or, equivalently, Σϕ = λ ϕ.

λ2 is an eigenvalue of Σ and ϕ2 is the corresponding eigenvector. As we are looking for the linear combination having

the largest variance not accounted for by Z1 we will choose the second largest eigenvalue of Σ and the corresponding

eigenvalue.

Z2 = X is the second principal component.

The above process can be continued for all principal components. We will derive as many principal components as

the obser ved variables.

In general, the kth Principal components of X is Zk = Xϕk, and V(Zk) = λk where λk is the kth largest eigenvalue of

Σ, and ϕk is the corresponding eigenvector.

It is possible to show that the first and the second principal components are uncorrelated. The same holds for any pair

of principal components.

The goal of the derivation is to show that lambda

must equal zero, which means the orthogonality

constraint is naturally satisfied by the eigenvector

solution.

PRINCIPAL COMPONENTS FROM SVD (Singular Value Decomposition)

Alternatively, principal components can be found by using the singular value decomposition of matrix X:

Here

  • U is an n×p orthogonal matrix ( ) whose columns uj are called the left singular vectors;
  • V is a p×p orthogonal matrix ( ) with columns vj called the right singular vectors;
  • D is a p×p diagonal matrix, with diagonal elements d1 ≥ d2 ≥... ≥ dp ≥0 known as the singular values.

The columns of Z = UD are called the principal components of X.

Three criteria to select the number of principal components=M (internal validation)

  1. Cumulated proportion of variance
  2. Kaiser rule (if the scale of the variables is too different, you standardize them)
  3. Elbow methodd

PRINCIPAL COMPONENTS REGRESSION APPROACH

The principal components regression (PCR) approach nvolves con structing the first M principal components,

Z1,...,ZM, and then using these components as the predictors in a linear regression model that is fit using least squares.

The key idea is that often a small number of principal components suffice to explain most of the variability in

the data , as well as the relationship with the response. In other words, we assume that the directions in which

X1, ...,Xp show the most variation are also associated with Y.

While this assumption is not guaranteed to be true, it often turns out to be a reasonable enough approximation to give

good results.

If the assumption underlying PCR holds, then fitting a least squares model to Z1,...,ZM will lead to better results than

fitting a least squares model to X1,...,Xp, since most or all of the information in the data that relates to the response is

contained in Z1,...,ZM, and by estimating only M ≪ p coefficients we can mitigate overfitting.

As more principal components are used in the regression model, the bias decreases, but the variance increases.

When M = p then PCRegression amounts simply to a least squares fit using all of the original predictors.

We note that even though PCR provides a simple way to perform regression using M < p predictors, it is not a feature

selection method. In PCR, the number of principal components, M, is typically chosen by cross-validation.

When performing PCR, it is generally recommended to standardize each predictor, prior to generating the principal

components. This standardization ensures that all variables are on the same scale. In the absence of standardization, the

high-variance variables will tend to play a larger role in the principal components obtained, and the scale on which the

variables are measured will ultimately have an effect on the final PCR model.

However, if the variables are all measured in the same units (say, kilograms, or inches), then one might choose

not to standardize them.

THE PARTIAL LEAST SQUARES APPROACH (supervised alternative to PCR)

The PCR approach identifies the linear combinations of the predictors that enter the reduced model (i.e., the principal

components of the n ×p matrix of predictors X) in an unsupervised way, because the response variable Y does not play

any role in identifying those directions.

Cross-validation may in fact be used to decide the number of components to enter, but not the directions themselves.

As a consequence, PCR is effective as long as the directions best explaining the variance of the Xs also are the

directions best explaining the co-variation of Y and the Xs.

PCR is effective as long as

However, this assumption is not guaranteed to be true. This is why the PARTIAL LEAST SQUARES method was

developed.