# Import library
  library(corrplot)
## corrplot 0.84 loaded
  library(DT)
  library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
  library(ggplot2)
  library(knitr)
  library(matrixcalc)
  library(stats)

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 μ=σ=(N+1)/2.

  # Random variable X
  N <- round(runif(1, 6, 500))
  X <- runif(10000, min=0, max=N)
  
  #Random variable Y
  Y <- rnorm(10000, (N+1)/2,(N+1)/2)

Probability. Calculate as a minimum the below probabilities a through c. Assume the small letter “x” is estimated as the median of the X variable, and the small letter “y” is estimated as the 1st quartile of the Y variable. Interpret the meaning of all probabilities.

  1. P(X > x | X > y)
  x <- median(X)
  y <- quantile(Y, 0.25)
  sum(X > x & X > y)/sum(X > y)
## [1] 0.5948132
  1. P(X > x, Y > y)
  sum(X > x & Y > y)/10000
## [1] 0.3763
  1. P(X < x | X > y)
  sum(X < x & X > y)/10000
## [1] 0.3406

Investigate whether P(X>x and Y>y)=P(X>x)P(Y>y) by building a table and evaluating the marginal and joint probabilities.

  # We build the table!!
  problemOneTable <- matrix(c(sum(X > x & Y > y), sum(X < x & Y > y), sum(X > x & Y > y) + sum(X < x & Y > y), sum(X > x & Y < y), sum(X < x & Y < y), sum(X > x & Y < y) + sum(X < x & Y < y), sum(X > x & Y > y) + sum(X > x & Y < y), sum(X < x & Y > y) + sum(X < x & Y < y), sum(X > x & Y > y) + sum(X < x & Y > y) + sum(X > x & Y < y) + sum(X < x & Y < y)), nrow=3, ncol = 3)
  colnames(problemOneTable) = c("Y > y", "Y < y", "All")
  rownames(problemOneTable) = c("X > x", "X < x", "All")
  datatable(problemOneTable)

Check to see if independence holds by using Fisher’s Exact Test and the Chi Square Test. What is the difference between the two? Which is most appropriate?

  # Fisher's Exact Test
  fisher.test(problemOneTable, simulate.p.value=TRUE)
## 
##  Fisher's Exact Test for Count Data with simulated p-value (based
##  on 2000 replicates)
## 
## data:  problemOneTable
## p-value = 0.9805
## alternative hypothesis: two.sided
  # Chi Square Test
  chisq.test(problemOneTable, correct=TRUE)
## 
##  Pearson's Chi-squared test
## 
## data:  problemOneTable
## X-squared = 0.36053, df = 4, p-value = 0.9856

Problem 2

Descriptive and Inferential Statistics. Provide univariate descriptive statistics and appropriate plots for the training data set. Provide a scatterplot matrix for at least two of the independent variables and the dependent variable. Derive a correlation matrix for any three quantitative variables in the dataset. Test the hypotheses that the correlations between each pairwise set of variables is 0 and provide an 80% confidence interval. Discuss the meaning of your analysis. Would you be worried about familywise error? Why or why not?

  trainData <- read.csv(file="/Users/suma/Desktop/CUNY SPS - Masters Data Science/DATA 605/house-prices-advanced-regression-techniques/train.csv", header=TRUE, sep=",")

