Docsity

Big Data and Analytics - notes, Appunti di Analisi Dei Dati

Toggle sidebar
bg1
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.
-
-
Naive Bayes - Gaussian is doing worse than LDA and LR: the predictors are actually correlated.
-
The imbalance between the two classes (0s approx. double than 1s) make specificity much larger than
sensitivity.
-
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.
COMPARING CLASSIFIERS
Wednesday, February 11, 2026
09:43
SECOND 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

Anteprima parziale del testo

Scarica Big Data and Analytics - notes e più Appunti in PDF di Analisi Dei Dati solo su Docsity!

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.

  • Naive Bayes - Gaussian is doing worse than LDA and LR: the predictors are actually correlated. The imbalance between the two classes (0s approx. double than 1s) make specificity much larger than sensitivity.

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.

COMPARING CLASSIFIERS

Wednesday, February 11, 2026 09:

PREDICTION ERROR COSTS

  • C(1|0): cost of classifying a negative as positive.∞∞
  • C(0|1): cost of classifying a positive as negative. We can derive the following classification rule:
  • i = 0 if
  • i = 1 if that is, we allocate a test-set unit to the class returning the highest estimated probability divided by the relative error cost. In other terms, the general classification rule becomes that is, we allocate to class 0 if the ratio between the estimated probabilities to belong to class 1 or class 0 is smaller than the ratio between the cost to classify a negative as positive and a positive as negative, while we allocate to class 0 if the contrary holds. Therefore, it is decisive the cost ratio And we can rewrite everything as If r=1 we obtain the Bayes rule. The general cut-off to classify units is therefore r/1+r. Note that if r - > ∞, missing a negative is infinitely more risky than missing a positive, and thus we tend to classify all the units as negative; if r - > ∞, the viceversa holds. In medical applications (e.g. yi = 1 if an individual dies BECAUSE OF a medicine), the ratio r is close to 0, i.e. we require that P(yi = 1) is close to 0 to certify the absence of risk (class 0). PERFORMANCE PLOTS Cut-off r/ (1+r) is crucial to study the properties of a classifier. In a standard case, the cut-off is 0.5; in many other cases, instead, the ratio r moves the cut-off towards 0 or 1 (the extremes of r 1+r ). Therefore, according to the aim (predicting well both classes or one in specific), it is essential to assess the properties of a classifier as the cut-off varies. The R function performance from package ROCR allows to perform these analyses taking into account several performance measures (including those defined above). The classical ROC (Receiver Operating Characteristic) curve, for instance, plots the specificity in x-axis and the sensitivity in y-axis for all possible thresholds, i.e. the hit rates of negative and positive, respectively. ROC is useful because it shows the trade-off : If you increase sensitivity, you usually increase false positives. You cannot increase both sensitivity and specificity at the same time (except with a perfect model).

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

Confusion matrix and misclassification rate

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:

#Lab: Comparing Classifiers

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)

or by hand:

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")

sensitivity and specificity

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])

ROC curve specificity/sensitivity

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)")

ROC curve false positive rate/true positive rate

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:

  • x-axis = rate of positive predictions
  • y-axis = lift Lift measures improvement over random selection.

Rate of positive predictions/lift

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)")

lift by hand

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")

Cumulative lift by hand

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:

  • n not much larger than p --> lot of variability in the least squares fit (overfitting and poor predictions) p > n --> there is no longer a unique least squares coefficient estimate, variance is infinite so the method cannot be used.

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.

SUBSET SELECTION

We have:

  • Best subset selection
  • Stepwise selection Best subset selection We fit a separate least squares regression for each possible combination of the p predictors and then select the one that is best among all. Although this method finds the BEST OVERALL model, it has computational limitations as it has to fit 2^p models. Thus, this approach becomes computationally infeasible for values of p greater than around 40. In addition to this, the larger p is and consequently the search space, the higher the cance of overfitting and high variance of coefficient estimates.

LINEAR MODEL SELECTION AND

