###Problem 1: Using R, generate a random variable X that has 10,000 random uniform numbers from 1 to N, where N can be any number of your choosing greater than or equal to 6. Then generate a random variable Y that has 10,000 random normal numbers with a mean of U=O=(N+1)/2.
max = 6
count = 10000
# Uniform numbers
X = runif(count, 1, max)
hist(X, col = 'red', breaks = 15)
# Normal numbers
Y = rnorm(count, mean = (max+1)/2, sd = (max+1)/2)
hist(Y, col = 'lightblue', breaks = 15)
df = data.frame(cbind(X, Y))
#get all values
df[0:6,1:2]
## X Y
## 1 1.766776 8.108629
## 2 2.586735 9.848315
## 3 5.113112 6.389257
## 4 1.020591 2.407479
## 5 4.936947 2.590854
## 6 1.877105 1.157279
# Get the median of x and the 1st quartile of the Y variable
x = median(X)
y = quantile(Y, 0.25)
prob_1 = (X > x)
probX = (length(prob_1[prob_1 == TRUE])) / length(prob_1)
prob_2 = (X > y)
proby = (length(prob_2[prob_2 == TRUE]))/ length(prob_2)
sprintf("Probability: %s", ((probX * proby))/ proby)
## [1] "Probability: 0.5"
prob_1 = (X > x)
probX = (length(prob_1[prob_1 == TRUE]))/ length(prob_1)
prob_2 = (Y > y)
probY = (length(prob_2[prob_2 == TRUE]))/(length(prob_2))
sprintf("probability: %s", probX * probY)
## [1] "probability: 0.375"
prob_1 = (X < x)
probX = (length(prob_1[prob_1 == TRUE]))/(length(prob_1))
prob_2 = (X > y)
probY = (length(prob_2[prob_2 == TRUE]))/(length(prob_2))
sprintf("probability: %s", ((probX * probX)) / probY)
## [1] "probability: 0.256805341551104"
library(data.table)
prob_1 = (X > x)
probX = (length(prob_1[prob_1 == TRUE]))/(length(prob_1))
prob_2 = (Y > y)
probY = (length(prob_2[prob_2 == TRUE]))/(length(prob_2))
dt = data.table(
id = c("(X>x)","(Y>y)","(X>x)*(Y>y)","(X>x and Y>y)"),
x = c(probX, probY, (probX * probY), (probX * probY)),
y = c(probY, probX, (probX * probY), (probX * probY))
)
dt
## id x y
## 1: (X>x) 0.500 0.750
## 2: (Y>y) 0.750 0.500
## 3: (X>x)*(Y>y) 0.375 0.375
## 4: (X>x and Y>y) 0.375 0.375
# based on this, we can conclude that they are equal.
fisher.test(table(X>x, Y>y))
##
## Fisher's Exact Test for Count Data
##
## data: table(X > x, Y > y)
## p-value = 0.6608
## alternative hypothesis: true odds ratio is not equal to 1
## 95 percent confidence interval:
## 0.8932291 1.0728095
## sample estimates:
## odds ratio
## 0.9788895
chisq.test(table(X>x, Y>y))
##
## Pearson's Chi-squared test with Yates' continuity correction
##
## data: table(X > x, Y > y)
## X-squared = 0.19253, df = 1, p-value = 0.6608
# p-values from both tests are more than 0.05; which means DO NOT reject the null hypothesis and that the 2 variables are independent. Sample size is large at n=10000, therefore the Chi squared test is better.
# load data
training_data = read.csv("C:\\Users\\rhous\\Documents\\College\\Data 605 - Fundamentals of Computational Mathematics\\Data\\train.csv")
# plot linear regression model
plot(training_data$GrLivArea, training_data$SalePrice, main = "Living Area V Sale Price", xlab = "Above Groud Living area", ylab = "Sale Price")
linear_model = lm(training_data$SalePrice ~ training_data$GrLivArea)
summary(linear_model)
##
## Call:
## lm(formula = training_data$SalePrice ~ training_data$GrLivArea)
##
## Residuals:
## Min 1Q Median 3Q Max
## -462999 -29800 -1124 21957 339832
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 18569.026 4480.755 4.144 3.61e-05 ***
## training_data$GrLivArea 107.130 2.794 38.348 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 56070 on 1458 degrees of freedom
## Multiple R-squared: 0.5021, Adjusted R-squared: 0.5018
## F-statistic: 1471 on 1 and 1458 DF, p-value: < 2.2e-16
# residual analysis to evaluate model quality
plot(fitted(linear_model, resid(linear_model)))
qqnorm(resid(linear_model))
qqline(resid(linear_model))
library(Hmisc)
## Warning: package 'Hmisc' was built under R version 4.0.5
## Loading required package: lattice
## Loading required package: survival
## Loading required package: Formula
## Warning: package 'Formula' was built under R version 4.0.3
## Loading required package: ggplot2
##
## Attaching package: 'Hmisc'
## The following objects are masked from 'package:base':
##
## format.pval, units
library(corrplot)
## Warning: package 'corrplot' was built under R version 4.0.5
## corrplot 0.88 loaded
linear_model = lm(training_data$SalePrice ~ training_data$GarageArea + training_data$LotArea)
summary(linear_model)
##
## Call:
## lm(formula = training_data$SalePrice ~ training_data$GarageArea +
## training_data$LotArea)
##
## Residuals:
## Min 1Q Median 3Q Max
## -296384 -31984 -4911 24604 482522
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 6.322e+04 4.016e+03 15.742 < 2e-16 ***
## training_data$GarageArea 2.212e+02 7.587e+00 29.151 < 2e-16 ***
## training_data$LotArea 1.245e+00 1.625e-01 7.663 3.29e-14 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 60940 on 1457 degrees of freedom
## Multiple R-squared: 0.4124, Adjusted R-squared: 0.4115
## F-statistic: 511.2 on 2 and 1457 DF, p-value: < 2.2e-16
# subset data with selected columns
training_subset = training_data[,c("GarageArea", "LotArea", "SalePrice")]
# scatterplot / correlation matrix
training_subset.cor = cor(training_subset)
training_subset.rcorr = rcorr(as.matrix(training_subset))
training_subset.coeff = training_subset.rcorr$r
training_subset.p = training_subset.rcorr$P
training_subset.coeff
## GarageArea LotArea SalePrice
## GarageArea 1.0000000 0.1804028 0.6234314
## LotArea 0.1804028 1.0000000 0.2638434
## SalePrice 0.6234314 0.2638434 1.0000000
training_subset.p
## GarageArea LotArea SalePrice
## GarageArea NA 3.802736e-12 0
## LotArea 3.802736e-12 NA 0
## SalePrice 0.000000e+00 0.000000e+00 NA
# visualizing the correlation matrix
corrplot(training_subset.cor)
Hypothesis test for Pearson’s r:
Null hypothesis H₀: ⍴ = 0 x and y are not correlated.
Alternative hypothesis Hₐ: ⍴ <0 (one-tail test in the negative direction) or ⍴ >0 (one-tail test in the positive direction) or ⍴≠0 (two-tail test in both direction)
Familywise error (FWER): Probability of getting at least one false conclusion when testing multiple hypotheses. Can happen as we test the correlation for a series of variables. There are methods for control and detection of FWER. Choices of methods should be chosen carefully for various analysis.
# convert correlation matrix
Cor_Matrix = data.matrix(training_subset.coeff, rownames.force = NA)
# Invert the correlation matrix
Pre_Matrix = solve(Cor_Matrix)
# multiplying matrices
c = Cor_Matrix %*% Pre_Matrix
p = Pre_Matrix %*% Cor_Matrix
# determine U through row operation, and build L matrix
A <- matrix(
Cor_Matrix,
nrow = 3,
ncol = 3,
byrow = TRUE
)
L = matrix(
c(1, 0, 0,
NA, 1, 0,
NA, NA, 1
),
nrow = 3,
ncol = 3,
byrow = TRUE
)
L21 = A[2,1] / A[1,1]
A[2,] = -A[2,] + A[1,] * L21
L31 = A[3,1] / A[1,1]
A[3,] = A[3,] - A[1,] * L31
L32 = -A[3,2] / A[2,2]
A[3,] = A[3,] + A[2,] * L32
L[2,1] = -L21
L[3,1] = L31
L[3,2] = -L32
L
## [,1] [,2] [,3]
## [1,] 1.0000000 0.0000000 0
## [2,] -0.1804028 1.0000000 0
## [3,] 0.6234314 -0.1564668 1
library(fitdistrplus)
## Warning: package 'fitdistrplus' was built under R version 4.0.5
## Loading required package: MASS
# select & visualized right-skewed varialbe
hist_A = hist(training_data$MSSubClass, breaks = 30)
# fit exponential prob. density function
fitdistr(training_data$MSSubClass, "exponential")
## rate
## 0.0175755387
## (0.0004599729)
# generate exponential distribution
exp = rexp(1000, rate = 0.0175755387)
hist_B = hist(exp, breaks = 30)
# compare two histograms
plot(hist_B, col = "green")
plot(hist_A, col = "red", add = T)
# 5th and 95th percentile
quantile(exp, c(0.05, 0.95))
## 5% 95%
## 2.877114 165.265630
# generate confidence interval
ci = qt(0.975, df =length(training_data$MSSubClass)-1) * sd(training_data$MSSubClass) / sqrt(length(training_data$MSSubClass)) #calculate error for the mean
mean(training_data$MSSubClass) - ci # left side
## [1] 54.72567
mean(training_data$MSSubClass) + ci # right side
## [1] 59.06885
#5th and 95th percentile
quantile(training_data$MSSubClass, c(0.05, 0.95))
## 5% 95%
## 20 160
Control variables: LotArea TotalBsmtSF TotRmsAbvGrd GarageArea Experimental variable: SalePrice
# Clean data
training_data.lm = lm(training_data$SalePrice ~ log(training_data$LotArea) + sqrt(training_data$TotalBsmtSF)+ sqrt(training_data$GarageArea) + training_data$TotRmsAbvGrd )
# remove TotRmsAbGrd
training_data.lm = update(training_data.lm, .~. - training_data$TotRmsAbvGrd)
summary(training_data.lm)
##
## Call:
## lm(formula = training_data$SalePrice ~ log(training_data$LotArea) +
## sqrt(training_data$TotalBsmtSF) + sqrt(training_data$GarageArea))
##
## Residuals:
## Min 1Q Median 3Q Max
## -325689 -37253 -7010 29180 449082
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -278544.2 26942.8 -10.338 <2e-16 ***
## log(training_data$LotArea) 27162.2 3133.6 8.668 <2e-16 ***
## sqrt(training_data$TotalBsmtSF) 3802.5 217.5 17.482 <2e-16 ***
## sqrt(training_data$GarageArea) 4420.5 260.6 16.964 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 57980 on 1456 degrees of freedom
## Multiple R-squared: 0.4684, Adjusted R-squared: 0.4673
## F-statistic: 427.7 on 3 and 1456 DF, p-value: < 2.2e-16
# residuals
plot(fitted(training_data.lm), resid(training_data.lm))
qqline(resid(training_data.lm))
qqnorm(resid(training_data.lm))
Based on the risidulas plot, I think that a non-linear model would be better fitted. I would fix this by transforming one of the variablesm creating a non linear model
# Attempt to fix the model by mutating a variable
new_data = lm(log(training_data$SalePrice) ~ log(training_data$LotArea) + sqrt(training_data$TotalBsmtSF) + training_data$TotRmsAbvGrd + sqrt(training_data$GarageArea))
summary(new_data)
##
## Call:
## lm(formula = log(training_data$SalePrice) ~ log(training_data$LotArea) +
## sqrt(training_data$TotalBsmtSF) + training_data$TotRmsAbvGrd +
## sqrt(training_data$GarageArea))
##
## Residuals:
## Min 1Q Median 3Q Max
## -1.8121 -0.1211 0.0072 0.1533 0.8284
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 9.9326501 0.1144193 86.809 < 2e-16 ***
## log(training_data$LotArea) 0.0583310 0.0137781 4.234 2.44e-05 ***
## sqrt(training_data$TotalBsmtSF) 0.0179309 0.0009205 19.480 < 2e-16 ***
## training_data$TotRmsAbvGrd 0.0799949 0.0043196 18.519 < 2e-16 ***
## sqrt(training_data$GarageArea) 0.0227166 0.0011132 20.407 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.2445 on 1455 degrees of freedom
## Multiple R-squared: 0.6264, Adjusted R-squared: 0.6254
## F-statistic: 609.9 on 4 and 1455 DF, p-value: < 2.2e-16
new_data = update(training_data.lm, .~. - train$TotRmsAbvGrd)
summary(new_data)
##
## Call:
## lm(formula = training_data$SalePrice ~ log(training_data$LotArea) +
## sqrt(training_data$TotalBsmtSF) + sqrt(training_data$GarageArea))
##
## Residuals:
## Min 1Q Median 3Q Max
## -325689 -37253 -7010 29180 449082
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -278544.2 26942.8 -10.338 <2e-16 ***
## log(training_data$LotArea) 27162.2 3133.6 8.668 <2e-16 ***
## sqrt(training_data$TotalBsmtSF) 3802.5 217.5 17.482 <2e-16 ***
## sqrt(training_data$GarageArea) 4420.5 260.6 16.964 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 57980 on 1456 degrees of freedom
## Multiple R-squared: 0.4684, Adjusted R-squared: 0.4673
## F-statistic: 427.7 on 3 and 1456 DF, p-value: < 2.2e-16
plot(fitted(new_data), resid(new_data))
qqnorm(resid(new_data))
qqline(resid(new_data))
Load Test data
test = read.csv("C:\\Users\\rhous\\Desktop\\data\\test.csv", header = F)
# compute predicted outputs
predict.test = predict(new_data, newdata = test)
# compare actual vs. predicted price
final = plot(log(training_data$SalePrice),predict.test)
abline(lm(log(training_data$SalePrice) ~ predict.test))
# back-transform SalePrice
predictedPrice = exp(predict.test)
write.csv(predictedPrice, file = "C:\\Users\\rhous\\Desktop\\data\\Prices.csv", row.names = F)
#Name: Brett Dav
#Score: 0.40878