# Display train data
datatable(trainData, options = list(pageLength = 5))
# Summary Statistics
summary(trainData)
##        Id           MSSubClass       MSZoning     LotFrontage    
##  Min.   :   1.0   Min.   : 20.0   C (all):  10   Min.   : 21.00  
##  1st Qu.: 365.8   1st Qu.: 20.0   FV     :  65   1st Qu.: 59.00  
##  Median : 730.5   Median : 50.0   RH     :  16   Median : 69.00  
##  Mean   : 730.5   Mean   : 56.9   RL     :1151   Mean   : 70.05  
##  3rd Qu.:1095.2   3rd Qu.: 70.0   RM     : 218   3rd Qu.: 80.00  
##  Max.   :1460.0   Max.   :190.0                  Max.   :313.00  
##                                                  NA's   :259     
##     LotArea        Street      Alley      LotShape  LandContour
##  Min.   :  1300   Grvl:   6   Grvl:  50   IR1:484   Bnk:  63   
##  1st Qu.:  7554   Pave:1454   Pave:  41   IR2: 41   HLS:  50   
##  Median :  9478               NA's:1369   IR3: 10   Low:  36   
##  Mean   : 10517                           Reg:925   Lvl:1311   
##  3rd Qu.: 11602                                                
##  Max.   :215245                                                
##                                                                
##   Utilities      LotConfig    LandSlope   Neighborhood   Condition1  
##  AllPub:1459   Corner : 263   Gtl:1382   NAmes  :225   Norm   :1260  
##  NoSeWa:   1   CulDSac:  94   Mod:  65   CollgCr:150   Feedr  :  81  
##                FR2    :  47   Sev:  13   OldTown:113   Artery :  48  
##                FR3    :   4              Edwards:100   RRAn   :  26  
##                Inside :1052              Somerst: 86   PosN   :  19  
##                                          Gilbert: 79   RRAe   :  11  
##                                          (Other):707   (Other):  15  
##    Condition2     BldgType      HouseStyle   OverallQual    
##  Norm   :1445   1Fam  :1220   1Story :726   Min.   : 1.000  
##  Feedr  :   6   2fmCon:  31   2Story :445   1st Qu.: 5.000  
##  Artery :   2   Duplex:  52   1.5Fin :154   Median : 6.000  
##  PosN   :   2   Twnhs :  43   SLvl   : 65   Mean   : 6.099  
##  RRNn   :   2   TwnhsE: 114   SFoyer : 37   3rd Qu.: 7.000  
##  PosA   :   1                 1.5Unf : 14   Max.   :10.000  
##  (Other):   2                 (Other): 19                   
##   OverallCond      YearBuilt     YearRemodAdd    RoofStyle   
##  Min.   :1.000   Min.   :1872   Min.   :1950   Flat   :  13  
##  1st Qu.:5.000   1st Qu.:1954   1st Qu.:1967   Gable  :1141  
##  Median :5.000   Median :1973   Median :1994   Gambrel:  11  
##  Mean   :5.575   Mean   :1971   Mean   :1985   Hip    : 286  
##  3rd Qu.:6.000   3rd Qu.:2000   3rd Qu.:2004   Mansard:   7  
##  Max.   :9.000   Max.   :2010   Max.   :2010   Shed   :   2  
##                                                              
##     RoofMatl     Exterior1st   Exterior2nd    MasVnrType    MasVnrArea    
##  CompShg:1434   VinylSd:515   VinylSd:504   BrkCmn : 15   Min.   :   0.0  
##  Tar&Grv:  11   HdBoard:222   MetalSd:214   BrkFace:445   1st Qu.:   0.0  
##  WdShngl:   6   MetalSd:220   HdBoard:207   None   :864   Median :   0.0  
##  WdShake:   5   Wd Sdng:206   Wd Sdng:197   Stone  :128   Mean   : 103.7  
##  ClyTile:   1   Plywood:108   Plywood:142   NA's   :  8   3rd Qu.: 166.0  
##  Membran:   1   CemntBd: 61   CmentBd: 60                 Max.   :1600.0  
##  (Other):   2   (Other):128   (Other):136                 NA's   :8       
##  ExterQual ExterCond  Foundation  BsmtQual   BsmtCond    BsmtExposure
##  Ex: 52    Ex:   3   BrkTil:146   Ex  :121   Fa  :  45   Av  :221    
##  Fa: 14    Fa:  28   CBlock:634   Fa  : 35   Gd  :  65   Gd  :134    
##  Gd:488    Gd: 146   PConc :647   Gd  :618   Po  :   2   Mn  :114    
##  TA:906    Po:   1   Slab  : 24   TA  :649   TA  :1311   No  :953    
##            TA:1282   Stone :  6   NA's: 37   NA's:  37   NA's: 38    
##                      Wood  :  3                                      
##                                                                      
##  BsmtFinType1   BsmtFinSF1     BsmtFinType2   BsmtFinSF2     
##  ALQ :220     Min.   :   0.0   ALQ :  19    Min.   :   0.00  
##  BLQ :148     1st Qu.:   0.0   BLQ :  33    1st Qu.:   0.00  
##  GLQ :418     Median : 383.5   GLQ :  14    Median :   0.00  
##  LwQ : 74     Mean   : 443.6   LwQ :  46    Mean   :  46.55  
##  Rec :133     3rd Qu.: 712.2   Rec :  54    3rd Qu.:   0.00  
##  Unf :430     Max.   :5644.0   Unf :1256    Max.   :1474.00  
##  NA's: 37                      NA's:  38                     
##    BsmtUnfSF       TotalBsmtSF      Heating     HeatingQC CentralAir
##  Min.   :   0.0   Min.   :   0.0   Floor:   1   Ex:741    N:  95    
##  1st Qu.: 223.0   1st Qu.: 795.8   GasA :1428   Fa: 49    Y:1365    
##  Median : 477.5   Median : 991.5   GasW :  18   Gd:241              
##  Mean   : 567.2   Mean   :1057.4   Grav :   7   Po:  1              
##  3rd Qu.: 808.0   3rd Qu.:1298.2   OthW :   2   TA:428              
##  Max.   :2336.0   Max.   :6110.0   Wall :   4                       
##                                                                     
##  Electrical     X1stFlrSF      X2ndFlrSF     LowQualFinSF    
##  FuseA:  94   Min.   : 334   Min.   :   0   Min.   :  0.000  
##  FuseF:  27   1st Qu.: 882   1st Qu.:   0   1st Qu.:  0.000  
##  FuseP:   3   Median :1087   Median :   0   Median :  0.000  
##  Mix  :   1   Mean   :1163   Mean   : 347   Mean   :  5.845  
##  SBrkr:1334   3rd Qu.:1391   3rd Qu.: 728   3rd Qu.:  0.000  
##  NA's :   1   Max.   :4692   Max.   :2065   Max.   :572.000  
##                                                              
##    GrLivArea     BsmtFullBath     BsmtHalfBath        FullBath    
##  Min.   : 334   Min.   :0.0000   Min.   :0.00000   Min.   :0.000  
##  1st Qu.:1130   1st Qu.:0.0000   1st Qu.:0.00000   1st Qu.:1.000  
##  Median :1464   Median :0.0000   Median :0.00000   Median :2.000  
##  Mean   :1515   Mean   :0.4253   Mean   :0.05753   Mean   :1.565  
##  3rd Qu.:1777   3rd Qu.:1.0000   3rd Qu.:0.00000   3rd Qu.:2.000  
##  Max.   :5642   Max.   :3.0000   Max.   :2.00000   Max.   :3.000  
##                                                                   
##     HalfBath       BedroomAbvGr    KitchenAbvGr   KitchenQual
##  Min.   :0.0000   Min.   :0.000   Min.   :0.000   Ex:100     
##  1st Qu.:0.0000   1st Qu.:2.000   1st Qu.:1.000   Fa: 39     
##  Median :0.0000   Median :3.000   Median :1.000   Gd:586     
##  Mean   :0.3829   Mean   :2.866   Mean   :1.047   TA:735     
##  3rd Qu.:1.0000   3rd Qu.:3.000   3rd Qu.:1.000              
##  Max.   :2.0000   Max.   :8.000   Max.   :3.000              
##                                                              
##   TotRmsAbvGrd    Functional    Fireplaces    FireplaceQu   GarageType 
##  Min.   : 2.000   Maj1:  14   Min.   :0.000   Ex  : 24    2Types :  6  
##  1st Qu.: 5.000   Maj2:   5   1st Qu.:0.000   Fa  : 33    Attchd :870  
##  Median : 6.000   Min1:  31   Median :1.000   Gd  :380    Basment: 19  
##  Mean   : 6.518   Min2:  34   Mean   :0.613   Po  : 20    BuiltIn: 88  
##  3rd Qu.: 7.000   Mod :  15   3rd Qu.:1.000   TA  :313    CarPort:  9  
##  Max.   :14.000   Sev :   1   Max.   :3.000   NA's:690    Detchd :387  
##                   Typ :1360                               NA's   : 81  
##   GarageYrBlt   GarageFinish   GarageCars      GarageArea     GarageQual 
##  Min.   :1900   Fin :352     Min.   :0.000   Min.   :   0.0   Ex  :   3  
##  1st Qu.:1961   RFn :422     1st Qu.:1.000   1st Qu.: 334.5   Fa  :  48  
##  Median :1980   Unf :605     Median :2.000   Median : 480.0   Gd  :  14  
##  Mean   :1979   NA's: 81     Mean   :1.767   Mean   : 473.0   Po  :   3  
##  3rd Qu.:2002                3rd Qu.:2.000   3rd Qu.: 576.0   TA  :1311  
##  Max.   :2010                Max.   :4.000   Max.   :1418.0   NA's:  81  
##  NA's   :81                                                              
##  GarageCond  PavedDrive   WoodDeckSF      OpenPorchSF     EnclosedPorch   
##  Ex  :   2   N:  90     Min.   :  0.00   Min.   :  0.00   Min.   :  0.00  
##  Fa  :  35   P:  30     1st Qu.:  0.00   1st Qu.:  0.00   1st Qu.:  0.00  
##  Gd  :   9   Y:1340     Median :  0.00   Median : 25.00   Median :  0.00  
##  Po  :   7              Mean   : 94.24   Mean   : 46.66   Mean   : 21.95  
##  TA  :1326              3rd Qu.:168.00   3rd Qu.: 68.00   3rd Qu.:  0.00  
##  NA's:  81              Max.   :857.00   Max.   :547.00   Max.   :552.00  
##                                                                           
##    X3SsnPorch      ScreenPorch        PoolArea        PoolQC    
##  Min.   :  0.00   Min.   :  0.00   Min.   :  0.000   Ex  :   2  
##  1st Qu.:  0.00   1st Qu.:  0.00   1st Qu.:  0.000   Fa  :   2  
##  Median :  0.00   Median :  0.00   Median :  0.000   Gd  :   3  
##  Mean   :  3.41   Mean   : 15.06   Mean   :  2.759   NA's:1453  
##  3rd Qu.:  0.00   3rd Qu.:  0.00   3rd Qu.:  0.000              
##  Max.   :508.00   Max.   :480.00   Max.   :738.000              
##                                                                 
##    Fence      MiscFeature    MiscVal             MoSold      
##  GdPrv:  59   Gar2:   2   Min.   :    0.00   Min.   : 1.000  
##  GdWo :  54   Othr:   2   1st Qu.:    0.00   1st Qu.: 5.000  
##  MnPrv: 157   Shed:  49   Median :    0.00   Median : 6.000  
##  MnWw :  11   TenC:   1   Mean   :   43.49   Mean   : 6.322  
##  NA's :1179   NA's:1406   3rd Qu.:    0.00   3rd Qu.: 8.000  
##                           Max.   :15500.00   Max.   :12.000  
##                                                              
##      YrSold        SaleType    SaleCondition    SalePrice     
##  Min.   :2006   WD     :1267   Abnorml: 101   Min.   : 34900  
##  1st Qu.:2007   New    : 122   AdjLand:   4   1st Qu.:129975  
##  Median :2008   COD    :  43   Alloca :  12   Median :163000  
##  Mean   :2008   ConLD  :   9   Family :  20   Mean   :180921  
##  3rd Qu.:2009   ConLI  :   5   Normal :1198   3rd Qu.:214000  
##  Max.   :2010   ConLw  :   5   Partial: 125   Max.   :755000  
##                 (Other):   9
# Appropriate plots

