






















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!























Box-Cox transformations are useful to recover Gaussianity for a random
sample and are given by 𝑥𝑥𝜆𝜆 = (^) �
𝑥𝑥 𝜆𝜆^ − 𝜆𝜆 ,^ 𝜆𝜆 ≠^0 log 𝑥𝑥 , 𝜆𝜆 = 0
where 𝜆𝜆 is estimated through
maximum likelihood. In R the best value for 𝜆𝜆 can be found as follows:
lambda = powerTransform(data) where data is a matrix whose columns are the random samples in analysis. After that, Box-Cox transformations can be applied as follows:
boxcox = bcPower(x, lambda$lambda[i]) where x is the i -th column of data.
In order to plot ellipses one should resort to the function ellipse of the library car. In particular, the syntax is the following:
ellipse(center, shape, radius, center.pch = 16) where center is the center of the ellipse, shape is a 2 × 2 covariance matrix and radius is the radius of the circle generating the ellipse.
Given a set p of 𝑝𝑝-values, it is possible to adjust them using a particular correction as follows:
pAdjusted = p.adjust(p, method) where method specifies the correction ( bonferroni , BH and so on).
A possible way to test the homogeneity of variances for multiple random samples drawn from different population is the following:
bartlett.test(x, g) where x is a numeric vector of data values (or a list of numeric data vectors representing the respective samples) and g is a vector or factor object
giving the group for the corresponding elements of x (ignored if x is a list). Moreover, it is also possible to compare the variances of two Gaussian samples through the following call:
var.test(x,y) where x and y are the numeric vectors of data values.
In the case of multivariate samples one needs to proceed qualitatively by plotting the sample covariance matrices through the function image as follows:
image(S1, col=heat.colors(100), main='Title', asp=1, axes = FALSE, breaks = quantile(rbind(S1,…,Sn), (0:100)/100, na.rm=TRUE)) ⋮ image(Sn, col=heat.colors(100), main='Title', asp=1, axes = FALSE, breaks = quantile(rbind(S1,…,Sn), (0:100)/100, na.rm=TRUE)) where n is the number of matrices to compare.
The scores can be accessed through the call pca$scores and useful graphical representations can be obtained as follows:
plot(pca$scores[,1:2]) abline(h=0, v=0, lty=2, col='grey') biplot(pca)
It is possible to plot the boxplot relative to each class in which the data are partitioned as follows:
plot(labels,data) where data is a vector containing the realization of the variable in analysis for each statistical unit and labels is a factor containing the labels associated to each unit. An alternative way is the following:
boxplot(data ~ labels)
The code to perform ANOVA in R is the following:
fitted = aov(formula,data) where formula is a formula specifying the model and data is a data frame in which the variables specified in the formula will be found (if missing, the variables are searched for in global environment). Moreover, the call summary(fitted) provides useful information such as the 𝑝𝑝-value of the test 𝐻𝐻 0 : 𝜏𝜏 1 = ⋯ = 𝜏𝜏𝑔𝑔 = 0vs𝐻𝐻 1 : ∃𝑖𝑖: 𝜏𝜏 (^) 𝑖𝑖 ≠ 0.
In order to compute confidence intervals for the differences in the mean it is first necessary to compute the sample mean associated to each group, which can be done as follows:
M = tapply(data, labels, mean) Moreover, the estimate for the common covariance can be obtained as follows:
SSres = sum(residuals(fitted)^2) S = SSres/(n-g) It is therefore possible to compute the confidence interval for all the differences as follows:
treat = levels(labels) ICrange=NULL for(i in 1:(g-1)){
fitted = manova(formula,data) where formula is a formula specifying the model and data is a data frame in which the variables specified in the formula will be found (if missing, the variables are searched for in global environment). Moreover, the call summary.manova(fitted,test) , where test is the name of the test statistic to be used (such as Wilks ), provides useful information such as the 𝑝𝑝-value of the test 𝐻𝐻 0 : 𝜏𝜏 1 = ⋯ = 𝜏𝜏 (^) 𝑔𝑔 = 0vs𝐻𝐻 1 : ∃𝑖𝑖: 𝜏𝜏 (^) 𝑖𝑖 ≠ 0. It is also possible to
perform an ANOVA test for all the 𝑝𝑝 variables through the call summary.aov(fitted). All in all, the matrix 𝑊𝑊 can be obtained as follows:
W = summary.manova(fitted)$SS$Residuals
Libraries to import:
library(MASS) library(class) library(rgl) library(mvtnorm)
The code to perform LDA is the following:
classifier.lda = lda(data, labels, prior = proportions) where data is a matrix or data frame containing the explanatory variables, labels is a factor specifying the class for each observations and the attribute prior specifies the prior probabilities of class membership. Note that if the attribute prior is omitted then the priors are estimated from the empirical frequencies. The return value is an object of class lda containing many attribute such as:
Given a data frame newData containing the realizations of the feature vector for new statistical units we can make inference on the labels associated to them as follows:
predict(classifier.lda, newData) In the case of LDA the object returned by predict has the following attributes:
z = predict(classifier.lda, xy)$post z1 = z[,1] - pmax(z[,2], z[,3]) z2 = z[,2] - pmax(z[,1], z[,3]) z3 = z[,3] - pmax(z[,1], z[,2]) contour(x, y, matrix(z1, 200), levels=0, drawlabels=F, add=T) contour(x, y, matrix(z2, 200), levels=0, drawlabels=F, add=T) contour(x, y, matrix(z3, 200), levels=0, drawlabels=F, add=T)
𝐾𝐾-Nearest Neighbours
The code to perform 𝐾𝐾-nearest neighbours discriminant analysis is the following:
classifier.knn = knn(train, test, cl = labels, k = K, prob) where train is a matrix or data frame of training set cases, test is a matrix or data frame of test set cases, cl is a factor of true classifications of training set, 𝑘𝑘 is the number of neighbours considered. Moreover, if the attribute prob is set to T then the proportion of the votes for the winning class are returned as attribute prob. The return object is the factor of classifications of test set.
The partition induced by 𝐾𝐾-nearest neighbours discriminant analysis can be plotted as follows (case 𝑝𝑝 = 2):
x11() plot(data, main='Title', xlab='Label1', ylab='Label2', pch=20) points(data[i1,], col=1, pch=20) ⋮ points(data[ig,], col=g, pch=20) legend("topright", legend=levels(labels), fill=c(1,…,g), cex=.7) points(classifier.lda$means, pch=4,col=c(1,…,g) , lwd=2, cex=1.5)
x = seq(min(data[,1]), max(data[,1]), length=200) y = seq(min(data [,2]), max(data[,2]), length=200) xy = expand.grid(Feature1=x, Feature2=y)
z = as.numeric(knn(train = data, test = xy, cl = labels, k = K)) contour(x, y, matrix(z, 200), levels=c(1.5, 2.5), drawlabels=F, add=T)
Quadratic Discriminant Analysis
The code to perform LDA is the following:
classifier.qda = qda(data, labels, prior = proportions) where data is a matrix or data frame containing the explanatory variables, labels is a factor specifying the class for each observations and the attribute prior specifies the prior probabilities of class membership. Note that if the attribute prior is omitted then the priors are estimated from the empirical frequencies. The return value is an object of class lda containing many attribute such as:
Given a data frame newData containing the realizations of the feature vector for new statistical units we can make inference on the labels associated to them as follows:
predict(classifier.qda, newData) In the case of QDA the object returned by predict has the following attributes:
Remark: The estimation of the AER and the plotting of the induced partition is identical to the case of LDA.
Fisher’s Discriminant Analysis
In order to perform Fisher’s discriminant analysis one first needs to estimate the covariability between and within the groups as follows:
M = sapply(data,mean) M1 = sapply(data[i1,],mean) ⋮
points(canonicalM1[1], canonicalM1[2], pch=4,col=1 , lwd=2, cex=1.5) ⋮ points(canonicalMg[1], canonicalMg[2], pch=4,col=g , lwd=2, cex=1.5) x = seq(min(coordinate1),max(coordinate1),len=200) y = seq(min(coordinate2),max(coordinate2),len=200) xy = expand.grid(coordinate1=x, coordinate2=y) z = cbind(sqrt(rowSums(scale(xy, canonicalM1, scale = FALSE) ^ 2)), …, sqrt(rowSums(scale(xy, canonicalM3, scale = FALSE) ^ 2))) z1 <- z[,1] - pmin(z[,2], z[,3]) z2 <- z[,2] - pmin(z[,1], z[,3]) z3 <- z[,3] - pmin(z[,1], z[,2]) contour(x, y, matrix(z1, 200), levels=0, drawlabels=F, add=T) contour(x, y, matrix(z2, 200), levels=0, drawlabels=F, add=T) contour(x, y, matrix(z3, 200), levels=0, drawlabels=F, add=T) Remark: It is possible to perform dimensionality reduction by considering 𝑘𝑘 < 𝑝𝑝 coordinates.
Libraries to import:
library(mvtnorm) library(rgl) library(car)
The dissimilarity matrix can be computed as follows:
dissimilarityMatrix = dist(data, method='euclidean') where data is the data frame (or a numeric matrix) and the attribute method specifies the metric to use (Euclidean, Canberra, Manhattan, …). Note that dissimilarityMatrix is a dist object and not a matrix. The result obtained can be visualised as follows:
image(1:n,1:n,as.matrix(dissimilarityMatrix), main= 'Title', asp=1, xlab='i', ylab='j') where n is the number of statistical units.
The code to perform hierarchical clustering is the following:
clustered = hclust(dissimilarityMatrix, method='single') where the attribute method specifies the linkage method (single, average, complete, Ward …). The object clustered is a list with many attributes:
The dendrogram can be plotted as follows:
plot(clustered, main='Dendrogram', hang=-0.1, xlab='', labels=F, cex=0.6, sub='') Moreover, we can draw a rectangle around the branches of the dendrogram highlighting the clusters corresponding to 𝑘𝑘 = 𝐾𝐾 as follows:
In order to choose the right value for 𝐾𝐾 one can run the following code:
b = NULL w = NULL for(k in 1:10){ clustered.k = kmeans(data, k) w = c(w, sum(clustered.k$wit)) b = c(b, clustered.k$bet) } matplot(1:10, w/(w+b), pch='', xlab='Clusters', ylab='Within/Tot', main='Choice of K', ylim=c(0,1)) lines(1:10, w/(w+b), type='b', lwd=2) and then look for an ankle in the plotted line.
Multidimensional Scaling
The code to perform multidimensional scaling is the following:
scaled = cmdscale(distObj, k=K) where distObj is a distance structure or a full symmetric matrix containing the dissimilarities and the attribute 𝑘𝑘 specifies the maximum dimension of the space which the data are to be represented in. It is possible to compare the original distance structure with the scaled one as follows:
plot(distObj, dist(scaled)) In particular, strong correlation between such structures is an indicator of good representation.
The STRESS can be computed (and plotted) as follows:
Stressk = NULL for(k in 1:4) { scaled.k = cmdscale(distObj, k) Stress = (sum((as.vector(distObj) - as.vector(dist(scaled.k)))^2) /
sum(as.vector(scaled.k)^2))^(1/2) Stressk = c(Stressk, Stress) } x11() plot(1:4,Stressk,xlab='k',ylab='Stress',lwd=2)
It is possible to perform hypothesis tests for linear combinations of the parameters as follows:
linearHypothesis(fittedModel, C, v) In particular, such function performs the test 𝐻𝐻 0 : 𝐶𝐶𝛽𝛽 = 𝑐𝑐vs𝐻𝐻 1 : 𝐶𝐶𝛽𝛽 ≠ 𝑐𝑐.
Moreover, it is also possible to compute confidence intervals for the 𝛽𝛽𝑖𝑖’s as follows:
confint(fittedModel, level) where the attribute level specifies the level of the confidence interval. Note that such function computes the one-at-the-time confidence interval (a correction such as Bonferroni is necessary to have a global level of confidence.
Given a data frame newData containing the realizations of the feature vector for new statistical units we can make predictions as follows:
interval = predict(fittedModel, newData, interval, level) where the attribute interval specifies the type of interval to compute ( confidence for a confidence interval for the mean and prediction for a prediction interval for the new observations) and the attribute level specifies the level of such interval.
To perform diagnostics on the fitted model one can use the following code:
plot(fittedModel) shapiro.test(residuals(fittedModel)) In particular, the call plot(fittedModel) prints four different figures:
Ridge Regression
The code to estimate the vector of parameters 𝛽𝛽 through ridge regression
is the following:
fittedRidge = lm.ridge(y ~ z1 + … + zr, lambda) where y is the target, z1,…,zr are the covariates and the attribute lambda specifies the value of the regularization parameter. The attribute lambda can also coincide with a vector of values, in which case the model is fitted for each single value of the regularization parameter. Moreover, it is possible to identify the best value for lambda through the following call:
select(fittedRidge)
Lasso Regression The code to estimate the vector of parameters 𝛽𝛽 through lasso regression
is the following:
fittedLasso = glmnet(x,y, lambda) where y is the response variable, x is the input matrix (whose rows are the observation vectors) and the attribute lambda specifies the sequence of values for the regularization parameter. The values of the parameters as a function of 𝜆𝜆 can be plotted as follows:
plot(fittedLasso,xvar='lambda',label=TRUE, col = rainbow(dim(x)[2])) legend('topright', dimnames(x)[[2]], col = rainbow(dim(x)[2]), lty=1, cex=1) The optimal value for the regularization coefficient can be obtained as follows:
crossValidation = cv.glmnet(x,y,lambda) bestLambda = crossValidation$lambda.min