Given:
\(y = (y_1, . . . , y_n)\) and \(\hat{y} = (\hat{y_1}, . . . , \hat{y_m})\) are the OLS fit in multiple regression.
To Prove:
\(R^2\) is equal to the empirical squared correlation between \(y\) and \(\hat{y}\)
Proof:
We know that sum of residuals \(\sum\limits_{i=1}^{n} (y_i - \hat{y_i}) = 0\)
\(\implies \sum\limits_{i=1}^{n}y_i - \sum\limits_{i=1}^{n}\hat{y_i} = 0\)
\(\implies \sum\limits_{i=1}^{n}y_i = \sum\limits_{i=1}^{n}\hat{y_i}\)
Now on subracting \(n\bar{y}\) on both sides
\(\implies \sum\limits_{i=1}^{n}y_i - n\bar{y} = \sum\limits_{i=1}^{n}\hat{y_i} - n\bar{y}\)
\(\implies \sum\limits_{i=1}^{n}(y_i - \bar{y}) = \sum\limits_{i=1}^{n}(\hat{y_i} - \bar{y})\)
We know that empirical squared correlation between \(y\) and \(\hat{y}\) is
\(Cor(y,\bar{y_1})\) \(= \frac{\sum\limits_{i=1}^{n}(y_i - \bar{y})(\hat{y_i}-\bar{y})}{\sqrt{\sum\limits_{i=1}^{n}{(y_i - \bar{y})}^2\sum\limits_{i=1}^{n}{(\hat{y_i}-\bar{y})}^2 }}\)
\(\implies Cor(y,\bar{y_1}) = \frac{\sum\limits_{i=1}^{n}(\hat{y_i} - \bar{y})(\hat{y_i}-\bar{y})}{\sqrt{\sum\limits_{i=1}^{n}{(y_i - \bar{y})}^2\sum\limits_{i=1}^{n}{(\hat{y_i}-\bar{y})}^2}}\)
Since \(\sum\limits_{i=1}^{n}(y_i - \bar{y}) = \sum\limits_{i=1}^{n}(\hat{y_i} - \bar{y})\)
Now squaring on both the sides, we get
\((Cor(y,\bar{y_1}))^2 = \frac{((\sum\limits_{i=1}^{n}{(y_i - \bar{y})}^2))^2}{\sum\limits_{i=1}^{n}{(y_i - \bar{y})}^2\sum\limits_{i=1}^{n}{(\hat{y_i}-\bar{y})}^2}\)
\((Cor(y,\bar{y_1}))^2 = \frac{\sum\limits_{i=1}^{n}{(\hat{y_i} - \bar{y})}^2}{\sum\limits_{i=1}^{n}{(y_i-\bar{y})}^2}\) \(----->(1)\)
We know that coefficient of determination \(R^2\) is given by \(\frac{SS_{reg}}{SS_Y}\)
\(R^2 = \frac{SS_{reg}}{SS_Y} = \frac{SS_{Y}-SSE}{SS_y} = \frac{\sum\limits_{i=1}^{n}{(\hat{y_i} - \bar{y})}^2}{\sum\limits_{i=1}^{n}{(y_i-\bar{y})}^2}\). \(----->(2)\)
From (1) and (2), we can see that \(R^2 = (Cor(y,\hat{y}))^2\)
Hence proved
(10mm)
Given:One predictor, x, uniformly distributed in [−1, 1], and x the response, y, is generated as \(y ∼ N (3 + 0.5x, \sigma2)\), with \(\sigma = 0.5\).
We are generating a sample of size \(n \epsilon {50, 100, 200}\) from it, and then using that sample to fit the model by least squares.This is then repeated for \(N = 1000\) times.(There are 3 settings, one for each n.)
Then we are plotting histograms for intercepts and slopes for each sample size.Here we see that all of them are normal compared to the theoretical normal and further the contour plots and surface plots are being plotted for intercepts and slopes for each sample size. We can see that the least squares coefficients follow joint normal distribution for all sample sizes.
##a]
#loading libraries
library(rcompanion)
#Number of simulations
N <- 1000
#sample size
n <- c(50, 100, 200)
# Initializing the data frames to store intercepts and slopes
all_intercepts <- data.frame(matrix(ncol = 3, nrow = 0))
all_slopes <- data.frame(matrix(ncol = 3, nrow = 0))
# Simulating N times
for (j in 1:N) {
intercepts <- c()
slopes <- c()
# Sample size
for (i in n) {
x <- runif(i, -1, 1)
y <- 3 + 0.5 * x + rnorm(i, mean = 0, sd = 0.5)
# Fitting the model and Extracting coefficients (intercept and slope)
model <- lm(y ~ x)
beta <- coef(model)
intercepts <- c(intercepts, beta[1])
slopes <- c(slopes, beta[2])
}
# Appending the results to data frames for each simulation
all_intercepts <- rbind(all_intercepts, intercepts)
all_slopes <- rbind(all_slopes, slopes)
}
# Naming the columns of data frames with sample sizes
names(all_intercepts) <- c('n=50', 'n=100', 'n=200')
names(all_slopes) <- c('n=50', 'n=100', 'n=200')
# Plotting histograms for intercepts and slopes for each sample size (marginally normal)
for (i in c('n=50', 'n=100', 'n=200')) {
par(mfrow = c(1, 2))
plotNormalHistogram(all_intercepts[, i], main = paste("Intercept for", i), xlab = 'Intercept')
plotNormalHistogram(all_slopes[, i], main = paste("Slope for", i), xlab = 'Slope')
}
# Plotting contour plots and surface plots for intercepts and slopes for each sample size (joint normal)
for (i in c('n=50', 'n=100', 'n=200')) {
par(mfrow = c(1, 2))
x = cut(all_intercepts[,i], 20)
y = cut(all_slopes[,i], 20)
z = table(x, y)
contour(z, main = i, xlab = "Intercept", ylab = "Slope")
persp(z, main = i, xlab = "Intercept", ylab = "Slope", theta=-30, phi=25,expand=0.6)
}
Repeating the above procedure, now with errors that have the t-distribution with \(k \epsilon {2, 5, 10, 20}\) degrees of freedom.Plots for least square intercept and slopes have been plotted, where we can see that each of them are converging into normal distribution as the degree of freedom increases.
Then we are plotting histograms for intercepts and slopes and also the contour plots and surface plots for intercepts and slopes.We can observe that the spread of the distribution decreases with the increase in sample size.
When the sample size was small, t-distribution had larger spread than the Normal distribution. As the sample size increased, slope and intercept both are converged into Normal distribution
##b]
#Errors that have the t-distribution with k ∈ {2, 5, 10, 20} degrees of freedom
t <- c(2,5,10,20,50)
# Initializing the data frames to store intercepts and slopes
all_intercepts <- data.frame(matrix(ncol = 12, nrow = 0))
all_slopes <- data.frame(matrix(ncol = 12, nrow = 0))
# Simulating N times
for (j in 1:N) {
intercepts <- c()
slopes <- c()
# Sample size
for (i in n) {
x <- runif(i, -1, 1)
for (k in t) {
y <- 3 + 0.5 * x + rt(i,k)
# Fitting the model and Extracting coefficients (intercept and slope)
model <- lm(y ~ x)
beta <- coef(model)
intercepts <- c(intercepts, beta[1])
slopes <- c(slopes, beta[2])
}
}
# Appending the results to data frames for each simulation
all_intercepts <- rbind(all_intercepts, intercepts)
all_slopes <- rbind(all_slopes, slopes)
}
#naming intercepts and slopes w.r.t sample sizes
t_col <- c()
for (i in n){
for (k in t) {
col_name = paste("n=",as.character(i)," t=",as.character(k))
t_col <- c(t_col,col_name)
}
}
names(all_intercepts) <- t_col
names(all_slopes) <- t_col
# Plotting histograms for intercepts and slopes for each sample size (marginally normal)
for (i in t_col){
par(mfrow=c(1,2))
plotNormalHistogram(all_intercepts[,i],main=paste("Intercept for",i),xlab='Intercept')
plotNormalHistogram(all_slopes[,i],main=paste("Slope for",i),xlab='Slope')
}
# Plotting contour plots and surface plots for intercepts and slopes for each sample size (joint normal)
for (i in t_col){
par(mfrow = c(1, 2))
x = cut(all_intercepts[,i], 20)
y = cut(all_slopes[,i], 20)
z = table(x, y)
contour(z, main = i, xlab = "Intercept", ylab = "Slope")
persp(z, main = i, xlab = "Intercept", ylab = "Slope", theta=-30, phi=25,expand=0.6)
}
We loaded the “Boston” dataset from “MASS” Library. Based on the Structure of the dataset we to found the discrete predictor variables values to omit.The columns chas and rad are integers therefore their values are discrete in nature, hence were dropped.
# Installing MASS from the local tarball file
install.packages("https://cran.rstudio.com/bin/macosx/big-sur-arm64/contrib/4.3/MASS_7.3-60.0.1.tgz", repos = NULL, type = "source")
library(MASS)
Data <- Boston
head(Data)
#Omitting the 'chas' and 'rad' variables
str(Boston)
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
my_Data <- subset(Boston, select = -c(chas, rad))
head(my_Data)
#Fitting the linear model with medv as respons
model <- lm(medv ~ ., data = my_Data)
Checking the standard assumptions of a linear regression model (mean zero, homoscedasticity, and normality)
Mean:The mean of the residuals, is very close to 0, thus the model is doing a good job of capturing the systematic patterns in the data.It has an unbiased estimate of the true relationship between the predictors and the response variable.
Homoscedasticity:From residuals against fitted values plot we can see that the mean residual doesn’t change with the fitted values but the spread of the residuals is increasing as the fitted values changes.Therefore the spread is not constant.Thus, the model is heteroscedastic in nature.
Normality:In the Q-Q plot, the points do not closely follow the reference line, it suggests that normality is not there.Also the histogram of residuals shows a non-symmetric shape,ie that is peak of the distribution is on the left side, and the distribution extends more to the right thereby suggesting non-normality.
#Checking the standard assumptions of a linear regression model (mean zero, homoscedasticity, and normality)
#Checking whether mean of residuals is equal to zero
summary(model)
##
## Call:
## lm(formula = medv ~ ., data = my_Data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -13.3315 -2.8771 -0.6792 1.6858 27.4744
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2.970e+01 5.051e+00 5.879 7.59e-09 ***
## crim -7.010e-02 3.269e-02 -2.144 0.032482 *
## zn 3.989e-02 1.409e-02 2.831 0.004835 **
## indus -4.198e-02 6.080e-02 -0.691 0.490195
## nox -1.458e+01 3.899e+00 -3.740 0.000206 ***
## rm 4.188e+00 4.255e-01 9.843 < 2e-16 ***
## age -1.868e-03 1.359e-02 -0.137 0.890696
## dis -1.503e+00 2.059e-01 -7.301 1.15e-12 ***
## tax 8.334e-04 2.386e-03 0.349 0.727038
## ptratio -8.738e-01 1.323e-01 -6.607 1.02e-10 ***
## black 8.843e-03 2.763e-03 3.200 0.001461 **
## lstat -5.267e-01 5.224e-02 -10.083 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 4.899 on 494 degrees of freedom
## Multiple R-squared: 0.7225, Adjusted R-squared: 0.7163
## F-statistic: 116.9 on 11 and 494 DF, p-value: < 2.2e-16
mean(model$residuals)
## [1] 2.106352e-16
#mean of the residuals
#Plotting the mean of the residuals and the residuals
plot(model$residuals, ylab = 'Residuals',col = 'blue')
abline(h = mean(model$residuals), lty = 10, col = 'red')
#Verifying the homoscedasticity
# Plotting residuals against fitted values
plot(model, which = 1)
#Verifying the Normality Assumption
# Q-Q plot of residuals
qqnorm(model$residuals)
qqline(model$residuals)
# Histogram of residuals
hist(model$residuals, main = "Histogram of Residuals", xlab = "Residuals")
Checking for outliers in the predictor. The plot clearly identifies the Hat values exceeding the threshold (dotted line) that identify as the outliers in the predictor.The green point in the plot corresponds to the observation with the maximum hat value
#Checking for outliers in predictors
plot(hatvalues(model), type='h', col="blue", ylab="Hat Values", main="Hat values")
p = 12; n = 506
# p = number of predictor variables, n =number of observations in the dataset
abline(h = 2*(p+1)/n, lty=2, col = 'red')
points(which.max(hatvalues(model)), hatvalues(model)[which.max(hatvalues(model))], col = 'green', pch = 16)
Checking for outliers in response From the plot we can observe that the values by studentized residuals that lie above the threshold have more leverage and are potential outliers in predictors.
#Checking outliers via externally studentized residuals
#Calculating externally studentized residuals
studentized_residuals <- rstudent(model)
#Plotting externally studentized residuals
plot(abs(studentized_residuals), type = "h", ylab = "Externally Studentized Residuals (in absolute value)", main = "Outliers in Response")
abline(h = qt(0.95, n - p - 2), col = 'red')
#Identifying and labelling potential outliers
potential_outliers <- which(abs(studentized_residuals) > qt(0.95, n - p - 2))
points(potential_outliers, abs(studentized_residuals[potential_outliers]), col = 'green', pch = 16)
#Printing the observation index where the maximum studentized residual occurs
max_studentized_residual_index <- which.max(abs(studentized_residuals))
print(paste("Max studentized residual outlier occurs at:", as.character(max_studentized_residual_index)))
## [1] "Max studentized residual outlier occurs at: 369"
Checking for influential observations
Cook’s distance provides us a measure of how much the model’s predicted values (fitted values) would change if a particular observation is excluded. High Cook’s distance values indicate observations that have a substantial impact on the model. From the graph, the values that lie above the threshold have more leverage and are potential outliers in predictors.Points with Cook’s distance exceeding a threshold are considered influential.
# Calculating Cook's distance
cook_values <- cooks.distance(model)
# Plotting Cook's distance
plot(cook_values, type = "h", main = "Cook's Distance")
abline(h = 4 / (n - p - 1), col = 'red', lty = 2)
# Identifying and labelling influential observations
influential_observations <- which(cook_values > 4 / (n - p - 1))
points(influential_observations, cook_values[influential_observations], col = 'green', pch = 16)
text(influential_observations, cook_values[influential_observations], labels = influential_observations, pos = 2, col = 'green')
Checking for multicollinearity
Pairwise correlations b/w predictors: We are first plotting correlations between all the predictors pairwise correlations between predictors and visualizing the correlation matrix.High correlations suggest potential multicollinearity.
Using Variance inflation factor: The variance inflation factor can estimate how much the variance of a regression coefficient is inflated due to multicollinearity. As few indices vif’s lie in between 1.0-5.0 there is multicollinearity between the predictors.
Using Condition Indices: If any index’s condition index is in between 20-30 then there is a presence of multicollinearity and if condition index is greater than 30 then that index has strong multi- collinearity.We can observe the condition index greater than 30 for few indices which proves the multicollinearity.
#Loading the car package
install.packages("https://cran.rstudio.com/bin/macosx/big-sur-arm64/contrib/4.3/car_3.1-2.tgz", repos = NULL, type = "source")
library(car)
## Loading required package: carData
#Checking for multicollinearity via pairwise correlations b/w predictors
round( cor(my_Data[, -2]) , 2)
## crim indus nox rm age dis tax ptratio black lstat medv
## crim 1.00 0.41 0.42 -0.22 0.35 -0.38 0.58 0.29 -0.39 0.46 -0.39
## indus 0.41 1.00 0.76 -0.39 0.64 -0.71 0.72 0.38 -0.36 0.60 -0.48
## nox 0.42 0.76 1.00 -0.30 0.73 -0.77 0.67 0.19 -0.38 0.59 -0.43
## rm -0.22 -0.39 -0.30 1.00 -0.24 0.21 -0.29 -0.36 0.13 -0.61 0.70
## age 0.35 0.64 0.73 -0.24 1.00 -0.75 0.51 0.26 -0.27 0.60 -0.38
## dis -0.38 -0.71 -0.77 0.21 -0.75 1.00 -0.53 -0.23 0.29 -0.50 0.25
## tax 0.58 0.72 0.67 -0.29 0.51 -0.53 1.00 0.46 -0.44 0.54 -0.47
## ptratio 0.29 0.38 0.19 -0.36 0.26 -0.23 0.46 1.00 -0.18 0.37 -0.51
## black -0.39 -0.36 -0.38 0.13 -0.27 0.29 -0.44 -0.18 1.00 -0.37 0.33
## lstat 0.46 0.60 0.59 -0.61 0.60 -0.50 0.54 0.37 -0.37 1.00 -0.74
## medv -0.39 -0.48 -0.43 0.70 -0.38 0.25 -0.47 -0.51 0.33 -0.74 1.00
install.packages("https://cran.rstudio.com/bin/macosx/big-sur-arm64/contrib/4.3/ellipse_0.5.0.tgz", repos = NULL, type = "source")
library(ellipse)
##
## Attaching package: 'ellipse'
## The following object is masked from 'package:car':
##
## ellipse
## The following object is masked from 'package:graphics':
##
## pairs
require(ellipse)
plotcorr(cor(my_Data[, -2]))
#Checking for multicollinearity via variance inflation factors (VIF)
plot(vif(model), type='h', col=4, lwd=3)
abline(h = 10, lty=2)
#Checking for multicollinearity via condition indices # correlation matrix for the predictors
C = cor(my_Data[, -2])
# eigenvalues
L = eigen(C)
# condition indices
conditional_indices = max(L$val)/L$val
plot(conditional_indices, type='h', col=4, lwd=3) # threshold for suspects
abline(h = 1000, lty=2)
The assignment was divided among the team members.Katta Naga Shivani Reddy solved the first and second problem, providing the numerical experiment, R code, and result interpretation. The third problem was solved by Saloni Patnaik who also created the LaTeX document and markup file.