# Boxplot 
ggplot(trainData, aes(x=YearBuilt, y=OverallCond, fill=YearBuilt, group=YearBuilt)) + geom_boxplot() + labs(title="Overall Condition vs YearBuilt", x="Year Built", y="Overall Condition")

# Histograms

ggplot(trainData, aes(x=SalePrice)) + geom_histogram(fill="blue") + labs(title="Sale Price", x="Sale Price")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

ggplot(trainData, aes(x=OverallCond, color=LotShape)) +
  geom_histogram(fill="white", alpha=0.5, position="identity") + labs(title = "Overall Condition by LotShape", x = "Overall Condition")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

# Scatterplot

ggplot(trainData, aes(x=YearBuilt, y=SalePrice)) + geom_point() + labs(title="Sale Price vs Year Built Scatter Plot", x="Year Built", y="Sale Price")

# 2 Independent Variables: Lot Frontage and Garage Area, and Dependent Variable Sale Price 
pairs(~SalePrice+LotFrontage+GarageArea,data=trainData, main="Scatterplot Matrix")

Correlation Matrix:

  trainCorrMatrix <- cor(dplyr::select(trainData, GarageArea, BsmtUnfSF, GrLivArea, SalePrice))
  trainCorrMatrix
##            GarageArea BsmtUnfSF GrLivArea SalePrice
## GarageArea  1.0000000 0.1833027 0.4689975 0.6234314
## BsmtUnfSF   0.1833027 1.0000000 0.2402573 0.2144791
## GrLivArea   0.4689975 0.2402573 1.0000000 0.7086245
## SalePrice   0.6234314 0.2144791 0.7086245 1.0000000
  # Correlation Plot - two useful ways to view
  # With Numbers
  corrplot(trainCorrMatrix, method="number")

  # With Colors
  corrplot(trainCorrMatrix, method="color")

