
































































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!

































































Let us suppose we want to compare the performance of different classifiers on the same dataset SAheart. First of all, we need to ensure that the chosen validation scheme is the same, with the same sampling seed. The starting point is the confusion matrix: AS we have already said, from a confusion matrix we can derive various measures of classification performance such as the correct classification rate (hit rate), the misclassification rate, sensitivity, specificity, precision and fractions. We can then compare the different classifiers through cross-validation and/or validation set approach. From this table we can conclude that: Methods based on the Gaussian assumption on predictors, like LDA, perform well on the SAheart dataset, which means that the assumption is reasonable.
Logistic Regression (LR) performs equally well. This means that the decision boundary can be reasonably assumed to be linear.
k-NN has the worst performance, followed by Naive Bayes - kernel. This means that non-parametric approaches are not doing well, probably because the decision boundary is not far from linearity.
The positive predictive value is slightly smaller than the negative predictive value for LDA and LR, much smaller for Naive Bayes
PREDICTION MECHANISM (classification rule) So far, we have predicted the observations in a test set by Bayes' mathos, based on the maximum probability a posteriori: But is this mechanism truly right? We mmust consider the cost associated with prediction error.
Wednesday, February 11, 2026 09:
setwd('C:/Users/matteo.farne2/OneDrive/Documenti/Passato/Desktop/Backup PC/Documenti/Expansion Drive/Documents/Documents/Università/rtd-b/Big Data and Analytics') # 1. load dataset juice<-read.table("juice.txt",header=T) juice$scelta<-as.factor(juice$scelta) juice$negozio <- as.factor(juice$negozio) names(juice)<-c("choice","ID.customer","week","priceCH","priceMM", "discountCH","discountMM","loyalCH","loyalMM","shop") str(juice) summary(juice) n<-nrow(juice) table(juice$choice)/n # 2. estimation set.seed(123) # replicability unita.totali<-1: unita.training<-sample(x=unita.totali,size=0.75*1070) unita.test<-unita.totali[-unita.training] training.set<-juice[unita.training,] test.set<-juice[unita.test,] fit1<-glm(choice ~ week + priceCH + priceMM + discountCH + discountMM + loyalMM + shop, data=training.set, family=binomial) summary(fit1) # 3. remove week fit2<-glm(choice ~ priceCH + priceMM + discountCH + discountMM + loyalMM + shop, data=training.set, family=binomial) summary(fit2) # (test anova) anova(fit1,fit2,test="Chisq") # 4. Assessing predictive capability
predict2<-predict.glm(fit2, newdata = test.set, type = 'response') Y.prev<-as.integer(predict2 > 0.5) # Bayes rule mat.conf=table(test.set$choice,Y.prev) t.err.class<- 1 - (sum(diag(mat.conf)/sum(mat.conf))) err=(25+17)/sum(mat.conf) corr=(147+79)/sum(mat.conf) sens=79/(25+79) spec=147/(147+17) ppv=79/(79+17)#prec npv=147/(147+25) pos=(25+79)/sum(mat.conf) neg=(147+17)/sum(mat.conf) We compare two models, with and without the variable week. We test whether removing week significantly worsens the model through a chi-square test (anova) Maximum a posteriori probability rule: we allocate test units to class MM if and only if the predicted probability to choose MM is larger than 0.5. We build the confusion matrix and we estimate the misclassification rate:
Wednesday, February 11, 2026 10:
# lift curve library(ROCR) pred<-prediction(predict2, labels = test.set[, 1]) perf <- performance(pred,"lift","rpp") plot(perf, main="lift curve", colorize=T)
prob.ord <- sort(predict2, decreasing = T) soglie <- quantile(prob.ord, probs = seq(from=0.99, to=0.01, by=-0.1)) lift <- NULL for(i in 1:length(soglie)){ Y.prev<-as.integer(predict2 > soglie[i]) # Bayes rule mat.conf<-table(Y.prev, test.set[, 1]) # build the confusion matrix lift[i]<-((mat.conf[2,2])/(mat.conf[2,1]+mat.conf[2,2]))/((mat.conf[1,2]+mat.conf[2,2])/sum(mat.conf)) } plot(seq(from=0.99, to=0.01, by=-0.1), rev(lift), type="l", ylab= "lift", xlab="quantile")
sens<-mat.conf[2,2]/(mat.conf[2,2] + mat.conf[1,2]) spec<-mat.conf[1,1]/(mat.conf[1,1] + mat.conf[2,1])
perf <- performance(pred,"sens","spec") plot(perf, main="ROC curve", colorize=T) [email protected][[1]][93] abline([email protected][[1]][93],lty=2) abline([email protected][[1]][93],lty=2) text([email protected][[1]][93],[email protected][[1]][93]+0.02, "(0.896,0.760)")
pred<-prediction(predict2, labels = test.set[, 1]) perf <- performance(pred,"tpr","fpr") plot(perf, main="ROC curve", colorize=T) [email protected][[1]][93] abline([email protected][[1]][93],lty=2) abline([email protected][[1]][93],lty=2) text([email protected][[1]][93],[email protected][[1]][93]+0.02, "(0.104,0.760)") Plots Lift curve:
pred<-prediction(predict2, labels = test.set[, 1]) perf <- performance(pred,"lift","rpp") plot(perf, main="lift curve", colorize=T) abline([email protected][[1]][93],lty=2) abline([email protected][[1]][93],lty=2) text([email protected][[1]][93],[email protected][[1]][93]+0.04, "(0.358,2.121)")
pred.reg.log=predict prob.ord <- sort(pred.reg.log, decreasing = T) soglie <- quantile(prob.ord, probs = seq(0.99, 0.01, by=-0.1)) lift <- NULL pos.pred <- NULL pos.true <- NULL for(i in 1:length(soglie)){ Y.pred<-as.integer(pred.reg.log > soglie[i]) mat.conf<-table(Y.pred, test.set[, 1]) lift[i]<-((mat.conf[2,2])/(mat.conf[2,1]+mat.conf[2,2]))/ ((mat.conf[1,2]+mat.conf[2,2])/sum(mat.conf)) pos.pred[i]<-mat.conf[2,1]+mat.conf[2,2]; pos.true[i]<-mat.conf[2,2]; } plot(seq(from=0.99, to=0.01, by=-0.1), rev(lift), type="l", ylab= "lift", xlab="quantile", ylim=c(1,3),main="Lift curve") prop.MM=table(test.set$scelta)[2]/sum(table(test.set$scelta)) segments(0,1,1,1,col="blue")
n.test=dim(test.set)[1] plot(pos.pred/n.test,pos.true,type='l',xlab='soglie', ylab='successi',main='Cumulative lift curve') lines(pos.pred/n.test,round(prop.MM*pos.pred),lty=2)
In the regression setting, the standard linear model is commonly used to describe the relationship between Y and X. This model has distinct advantages in terms of inference and is often surprisingly competitive in relation to non- linear methods. However, in order to improve prediction accuracy and model interpretability, we can work with alternative fitting procedures. Prediction accuracy--> OLS performs well when n >> p (if relationship linear low bias and low variance). However, when:
Solution--> by constraining or shrinking the estimated coefficients, we can often substantially reduce the variance at the cost of a negligible increase in bias, leading to substantial improvements in accuracy. Interpretability--> Often not all variables used in the regression are in fact associated with the response. Including those irrelevant variables leads to unnecessary complexity. Solution--> by removing those variables (setting their coefficient estimate to zero) we can obtain a mroe easily interpreted model. OLS unlikely does this, thus we use approaches for automatically oerforming feature/variable selection. ALTERNATIVES TO OLS: Subset selection--> identify a subset of the p predictors that we believe to be related to the response. We then fit a model using least squares on the reduced set of variables.
Shrinkage--> fit a model involving all p predictors. However, the estimated coefficients are shrunken towards zero relative to the least squares estimated, this results in reduced variance (if coefficients are estimated to be zero = variable selection)
Dimension reduction--> projecting the p predictors into an M-dimensional subspace, where M < p. These M projections are used as predictors to fit OLS.
We have:
Sunday, January 25, 2026 10:
Validation and cross-validation As an alternative to the approaches just discussed, we can directly esti mate the test error using the validation set and cross-validation methods. This pro cedure has an advantage relative to AIC, BIC, Cp, and adjusted R2, in that it provides a direct estimate of the test error, and makes fewer assumptions about the true underlying model. Nowadays with fast computers, the computations required to perform cross-validation are hardly ever an issue. Thus, cross validation is a very attractive approach for selecting from among a number of models under consideration The one standard error rule (1SE rule) is a model selection method in machine learning and statistics that chooses the simplest model (most parsimonious) whose error is within one standard error of the best-performing model. It balances performance and complexity to prevent overfitting by favoring simpler models. SHRINKAGE METHODS We can fit a model containing all p predictors using a technique that constrains or regularizes the coefficient estimates, or equivalently, that shrinks the coefficient estimates towards zero, in order to significantly reduce their variance. The two best-known techniques for shrinking the regression coefficients towards zero are ridge regression and the lasso. Ridge Regression Recall that OLS fits the model by minimizing RSS. Ridge regression is very similar to least squares, except that the coefficients ridge are estimated by minimizing a slightly different quantity. where λ ≥ 0 is a tuning parameter, to be determined separately. The second term, called a shrinkage penalty, is small when β1,...,βp are close to zero, and so it has the effect of shrinking the estimates of βj towards zero. When λ = 0, the penalty term has no effect, and ridge regression will produce the least squares estimates. However, as λ →∞, the impact of the shrinkage penalty grows, and the ridge regression coefficient estimates will approach zero. Unlike least squares, which generates only one set of co efficient estimates, ridge regression will produce a different set of coefficient estimates, ˆβR λ , for each value of λ. Selecting a good value for λ is critical (cross-validation). Note: the shrinking penalty is applied to β1,...,βp, not to β0. OLS is scale.equivariant, but Ridge regression's estimates can change substantially when multiplying a given predictor by a constant. Therefore, it is best to apply it after standardizing the predictors, so that they are all on the same scale: Why does Ridge Regression improve over least squares? Ridge regression’s advantage over least squares is rooted in the bias-variance trade-off. As λ increases, the flexibility of the ridge regression fit decreases, leading to decreased variance but increased bias. Hence, ridge regression works best in situations where the least squares estimates have high variance. Ridge regression also has substantial computational advantages over best subset selection, which requires searching through 2p models. In contrast, for any fixed value of λ, ridge re gression only fits a single model, and the model-fitting procedure can be performed quite quickly. Ridge regression does have one obvious disadvantage: The penalty will shrink all of the coefficients towards zero, but it will not set any of them exactly to zero (unless λ = ∞). This may not be a problem for prediction accuracy, but it can create a challenge in model interpretation in settings in which the number of variables p is quite large. Even increasing the value of λ will tend to reduce the magnitudes of the coefficients, but will not result in exclusion of any of the variables. Thus, we turn to the Lasso…
The Lasso The Lasso coefficients minimize the quantity The only difference is that the β^2 j term in the ridge regression penalty has been replaced by |βj| in the lasso penalty. However, in the case of the lasso, the penalty has the effect of forcing some of the coefficient estimates to be exactly equal to zero when the tuning parameter λ is sufficiently large. Hence, much like best subset se lection, the lasso performs variable selection. As a result, models generated from the lasso are generally much easier to interpret than those produced by ridge regression. We say that the lasso yields sparse models, that is, models that involve only a subset of the variables. As in ridge regression, selecting a good value of λ for the lasso is critical. When λ = 0, then the lasso simply gives the least squares fit, and when λ becomes sufficiently large, the lasso gives the null model in which all coefficient estimates equal zero. However, in between these two extremes, the ridge regression and lasso models are quite different from each other: Depending on the value of λ, the lasso can produce a model involving any number of vari ables. In contrast, ridge regression will always include all of the variables in the model, although the magnitude of the coefficient estimates will depend on λ. It is clear that the lasso has a major advantage over ridge regression, in that it produces simpler and more interpretable models that involve only a subset of the predictors. However, which method leads to better prediction accuracy? Neither ridge regression nor the lasso will universally dominate the other. In general, one might expect the lasso to perform better in a setting where a relatively small number of predictors have substantial coefficients, and the remaining predictors have coefficients that are very small or that equal zero. Ridge regression will perform better when the response is a function of many predictors, all with coefficients of roughly equal size. However, the number of predictors that is related to the response is never known a priori for real data sets. Cross-validation can be used in order to determine which approach is better on a particular data set. Selecting the tuning parameter Cross-validation provides a simple way to tackle this problem. We choose a grid of λ values, and compute the cross- validation error for each value of λ. We then select the tuning parameter value for which the cross-validation error is smallest. Finally, the model is re-fit using all of the available observations and the selected value of the tuning parameter. DIMENSION REDUCTION METHODS Class of approaches that transform the predictors and then fit a least squares model using the transformed variables.
regfit.fwd <- regsubsets(Salary ~ ., data = Hitters, nvmax = 19, method = "forward") reg.summary<-summary(regfit.fwd) which.min(reg.summary$bic) plot(reg.summary$bic, xlab = "Number of Variables", ylab = "BIC", type = "l") points(6, reg.summary$bic[6], col = "red", cex = 2, pch = 20) regfit.bwd <- regsubsets(Salary ~ ., data = Hitters, nvmax = 19, method = "backward") reg.summary<-summary(regfit.bwd) which.min(reg.summary$bic) plot(reg.summary$bic, xlab = "Number of Variables", ylab = "BIC", type = "l") points(8, reg.summary$bic[8], col = "red", cex = 2, pch = 20)
coef(regfit.full, 6) coef(regfit.fwd, 6) coef(regfit.bwd, 8)
set.seed(1) train <- sample(c(TRUE, FALSE), nrow(Hitters), replace = TRUE) test <- (!train)
regfit.best <- regsubsets(Salary ~ ., data = Hitters[train, ], nvmax = 19)
test.mat <- model.matrix(Salary ~ ., data = Hitters[test, ])
val.errors <- rep(NA, 19) for (i in 1:19) { coefi <- coef(regfit.best, id = i) pred <- test.mat[, names(coefi)] %*% coefi val.errors[i] <- mean((Hitters$Salary[test] - pred)^2) }
val.errors which.min(val.errors) coef(regfit.best, 7)
predict.regsubsets <- function(object, newdata, id, ...) { form <- as.formula(object$call[[2]]) mat <- model.matrix(form, newdata) coefi <- coef(object, id = id) xvars <- names(coefi) mat[, xvars] %*% coefi }
regfit.best <- regsubsets(Salary ~ ., data = Hitters, nvmax = 19) coef(regfit.best, 7)
k <- 10 n <- nrow(Hitters) set.seed(1) folds <- sample(rep(1:k, length = n)) cv.errors <- matrix(NA, k, 19, dimnames = list(NULL, paste(1:19)))
for (j in 1:k) { best.fit <- regsubsets(Salary ~ ., data = Hitters[folds != j, ], nvmax = 19) for (i in 1:19) { pred <- predict(best.fit, Hitters[folds == j, ], id = i) cv.errors[j, i] <- mean((Hitters$Salary[folds == j] - pred)^2) } }
mean.cv.errors <- apply(cv.errors, 2, mean) mean.cv.errors par(mfrow = c(1, 1)) plot(mean.cv.errors, type = "b")
reg.best <- regsubsets(Salary ~ ., data = Hitters, nvmax = 19) coef(reg.best, 10)
set.seed(1) cv.out <- cv.glmnet(x[train, ], y[train], alpha = 0) plot(cv.out) bestlam <- cv.out$lambda.min bestlam
ridge.pred <- predict(ridge.mod, s = bestlam, newx = x[test, ]) mean((ridge.pred - y.test)^2)
out <- glmnet(x, y, alpha = 0) predict(out, type = "coefficients", s = bestlam)[1:20, ] library(plotmo) plot_glmnet(out,label=TRUE,s=cv.out$lambda.min) plot_glmnet(out,label=TRUE,s=cv.out$lambda.1se)
lasso.mod <- glmnet(x[train, ], y[train], alpha = 1, lambda = grid) plot(lasso.mod)
set.seed(1) cv.out <- cv.glmnet(x[train, ], y[train], alpha = 1) plot(cv.out) bestlam <- cv.out$lambda.min lasso.pred <- predict(lasso.mod, s = bestlam, newx = x[test, ]) mean((lasso.pred - y.test)^2)
out <- glmnet(x, y, alpha = 1, lambda = grid) lasso.coef <- predict(out, type = "coefficients", s = bestlam)[1:20, ] lasso.coef lasso.coef[lasso.coef != 0] library(plotmo) plot_glmnet(out) plot_glmnet(out,label=TRUE,s=cv.out$lambda.min) plot_glmnet(out,label=TRUE,s=cv.out$lambda.1se)
library(bestglm) x <- model.matrix(chd ~ ., data=SAheart)[, - 1] y <- SAheart$chd ?cv.glmnet grid <- 10^seq(10, - 2, length = 100)
out_chd_ridge <- cv.glmnet(x, y, alpha = 0, lambda = grid) plot(out_chd_ridge) str(out_chd_ridge) out_chd_ridge bestlam <- out_chd_ridge$lambda.1se bestlam
out <- glmnet(x, y, alpha = 0) predict(out, type = "coefficients", s = bestlam) library(plotmo) plot_glmnet(out,label=TRUE,s=out_chd_ridge$lambda.min) plot_glmnet(out,label=TRUE,s=out_chd_ridge$lambda.1se)
out_chd_lasso <- cv.glmnet(x, y, alpha = 1, lambda = grid) plot(out_chd_lasso) str(out_chd_lasso) out_chd_lasso bestlam <- out_chd_lasso$lambda.1se bestlam
out <- glmnet(x, y, alpha = 1) lasso.coef <- predict(out, type = "coefficients", s = bestlam) lasso.coef library(plotmo) plot_glmnet(out,label=TRUE,s=out_chd_lasso$lambda.min) plot_glmnet(out,label=TRUE,s=out_chd_lasso$lambda.1se)
First problem This formula is highly susceptible to outliers. Even one unusual point in the chosen neighborhoof of x_0 (of width 2h) can arbitrarily distort the prediction. Specifically, we observe that: A small value of h results in high variance in the estimates, as it uses very few observations and thus it is very sensitive to noise. In the limit, as h --> ∞, we get (each point predicts itself), which corresponds to maximum overfitting.
A large value of h results in high bias in the estimates. In the limit, as h --> ∞, we get (constant prediction everywhere), meaning that the prediction is the same accross the sample, regardless of the relaitonship between Y and X.
The issue:
Even when weighted, the local mean remains sensitive to extreme trends. For this reason, we consider the following (generic) multiple regression model: Y = f (X1,... ,Xp) + ϵ This model can be: Parametric: ○ Linear in both regressors and parameters--> f (X1,... ,Xp) = β0 + β1X1 +... + βpXp ○ Linear in the parameters and polynomial in the regressors--> f (X1) = β0 + β1X1 +... + βd Xd 1 Linear in the parameters and in the regressors/their interactions--> f (X1, X2) = β0 + β1X1 + β2X2 + β3X1X
○ Generalized linear--> g(Y ) = f (X1,... , Xp) + ϵ, with g as a linear function (es. logit transformation)
Non-parametric--> f depends on X1,…,Xp, but not through β1,…,βp. The form f is flexible, empirically determined by the data. The function f is smooth, meaning that is has (at least) two continuous and bounded derivatives.
To ssummarize--> Instead of fitting one global regression line , we pick a point , fit a small weighted regression near it. Move to next point and fit another small weighted regression. Repeat. This produces a smooth curve.