REGULARIZATION

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.

  • Principal component Regression
  • Partial Least squares

Forward and Backward Stepwise Selection

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)

Choosing Among Models Using the Validation-Set Approach and Cross-Validation

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)

The Lasso

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)

Ridge Regression and the Lasso: SAheart

library(bestglm) x <- model.matrix(chd ~ ., data=SAheart)[, - 1] y <- SAheart$chd ?cv.glmnet grid <- 10^seq(10, - 2, length = 100)

Ridge Regression

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)

The Lasso

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:

  • If data are dense around → many observations
  • If data are sparse around → maybe very few (or zero) So the number of observations used changes across the sample. That creates instability. One way to address this issue is to replace the neighborhood [xi − h; xi + h] with the neighborhood [xi − dk (x0); xi + dk (x0)], where dk (x0) is the distance (in euclidean terms) of x_0 from the k-th nearest point to x_0 itself. So instead of fixing the width of the window, we fix the number of points inside the window. In this way, the formula becomes: Which represents the k-nearest neighbors version of the running mean smoother, as it considers, for each x_0, a neighborhood containing a fixed number of k points (beside x_0 itself). Now in dense areas the window is small and is sparse areas the window automatically expands. Thus, variance becomes more stable across the space. Both the previous version and this formula are examples of a local average. When the relationship between Y and X is very irregular, even this last formula may yield erratic predictions (all points have equal weights, but this can be unstable if f(x) is irregular/nearby points are anomalous). However, we can observe that the first ever formula can be expressed as a weighted local mean of the form: Where the function K, called the kernel function, is defined as: Also the second formula can be expressed in this form by setting h = dk (x0). In general, for a generic form of K, this formula is called the NADARAYA-WATSON estimator, or KERNEL SMOOTHER. The choice of the kernel function K allows to reduce the weight in the prediction for points (not too) close to X_0 that exhibit an anomalous value. The efficiency of the kernel impacts (though not dramatically) the accuracy of the estimate. List of most commonly used kernel functions Note: for all kernels, Meaning that it integrates to 1 and is symmetric. This equation with h=1 is known as the uniform or rectangula kernel: It gives equal weight inside the window and zero outside. With , this corresponds to the original running mean. So instead of giving equal weight, we assign weights that decrease with distance

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.

  • Semi-parametric--> Y = β0 + β1X1 + f (X2), thus a combination of the first two. Weighted linear regression (assumes local straight line) Now, suppose we want to approximate point by point the unknown conditional expected value of Y given X=x using a linear funciton of x. Specifically, suppose we want to predict the value Y_0 using a linear function that is valid locally around : Y = β0 + β1( ). This line is valid only near , not globally. This approach is logical because the Taylor Series Expansion of any continuous and differentiable function f(x) in a neighborhood of x_0 is If we knew f(x), we would know that β0=f(x_0) and β1 = f '(x_0). Since f in unknown, we can estimate β0 and β1, similarly to the case of simple regression, by minimizing the weighted sum of squares (instead of ordinary least squares): And we define weights as = The weighted least squares estimator We define the smoothing matrix Wh, an n x n diagonal matrix(stores the kernel weights), such that Wij, h= with i,j = 1,…, n. Consequently, we can write the weighted least squares estimator of the vector β = (β0, β1)′ as β Where Are the design matrix of size n x 2 and the vector n x 1 containing the empirical observations of Y, respectively. X:
  • First column--> intercept
  • Second column--> centered regressor Y--> observed outcomes The 2 x 1 vector is a linear estimator in y (Everything except is fixed once the data and bandwidth are given).
  • The n x 1 vector is a linear predictor in y. The predictor is called
  • running line smoother if the kernel has a fixed bandwidth h point by point, LO(W)NESS (Locally Weighted Scatterplot Smoother) when h varies across pooints (for example, if h = dk (x0), as in k-nearest neighbors).

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.

  • Intercept ≈ value of the function
  • Slope ≈ derivative of the function We fit a small regression line using only points near giving higher weight to closer points