Test the hypothesis

We see that all p-values for all three quantitative variables are consistently very small small, under 0.05. Thus, we reject the null hypothesis. Generally though, we know that p-values alone are valid enough to provide accurate predictions. Family wise error <= 1 - (1-alpha)^c. I think Family wise error will be high because there are not enough series of tests done - the more tests that are done, the lower the error.

80% confidence that there is correlation with these two variables between 0.60 and 0.64

  cor.test(trainData$SalePrice,trainData$GarageArea, conf.level = 0.8)
## 
##  Pearson's product-moment correlation
## 
## data:  trainData$SalePrice and trainData$GarageArea
## t = 30.446, df = 1458, p-value < 2.2e-16
## alternative hypothesis: true correlation is not equal to 0
## 80 percent confidence interval:
##  0.6024756 0.6435283
## sample estimates:
##       cor 
## 0.6234314

80% confidence that there is correlation with these two variables between 0.18 and 0.24

  cor.test(trainData$SalePrice,trainData$BsmtUnfSF, conf.level = 0.8)
## 
##  Pearson's product-moment correlation
## 
## data:  trainData$SalePrice and trainData$BsmtUnfSF
## t = 8.3847, df = 1458, p-value < 2.2e-16
## alternative hypothesis: true correlation is not equal to 0
## 80 percent confidence interval:
##  0.1822292 0.2462680
## sample estimates:
##       cor 
## 0.2144791

