




































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!





































And c [2,3,4], then the result is
Categorical data
res <- c("Mi","Mi","Co","Co","Mi","Other","Co","Mi","Other","Co","Mi")
res <- factor(res, levels=c('Mi','Co','Other'))
Need to tell R that we’re not dealing with texts but with categorical data, they are kind of labels; for this
reason, we start defining a vector with text and then tell R that they are factors
table() where the object is a vector of factors, sums up the number of elements belonging to the same
factor
For instance, computing table(res) we obtain:
Mi Co Other
length(): length of a vector of factors or numbers
Categorical variables are also part of datasets
data.frame() is useful to build dataset, specifying the variables
student_id evaluation_W evaluation_O evaluation_P outcome
1 45020 30 28 30 Passed
2 45679 29 30 30 Passed
3 46789 30 30 30 Passed
4 43126 NA NA 30 To be repeated
5 42345 25 28 28 Passed
6 47568 26 27 28 Passed
7 45674 17 NA 28 To be repeated
1,2,… are the observations
attach() temporarily saving the data frame within your environment (need to have small data frames)
detach() you detach the saved variables
Another way to access data is through $, for instance exam$evaluation_W will show the column
The other simple way is exam[,2], indicating that we want to show the second column of the DB
You can also get and upload data from folders and files
record <- read.table('record.txt', header=T)
We read a table format (record.txt) creating a data frame from it
header=T: ask R to read the first line as name of variables
dim() is the dimension of dataset (n,p), dimnames() the names of columns and rows
Rename the variables
record <- data.frame(record[,1:7], row.names=record[,8])
var.names <- c("m100","m200","m400","m800","m1500","m3000","Marathon")
dimnames(record)[[2]] <- var.names
record
With this, we take data from the dataset just considering from the first to the seventh column. Then, we use
the last column to rename the rows.
Then, we create a new vector of characters, assigning it to the columns names
To save the dataset just created and renamed we use write.table(name of data frame, file= name)
save(x,y,z,…, file=’xyz.RData’) is useful in order to save all the variables in a file
save.image(‘xyz.RData’) will save the entire workspace
load(“xyz.RData”) will load a workspace
Visualizing data
Whenever there are categorical data, pie chart is the best in order to understand the frequency as it’s
easy to understand the angles
Libraries are used in order to have better representations
Set of codes put together in a folder that can be installed in order to implement something already
done
ggplot2 helps you in designing better charts
Multivariate data
is(res)[1] : which type of object res is (why should I put [1]?)
the function plot works differently based on the input
median
The boxes are built considering the first quartile and the third one
The 50% of data stays into the box
Q3 + 1.5*IQR is the upper whisker
Q1 - 1.5*IQR is the lower whisker
The problem with this plot is that the scale considers different type of measure (minutes and seconds)
similarities
One dimensional data analysis
value
Q-Q plot : is a way to verify (qualitatively) the gaussianity of a certain sample considering the quantiles
of the distribution
The more the points are following the line, the more the possibility that the sample is coming from a
Gaussian distribution
Otherwise you can run a Shapiro test : p-value (0.2569) is pretty high so we can say that our data is
normally distributed (The p-value should be less or equal 0.05 to reject the normality hypothesis)
Another way is through the sample mean. How different is 11.5 from the sample mean? We need to
use the std. deviation
T statistics is computing the difference between the sample mean and theoretical mean
Confidence interval: we estimate an interval in which the true value can be plausibly present
IC <- c(inf = sample.mean - sample.sd/sqrt(n) * qt( 1 - alpha/2, n-1 ),
center = sample.mean,
sup = sample.mean + sample.sd/sqrt(n) * qt( 1 - alpha/2, n-1 ))
pc.runrec$sd with the dollar we extract variables out of an output object (here the std. deviation of the
principal component)
Only taking the first principal component as subspace, we are capturing the 99.9% of the variability of the
dataset, so everything is summarized by it
There’s a trade-off between how much variability I want to take and the capability to easily represent it, as
much of the times we want to use PCA as input for other analysis
Loadings: can understand the weights of the variables (they are the components of the eigen vectors)
The result of the plot of loadings is telling us that the direction on which we have max variability is the
marathon’s one
The next direction along which you have max variability, excluding marathon, is explained by the 3000m and
so on
At the end, we understand that the longer the track, the higher the variability
Actually, is not really about comparing the variables, they have different unit of measures, is totally useless
Is the intrinsic unit of measure that matters, so we need to standardize the variable and compare the standard
deviations, that are pure numbers
Data Standardization
To standardize we create a new dataframe with the scale function scale(data)
We recompute the princomp with the new dataframe
Now, we see from the plot that the unit of measure, the one of the variability’s, is the same for each variable
(var=1)
In fact, standardizing variables means to assign variables std.dev=1, thus we report all the variables to the
same unit of measure
PCA is explaining a lot about the variability, but we might want to go forward, maybe to the second
When there’s an elbow we might stop, we gain a really little by going forward, stop there is enough
For what concerns the loadings, they seem almost the same from the plot of the first PC à Equal weights to
all the variables
With negative PCA, the country is pretty good, below the average whereas with positive you’re over the
mean, overall
If you’re on zero, you are on average
If you are above 0 on the second component, you are getting worse for the variables pointing up and
viceversa
Bi-plot
High in second component à High in short runs
The arrows indicate for what you are going bad
Regarding the second component, if it’s high, this means that this country is better in long runs
For principal component, you are better and better going to the right and viceversa
Here, we are considering and comparing correlation, not variability! Variability is the same for each
variable, we standardized them
Performing PCA on correlation might bring better insights on how ae variables related between each other
Food dataset
We have 8 variables and 25 countries
Looking at the boxplot we can notice the variability along variables
Variability is high for different variables because of both the unit of measure (easy to eat kilos of cereals,
difficult to eat kilos of eggs) and the diet type
st
: PCA on original variables
8 principal components, then summarized to understand the results
70 % of total variability is taken by the first PCA
Variability of principal components is always decreasing by construction, they are the lambdas, that have
been found from the highest to the little one
Scores: observation in the new system, coordinates in the new system
In the second PCA looking at boxplots we have a higher variance only because of outliers, so that the third
PCA might be useless, really close to the second one apart from the outliers
Loadings plot: we have both positive and negative loadings on the first
A country with a negative PCA on the first principal components represents a country in which Cereals and
Pulse are the most eaten, while if they are positive, they are more for meat, milk and pigs
Plotting milk-cereals and pc 1
and cereals, with the first and second PCA
nd
: scale variables
Variances explained by PCA drastically goes down
We need more variables to explain most of the data
Plotting with boxplots, we notice that the 3
rd
PC is capturing more variability than the second one, this means
that we cannot stop at the second one
As long as you reach the fourth, PC should be all considered, then we have an elbow
With the first principal component, we have a clear phenomenon of protein-based (positive) diet vs. fruit-
milk-cereals-pulse diet (negative)
The plot of comp 1 and comp 2 shows that Portugal has a real low value in comp 2 , this means that has a strong
consumption in fruit and fish, plotting Portugal with coordinates of first and second principal component
(given by the scores)
On the first principal component, going to the right we have a country rich in protein-based diet
3D data
We have a cloud of data in three dimensions
We want to find a line able to explain most of data
At first, we want to find a single number that best approximates (mean, barycenter)
Point that minimizes the distances à no dimensions, just a point
Then, we can try to find a line that has minimum distance from data
The line is created with a sum of points that minimizes the distances with data
Not the regression line! The regression line minimizes the error, that means the distance of the point from the
line but along the vertical direction, whereas the PC takes the projection on that line of the point
Regression line depends on the viewpoint, on the axis taken as reference, PC does not
We can also find the plane that is closer to the data cloud
Scores: coordinates of the projection
Loadings: direction
We will have x% of the times an interval that will cover the true beta 1
The interval is acceptable based on the problem
No zero in the interval: so, is beta 1 zero? à the interval tells us is not possible, zero is not in the interval. This
was also confirmed by the p-value, that was 2x
(connection between 0 and confidence interval)
With beta 1=0 à no relation
Now, we can predict new values through the regression model having the m100 and wanting the m200. New
values should always be structured as dataframe, otherwise the predict command won’t work
Predict command: takes as input the model, the new observations and possibly the interval we would like to
have for the new estimated values
predict(regression,newdata) : the result is the time taking for m200, the value of the regression line with
new m
Now we might also be interested in having an estimation of the error of the three predicted values.
There are many ways to assess it:
We have the line, an estimation of the mean of y given x 𝐸[𝑌|𝑋 = 𝑥 !
!
"
We know that we have an extra term generating the y
Having a new x 0 we want to predict the new y 0
This is going to be the mean of y given x 0 as regressor
We still have some uncertainty about the mean of y
given that regressor, we can estimate this uncertainty
through the confidence interval
A different thing is asking for an interval of values of Y,
not the mean, that will be spread out around the mean
Prediction interval : where Y will be with a certain
probability
The prediction interval is larger because is not
predicting the mean, is predicting the value, where Y is
IC_nd will show the central value of the mean, upper
and lower boundaries of the confidence interval given
the new x
IP_nd shows the interval in which the values of Y is
100 new observations
Plot:
UQ (uncertainty qualification): the further you go from the center of the data cloud, the further you go from
the mean, this because there’s higher uncertainty
The regression line might vary into the confidence interval, the true value of the mean of y will be into the
confidence interval à WRONG!
The confidence interval is made by 100 intervals, to have a line 99% of the times right you should have this
probability for each interval that is almost impossible
Interval for the coefficient can tell us how the regression line can vary
6 8 10 12 14 16 18
20
22
24
26
m
m
Obs.
Fit
Reg. line
Pred. new
IC
IP
Linear regression (m200 vs m100)
This is the plot of the regression line built on original values
also considering new data (10,11,12), respectively with
confidence and prediction interval
e : Vector of residuals, exactly what we are trying to minimize
y ∙ 1: mean
c 2
c 1
&
There’s more than one x, more than one regressor at a time
Not necessarily coming from the dataset, other x might come from PCA, transformation,…
Not linear in the original variables, linear in the transformed variables
How to interpret the betas?
The beta 0 is that the line will go through the barycenter, coming from the minimization of the squared error
The beta 1 is the increment in the mean of y if there’s an increment in the x of one unit
But how to interpret the betas in the multivariate?
Keeping everything else fixed and passing from x 1 to x 1+ , the prediction of y will increase of beta 1 à Is this
possible in practice?
à This is made possible only if variables are uncorrelated , otherwise you cannot just move one variable,
something else would change
The values of the coefficients (betas) are linked not only to the unit of measure of the variables, but also to the
presence of all the other coefficients. They have a certain value inside that model with those coefficients.
Regressors are uncorrelated if we take as x 1 , x 2 , …, x p the principal components
We find the estimates of the parameters beta by optimizing the function of squared error
"
&
&
&
'
&
Equivalent to: 𝑅𝑆𝑆 = F𝑦 "
!
"
"
&
&
!
"
&
&
Estimates: 𝛽 !
"
&
Fitted model: 𝑦* = 𝛽 !
"
"
(
(
Having the model, I can compute the predictions for all the i s in my dataset:
$
!
"
#"
(
#(
residuals 𝑒 = R
"
'
Find 𝛽 !
(
&
= X(𝑦
$
&
𝑖𝑠 𝑚𝑖𝑛
'
#)"
'
#)"
"
'
!
"
""
'"
!
"
"
(
(
Geometrically, we are looking for something as close as possible to y on the space, the projection
Dim=p+
c 1
1: Vector identifying the space
where there’s no variability
Where 𝑒
is the difference between what observed and what predicted through the model
I’m looking for a vector 𝑦* being as close as
possible to the vector of our observations
So, we look at residuals plot, might be more understandable
In the Residuals vs. Fitted plot we are not really plotting the error, we
are considering something really similar to the error
The red line is curve and has a sort of pattern à Not a good model
for these data
Cook’s distance: there are points that might be either an outlier or a
leverage or even both
Since the model doesn’t appear to be the best one, we add a new
column to our dataset, a new x
2 obtained by x 1
2
The model is still linear, x
2
is not quadratic. is not linear on the
original variables but it doesn’t matter, we need to consider linearity
in a larger sense
1
2
y 1
x 11
x 11
2
y 2 x 21 x 21
2
The new model is: 𝑑𝑖𝑠𝑡 = 𝛽
!
"
&
&
Once that the lm function has been run, we notice that R
2
has increased to 0.
What does Pr(>|t|) tell me?
à Shows the probability of having 𝛽
≠ 0 even though the true 𝛽=
In this case, 𝛽 1 has probability of 15% à High number!
Plotting the regression line, now we see that is curved
Also, considering the residuals plot, there’s no quadratic error in the residual vs fitted plot, plus there’s not a
pattern in the line
Tales of the distribution Is not actually following a gaussian but is acceptable
Anyway, we might perform a Shapiro-Wilk test to verify the gaussianity
Test:
0 : gaussian distribution, data follows a normal distribution
1 : no gaussianity that might be drawn from statistical evidence
In this case, the result is p-value=0.35 à We don’t have proofs to reject the gaussianity
Since the linear variable seems not so useful, we might try to eliminate it from the model
2
becomes 0.9361, very little gain by adding the linear variable
Do we need, then, the linear variable? à As a general rule, we tend to maintain all the terms lower than the
maximum, but it depends on the situation (hierarchy principle)
Also, the residuals plot seems worse, there’s a curve in the residuals vs. fitted, a connection between errors
and model
Anyway, the Shapiro test confirms the gaussianity with a p-value of 0.
Now, we would like to use the model to perform predictions
First of all, we need to decide which of the models to use (the complete one or just with quadratic variable)
Then, we generate 20 new speeds and transform them into squared or directly generate data as squared if
we use the model only with quadratic variable
Now, we can perform the predictions, doing at the same time the upper and lower values of confidence and
prediction intervals
Once that the predictions have been made, the plot is drawn, having the regression line in black, the
confidence interval in blue and the prediction interval in green
If we had kept the linear term, the plot would have been more complicated, would have been a surface
Dataset ‘work’
Multiple Linear Regression with both Dummies (Categorical Variables) and Numerical Variables
Set of 20 employees with multiple variables such as gender, year of service and education level
We want to build a model able to predict the average score of the test given the Years of service
Regression model that might split between female vs male and master vs. bachelor’s degree
The percentage of variance explained by the model is low
Years of service is useful to explain the average score but there’s still lot of variability not explained by the
variable
Let’s see if the population can be segmented through categorical variables and see if might help in
explaining the link by splitting the population by gender and education level
Linear regression for male and another different for female
Thus, we will have couples of betas, how to treat them? How to compare them?
Plus, the population will decrease in number because of the split and might happen that the variability is even
larger
First of all, we explore the possibility of having differences between females and males
Color the dots, females are orange and males are green
Qualitatively, from the plot we might notice that of course the two regression lines will be different in
intercept, the slope also might differ
Build a variable (dummy variable) that is 0 when female and 1 when male
The baseline will be females
Gender.new <- rep(0,n)
Gender.new[males] <- 1
We create a variable with 20 zeros as baseline, 1 when is male
Score=𝛽 0
1
*dummy+ 𝛽 2
*years + 𝛽 3
yearsdummy + 𝜀
If dummy=0, score= 𝛽 0
2 *years (this will be the slope, beta0 will be the intercept for the line fitting females)
If dummy=1, there’s an additional value to the slope given by 𝛽 3
*years and the additional value for the
intercept given by 𝛽 1
3 is what you need to add to the females’ slope to get the males’ one, is not the males’ slope!
The model that we are fitting will change both intercept and slope in case of dummy=
In the lm function nothing changes, we just need to insert the dummy variable and the interaction between
the two
lm(Y ~ X + Gender.new + X:Gender.new)
Testing the beta from the interaction (𝛽 3 ) we notice that is 0.1608: the probability is high enough to conclude
that the true 𝛽 might be equal to zero, we have no proofs to reject the H 0
0.0179 might be argued, if 𝛽 2 were zero, then this number different from zero had the possibility to come that
is really little, so we accept the fact that 𝛽 2
is different from 0
Now, we are explaining 0.85 of the variability through the model
Even the R-squared increased a lot and this because we added variables
‘Hitters’ dataset: PCA and Regression
Hitters <- na.omit(Hitters) will eliminate all the NaN values in the dataset
Principal component as regressors in the model
Predict the salary as function of the performance
Collinearity among the features: the model that you are fitting is very unstable, changing a little bit the data,
model will change a lot, variability is really high
Collinearity indicates that one information is also expressed from another one
Collinearity might be fixed first of all looking at the unit of measure, maybe they’re both measuring
temperature but one in Celsius and one in Fahrenheit, otherwise we can go for PCA
st
: we use all the variables in numerical terms and fit the model
The R-squared is 0.
Temptation to eliminate almost every variable
The p-value is telling us that you can remove one variable, keeping all the other variables in the model
We can remove one variable at a time, or we can try to get rid of collinearity performing the PCA on
regressors
Variables are scaled because we want to keep the propriety of having the regression line passing from the
barycenter
Scaling will allow us to perform PCA on correlation instead of covariance
The first PC tells us that every variable explains almost the same, they have the same weight
The second one explains performances in that year vs. performances along the career
The number of PC to choose is 2 but we might also go for 3
We redefine the variable in terms of score along the principal components
The first model that we might use is the one with 10 principal components to explain the salary
result <- lm(Hitters$Salary~ sp1.pc + sp2.pc + sp3.pc + sp4.pc + sp5.pc + sp6.pc + sp7.pc
2 is exactly the same, we are just using a different reference system through the Principal Components, but
the plane is the same
The only difference is that the variables now are orthogonal
Now we can go for the reduction of the model
0
1
2
This is the new model, however PC1 is e 11
x 1
+e 21
x 2
+…+e p
x p
and PC2=e 12
x 1
+…+e p
x p
Substituting we will get:
0
1 (e 11 x 1 +e 21 x 2 +…+e p 1 x p
2 (e 12 x 1 +…+e p x p ) that factorizing becomes
0
1 e 11
2 e 12 ) x 1 +() x 2 +…+ () x p
We can still use the original variables but having reduced the space, we are just considering the two first
components
This is called PCA-regression
It seems like nothing changed, but actually I reduced the variables
regsubsets(model_to_fit. (~.) : use all the variables in the dataset to explain the salary)
Function that automatically performs the variable selection by different criteria (R
2
, Adjusted R
2
,…)
The output is a matrix with all the possible models tested and variables used in that model
We can use all the variables or telling how many variables we would like to consider (nvmax=)
reg.summary$which will show which variables are included in a certain model
reg.summary$rsq will show us the R
2
of every model
We can use the plot to decide which model to keep based on a certain criteria (R
2 ,…)
Once you have decided the model to choose, you can get
the coefficients of that model chosen based on the
criteria
Thus, the output will be the variables used in that model
Plot of the variables included in each model with the
adjusted R
2
Black: included
White: not included
We can also choose what selection method to apply,
forward or backward
Before we were dealing with 2
p
models, with forward and backward we just select p+1 models
Anyway, the selection of the models should be computed manually in order to have an idea about what we
are doing
Linear Regression - Examples
Dummy variable: Country
Predict the number of cars and use the dummy variables
One variable for the car, one for the year and one for the dummy
Instead of projecting the Y on
x 2 , we project the Y on the
The error will be with average 0, standard deviation of sigma squared and normally distributed
We are creating two datasets, one with the original y, one with the new y but both with the same 𝑓, used as a
dataset
Create data until x
p
, that is n- 1
Do this both for training and test set
Then, we plot data
Black dots are the real ones, the only information we have onto which we should build the function
Red dots should be the one predicted, we want to use them to see how far we are from our prediction
The blue is the true function that generated the red dots
This is also called Montecarlo
First, we try using a linear model and then we start adding one column at a time until the end
Once that the last plot is reached, the black line goes through every possible black dot but we are really far
from the red ones
The more variable you have, the higher the dimension
The adjusted R2 shows that once you get to the power 3, you are not gaining something more in adding
more variables, but you are losing in prediction, the residual sum of squared is worst off
Now, we compare it with the true model
By rising the power, coefficients of 𝛽 2 is really changing, might drive into really bad conclusions, this valid also
for 𝛽 3
The goal is to explore the relationship between age and presence of coronary heart disease
Split the age into two classes and compute the probability of having the disease or not
Work with the probability of observing a phenomenon, not zeros and ones
0
1
This is the improper way to treat the problem
We need to use a generalized linear model with logit function
Model: logit(p(AGE))=beta0+beta1*AGE; p(AGE)=P[CHD=1|AGE]
Logistic regression: explain the probability
Logit function: log h
(
",(
i = 𝑓(𝑎𝑔𝑒) + 𝜀
glm: generalized linear model
Need to specify which model we want to use with the glm (link=logit)
binomial: want to fit 0 and 1
deviance: what you gain by using the model instead of just the average
Null deviance: how well the response is predicted by using just the intercept
Residual deviance: how well the response is predicted by the model when the predictors are included
The lower, the better, we have less difference between fitted values and observed values
linear.predictors: 100 values of the y, corresponding to the estimated value for each patient. They
correspond to the values for logit(p(x))
fitted.values: estimation of the probabilities, transformed output in terms of probability. They correspond
to p(x)
Regression model to fit the probability of having the disease given a certain age
How to interpret coefficients?
Increment the age by 10, the probability of having the disease is 3 times more
ln (
p
!
"
New patient: what’s the probability of the disease?
Predict function
type=’response’: we want the probability
Don’t specifying it, we will obtain the output of logit (that is the logarithm of the odds: log (
(
",(
We would like to have a label back, not a probability
We can choose a threshold saying that if the probability is above it, one of the labels is set
LDA and QDA: Gaussian distribution
We need to check for gaussianity and homoskedasticity (variance of the two classes is the same)
We want the gaussian distribution for both those who have the disease and not
We can use either a Q-Q plot or the Shapiro Test
We have 0.12 and 0.35, both are gaussian distribution (they’re not so high in value but we don’t have proofs
to reject the H 0
Check if the variance is the same. If yes, we go for LDA, otherwise we go for QDA
Basic approach: standard deviation for both groups and compare them through a measurement of a
standard deviation (Barlett test)
The test is necessary as it is incorrect to compare the absolute values of the variance
The Barlett Test is a kind of Shapiro Test for the homoskedasticity
0 : variance is the same
1
: at least two are different
We want a big p-value to accept the H 0
to have the LDA applicable
In this case, we obtain a p-value of 0.8794 à Really high, we accept the H 0
There’s homoskedasticity, so we can go for LDA, the variance between the classes is the same
Compute the prior, both P 0
and P 1
P0 <- n1 / n
P1 <- n0 / n
They are two parameters of this model, need to check whether they make sense, otherwise the entire model
will be affected
The means are computed considering all the dots when disease=1 and disease=