80% confidence that there is correlation with these two variables between 0.69 and 0.72

  cor.test(trainData$SalePrice,trainData$GrLivArea, conf.level = 0.8)
## 
##  Pearson's product-moment correlation
## 
## data:  trainData$SalePrice and trainData$GrLivArea
## t = 38.348, df = 1458, p-value < 2.2e-16
## alternative hypothesis: true correlation is not equal to 0
## 80 percent confidence interval:
##  0.6915087 0.7249450
## sample estimates:
##       cor 
## 0.7086245

Linear Algebra and Correlation. Invert your correlation matrix from above. (This is known as the precision matrix and contains variance inflation factors on the diagonal.) Multiply the correlation matrix by the precision matrix, and then multiply the precision matrix by the correlation matrix. Conduct LU decomposition on the matrix.

  # Precision Matrix - Invert correlation matrix
  trainPrecisionMatrix <- solve(trainCorrMatrix)

  # Multiply correlation matrix by the precision matrix
  round(trainCorrMatrix %*% trainPrecisionMatrix)
##            GarageArea BsmtUnfSF GrLivArea SalePrice
## GarageArea          1         0         0         0
## BsmtUnfSF           0         1         0         0
## GrLivArea           0         0         1         0
## SalePrice           0         0         0         1
  # Multiply the precisio matrix by the correlation matrix
  round(trainPrecisionMatrix %*% trainCorrMatrix)
##            GarageArea BsmtUnfSF GrLivArea SalePrice
## GarageArea          1         0         0         0
## BsmtUnfSF           0         1         0         0
## GrLivArea           0         0         1         0
## SalePrice           0         0         0         1

LU decomposition on the matrix.

  lu.decomposition(trainCorrMatrix)$U
##      [,1]      [,2]      [,3]      [,4]
## [1,]    1 0.1833027 0.4689975 0.6234314
## [2,]    0 0.9664001 0.1542888 0.1002024
## [3,]    0 0.0000000 0.7554087 0.4002391
## [4,]    0 0.0000000 0.0000000 0.3888845
  lu.decomposition(trainCorrMatrix)$L
##           [,1]      [,2]      [,3] [,4]
## [1,] 1.0000000 0.0000000 0.0000000    0
## [2,] 0.1833027 1.0000000 0.0000000    0
## [3,] 0.4689975 0.1596531 1.0000000    0
## [4,] 0.6234314 0.1036863 0.5298312    1
  lu.decomposition(trainPrecisionMatrix)$U
##          [,1]        [,2]        [,3]        [,4]
## [1,] 1.645523 -0.07849925 -0.07604617 -0.95514586
## [2,] 0.000000  1.06570325 -0.18895578 -0.09467239
## [3,] 0.000000  0.00000000  2.00863169 -1.42336558
## [4,] 0.000000  0.00000000  0.00000000  1.00000000
  lu.decomposition(trainPrecisionMatrix)$L
##             [,1]       [,2]       [,3] [,4]
## [1,]  1.00000000  0.0000000  0.0000000    0
## [2,] -0.04770475  1.0000000  0.0000000    0
## [3,] -0.04621399 -0.1773062  1.0000000    0
## [4,] -0.58045140 -0.0888356 -0.7086245    1

Calculus-Based Probability & Statistics. Many times, it makes sense to fit a closed form distribution to data. Select a variable in the Kaggle.com training dataset that is skewed to the right, shift it so that the minimum value is absolutely above zero if necessary. Then load the MASS package and run fitdistr to fit an exponential probability density function. (See https://stat.ethz.ch/R-manual/R-devel/library/MASS/html/fitdistr.html ). Find the optimal value of λ for this distribution, and then take 1000 samples from this exponential distribution using this value (e.g., rexp(1000, λ)). Plot a histogram and compare it with a histogram of your original variable. Using the exponential pdf, find the 5th and 95th percentiles using the cumulative distribution function (CDF). Also generate a 95% confidence interval from the empirical data, assuming normality. Finally, provide the empirical 5th percentile and 95th percentile of the data. Discuss.

The samples histogram shows a right skewed distribution. Similarly, the GarageArea variable histogram somewhat resembles a right skewed distribution.

  library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
  library(spatstat)
## Loading required package: spatstat.data
## Loading required package: nlme
## 
## Attaching package: 'nlme'
## The following object is masked from 'package:dplyr':
## 
##     collapse
## Loading required package: rpart
## 
## spatstat 1.62-2       (nickname: 'Shape-shifting lizard') 
## For an introduction to spatstat, type 'beginner'
## 
## Attaching package: 'spatstat'
## The following object is masked from 'package:MASS':
## 
##     area
  # Select a variable in the Kaggle.com training dataset that is skewed to the right, shift it so that the minimum value is absolutely above zero if necessary.  
  min <- min(trainData$GarageArea)
  min
## [1] 0
  # run fitdistr to fit an exponential probability density function
  expPDF <- fitdistr(trainData$GarageArea, densfun = "exponential")
  
  # optimal value
  lambda <- expPDF$estimate
  
  # samples histogram
  hist(rexp(1000, lambda), breaks=100, main="Simulation PDF - 1000 Samples")

  # variable histogram
  hist(trainData$GarageArea, breaks=100, main="Garage Area Variable")

  # Using the exponential pdf, find the 5th and 95th percentiles using the cumulative distribution function (CDF)
  quantile(lambda, probs=c(0.05, 0.95))
##          5%         95% 
## 0.002114254 0.002114254
  # generate a 95% confidence interval from the empirical data, assuming normality
  qnorm(0.95, mean(trainData$GarageArea), sd(trainData$GarageArea))
## [1] 824.6578
  # provide the empirical 5th percentile and 95th percentile of the data
  quantile(trainData$GarageArea, probs=c(0.05, 0.95))
##    5%   95% 
##   0.0 850.1

Discuss:
The histograms tend to skew to the right and there is not much of a normal distribution amongst the mean. The simulation somewhat resembles the our variable data’s distribution more and less of a normal distribution. The empirical data percentile and normal distribution percentile were very close.

Modeling. Build some type of multiple regression model and submit your model to the competition board. Provide your complete model summary and results with analysis. Report your Kaggle.com user name and score.

Linear Model:

linearModel <- lm(trainData$SalePrice ~ OverallCond + OverallQual + GarageArea + LotArea + YearBuilt, data=trainData)
linearModel
## 
## Call:
## lm(formula = trainData$SalePrice ~ OverallCond + OverallQual + 
##     GarageArea + LotArea + YearBuilt, data = trainData)
## 
## Coefficients:
## (Intercept)  OverallCond  OverallQual   GarageArea      LotArea  
##  -5.417e+05    3.146e+03    3.480e+04    8.183e+01    1.266e+00  
##   YearBuilt  
##   2.237e+02

Examine the summary: If the line is a good fit, the residuals should be normally distributed arounda mean of zero. Here we have have a median of -24492. A good model would have a median near zero and Min and Max of roughly the same magnitude. Below we have roughly similar magnitudes of Min -307954 and Max 390339. So far this model looks ok. The R^2 value explains 69.94% of the data’s variation. The adjusted R^2 value takes into account the number predictors used in the model, and this value will always be smaller than the R^2 value.

summary(linearModel)
## 
## Call:
## lm(formula = trainData$SalePrice ~ OverallCond + OverallQual + 
##     GarageArea + LotArea + YearBuilt, data = trainData)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -307954  -24492   -4342   16485  390339 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -5.417e+05  1.006e+05  -5.383 8.54e-08 ***
## OverallCond  3.146e+03  1.123e+03   2.801  0.00516 ** 
## OverallQual  3.480e+04  1.115e+03  31.216  < 2e-16 ***
## GarageArea   8.183e+01  6.735e+00  12.150  < 2e-16 ***
## LotArea      1.266e+00  1.169e-01  10.831  < 2e-16 ***
## YearBuilt    2.237e+02  5.150e+01   4.343 1.50e-05 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 43630 on 1454 degrees of freedom
## Multiple R-squared:  0.6994, Adjusted R-squared:  0.6984 
## F-statistic: 676.7 on 5 and 1454 DF,  p-value: < 2.2e-16

Residual Analysis:

Pairwise comparison of the data:

  pairs(trainData$SalePrice ~ OverallCond + OverallQual + GarageArea + LotArea + YearBuilt, data=trainData, gap=0.5)

The Normal Q-Q plot displays the residuals overall following closely to the line, which supports for a good model - but the ends diverge, with heavy tails. The histogram displays a normal looking (Gaussian) distribution centered at 0! This provides supports that our model is valid.

  plot(linearModel, col=c("blue"))

  hist(linearModel$residuals)

Kaggle Submission:
Username: kiwi #2 Score: 0.79716

  knitr::include_graphics("/Users/suma/Desktop/KaggleUsernameScore.png")

  testData <- read.csv(file="/Users/suma/Desktop/CUNY SPS - Masters Data Science/DATA 605/house-prices-advanced-regression-techniques/test.csv", header=TRUE, sep=",")

p <- predict(linearModel, testData)
df <- data.frame(cbind(testData$Id, p))
colnames(df) <- c("Id", "SalePrice")
df <- replace(df, is.na(df),0)
write.csv(df, file="model.csv", row.names = FALSE)