-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhouse4_output.txt
1801 lines (1428 loc) · 62.7 KB
/
house4_output.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
> sink(con, append=TRUE, type="message")
> # This will echo all input and not truncate 150+ character lines...
> source("house4.R", echo=TRUE, max.deparse.length=10000)
> library(plyr)
> library(caret)
Loading required package: lattice
Loading required package: ggplot2
> library(Metrics)
> # PRELIMINARIES I. FUNCTIONS
>
> # Function to recode levels to numeric in specified order and add ".n" to name
> recode <- function( df, var, lev ) {
+ to <- as.character( 0:(length(lev)-1) )
+ newvar <- as.numeric( as.character( mapvalues(df[[var]], from=lev, to=to) ) )
+ newname <- paste0(var,".n")
+ df <- cbind( df, newvar )
+ names(df)[ncol(df)] <- newname
+ df[var] <- NULL
+ df
+ }
> # Function to do initial data cleaning
> cleanData <- function( df ) {
+ # Convert pseudo-numeric "type of dwelling" identifier to a factor
+ df$MSSubClass <- as.factor( df$MSSubClass )
+
+ # Deal with numeric variables that have missing values
+ df$LotFrontage = as.character( df$LotFrontage )
+ df$HasLotFrontage = ifelse( df$LotFrontage=="NA", 0, 1 )
+ df$LotFrontage = ifelse( df$LotFrontage=="NA", "0", df$LotFrontage )
+ df$LotFrontage = as.numeric( df$LotFrontage )
+
+ df$MasVnrArea = as.character( df$MasVnrArea )
+ df$HasMasVnr = ifelse( df$MasVnrArea=="NA", 0, 1 )
+ df$MasVnrArea = ifelse( df$MasVnrArea=="NA", "0", df$MasVnrArea )
+ df$MasVnrArea = as.numeric( df$MasVnrArea )
+
+ df$GarageYrBlt = as.character( df$GarageYrBlt )
+ df$HasGarageYr = ifelse( df$GarageYrBlt=="NA", 0, 1 )
+ df$GarageYrBlt = ifelse( df$GarageYrBlt=="NA", "0", df$GarageYrBlt )
+ df$GarageYrBlt = as.numeric( df$GarageYrBlt )
+
+ # Dummy for "has basement"
+ df$HasBasement = ifelse( df$BsmtQual=="NA", 0, 1 )
+
+ # Recode ordered factors as pseudo-continuous numerical variables
+ qualcats = c( "Po", "Fa", "TA", "Gd", "Ex" )
+ qualcats2 = c( "NA", qualcats )
+ funcats = c( "Sal", "Sev", "Maj2", "Maj1", "Mod", "Min2", "Min1", "Typ" )
+ basecats = c( "NA", "Unf", "LwQ", "Rec", "BLQ", "ALQ", "GLQ" )
+ df <- recode( df, "ExterCond", qualcats )
+ df <- recode( df, "ExterQual", qualcats )
+ df <- recode( df, "HeatingQC", qualcats )
+ df <- recode( df, "KitchenQual", qualcats )
+ df <- recode( df, "BsmtCond", qualcats2 )
+ df <- recode( df, "FireplaceQu", qualcats2 )
+ df <- recode( df, "GarageQual", qualcats2 )
+ df <- recode( df, "GarageCond", qualcats2 )
+ df <- recode( df, "Functional", funcats )
+ df <- recode( df, "BsmtFinType1", basecats )
+ df <- recode( df, "BsmtFinType2", basecats )
+ df <- recode( df, "PavedDrive", c("N", "P", "Y" ) )
+ df <- recode( df, "Utilities", c("ELO", "NoSeWa", "NoSewr", "AllPub" ) )
+ df <- recode( df, "LotShape", c("IR3", "IR2", "IR1", "Reg" ) )
+ df <- recode( df, "BsmtExposure", c("NA", "No", "Mn", "Av", "Gd" ) )
+ df <- recode( df, "PoolQC", c("NA", "Fa", "TA", "Gd", "Ex" ) )
+ df <- recode( df, "GarageFinish", c("NA", "Unf", "RFn", "Fin" ) )
+
+ # BsmtHeight needs special treatment, since it's really a categorized continuous variable
+ from <- c("NA", "Po", "Fa", "TA", "Gd", "Ex" )
+ to <- c("0", "50", "75", "85", "95", "120" )
+ df$BsmtHeight <- as.numeric( mapvalues(df$BsmtQual, from=from, to=to) )
+ df$BsmtQual <- NULL
+
+ # Fix numeric variables that will get read as factors in test set
+ df$BsmtFinSF1 = as.numeric( as.character( df$BsmtFinSF1 ) )
+ df$BsmtFinSF1[is.na(df$BsmtFinSF1)] = mean(df$BsmtFinSF1, na.rm=TRUE)
+ df$BsmtFinSF2 = as.numeric( as.character( df$BsmtFinSF2 ) )
+ df$BsmtFinSF2[is.na(df$BsmtFinSF2)] = mean(df$BsmtFinSF2, na.rm=TRUE)
+ df$BsmtUnfSF = as.numeric( as.character( df$BsmtUnfSF ) )
+ df$BsmtUnfSF[is.na(df$BsmtUnfSF)] = mean(df$BsmtUnfSF, na.rm=TRUE)
+ df$BsmtFullBath = as.numeric( as.character( df$BsmtFullBath ) )
+ df$BsmtFullBath[is.na(df$BsmtFullBath)] = mean(df$BsmtFullBath, na.rm=TRUE)
+ df$BsmtHalfBath = as.numeric( as.character( df$BsmtHalfBath ) )
+ df$BsmtHalfBath[is.na(df$BsmtHalfBath)] = mean(df$BsmtHalfBath, na.rm=TRUE)
+ df$GarageCars = as.numeric( as.character( df$GarageCars ) )
+ df$GarageCars[is.na(df$GarageCars)] = mean(df$GarageCars, na.rm=TRUE)
+ df$GarageArea = as.numeric( as.character( df$GarageArea ) )
+ df$GarageArea[is.na(df$GarageArea)] = mean(df$GarageArea, na.rm=TRUE)
+
+ # Fix missing values
+ df$Utilities.n[is.na(df$Utilities.n)] = 3 # Modal value
+ df$Functional.n[is.na(df$Functional.n)] = 7 # Modal value
+ df$KitchenQual.n[is.na(df$KitchenQual.n)] = 3 # Modal value
+ df$Electrical[df$Electrical=="NA"] = as.factor("SBrkr")
+
+ # Take logarithms where appropriate
+ df$X1stFlrSF = log( df$X1stFlrSF )
+ names(df)[names(df)=="X1stFlrSF"] <- "Ln1stFlrSF"
+ df$GrLivArea = log( df$GrLivArea )
+ names(df)[names(df)=="GrLivArea"] <- "LnLivArea"
+ df$OFHEO = log( df$OFHEO )
+ names(df)[names(df)=="OFHEO"] <- "LnOFHEO"
+
+ # Normalize dependant variable (if this is a training set)
+ if (!is.null(df$SalePrice)) {
+ df$SalePrice = log( df$SalePrice ) - df$LnOFHEO
+ names(df)[names(df)=="SalePrice"] <- "RelPrice"
+ }
+
+ df
+ }
> # Function to get coefficients to be used to make factor continuous given baseline model
> getCoeffs <- function( df, basemodel, factor ) {
+ mod <- paste0( basemodel, "+", factor, "-1" )
+ lm <- lm(formula=mod, data=df)
+ fnames <- grep( factor, names(lm$coefficients), fixed=TRUE )
+ lm$coefficients[fnames]
+ }
> # Function to make factor continuous (given dummy coefficients) and add "_r" to name
> makeContinuous <- function( df, factor, coeffs ) {
+ outvar <- 0*(1:nrow(df))
+ fact <- df[[factor]]
+ for ( n in levels(fact) ) {
+ outvar[fact==n] <- coeffs[paste0(factor,n)]
+ }
+ df <- cbind( df, outvar )
+ names(df)[ncol(df)] <- paste0( factor, "_r" )
+ df[factor] <- NULL
+ df
+ }
> # Function to convert integer variable to above/below dummies for each of its values
> dummify <- function( df, var ) {
+ v <- df[[var]]
+ vals <- sort( unique(v) )
+ n <- length(vals) - 1
+ if (n==0) { return (NULL) }
+ for (i in vals[1:n]) {
+ newname <- paste0(var,".gt",as.character(i))
+ newvar <- as.numeric(v > i)
+ df <- cbind( df, newvar )
+ names(df)[ncol(df)] <- newname
+ }
+ df
+ }
> # Function to add to model any of the created dummies that have positive coefficients
> addDummiesToModel <- function( df, var, mod ) {
+ vars <- c()
+ for (name in names(df)) {
+ if ( grepl(paste0(var,".gt"), name, fixed=TRUE) ) {
+ vars <- c(vars,name)
+ }
+ }
+ newmod <- paste0( mod, " + ", paste(vars, collapse=" + ") )
+ lmfull <- lm( formula=newmod, data=df )
+ count = length(vars)
+ for (var in vars) {
+ if ( is.na( lmfull$coefficients[var] ) ) {
+ print( paste0( "Variable ", var, " removed due to rank deficiency"))
+ newmod <- gsub( paste0(" + ",var), "", newmod, fixed=TRUE )
+ count = count - 1
+ }
+ else if ( lmfull$coefficients[var] < 0 ) {
+ newmod <- gsub( paste0(" + ",var), "", newmod, fixed=TRUE )
+ count = count - 1
+ }
+ }
+ if (count==0) { return(NULL) }
+ newmod
+ }
> # Function to get coefficients to be used to make ordered variable continuous
> # (given a model that includes any dummies found to have positive coefficients)
> getOrderedCoeffs <- function( df, newmod, var ) {
+ lm1 <- lm(formula=newmod, data=df)
+ fnames <- grep( var, names(lm1$coefficients), fixed=TRUE )
+ coeffs <- lm1$coefficients[fnames]
+ names(coeffs) <- gsub( paste0(var,".gt"), "", names(coeffs), fixed=TRUE )
+ coeffs
+ }
> # Function to make ordered variable continuous (given coefficients) and add "_r" to name
> makeOrderedContinuous <- function( df, var, coeffs ) {
+ outvar <- 0*(1:nrow(df))
+ v <- df[[var]]
+ outvar <- 0
+ for (n in names(coeffs)) {
+ outvar <- outvar + ifelse( v>as.numeric(n), coeffs[n], 0 )
+ }
+ df <- cbind( df, outvar )
+ names(df)[ncol(df)] <- paste0( var, "_r" )
+ df[var] <- NULL
+ df
+ }
> # Function to make coefficients to be used to make ordered variable continuous
> makeOrderedCoeffs <- function( df, mod, var ) {
+ datemp <- dummify( df, var )
+ if (is.null(datemp)) {
+ print( paste0("dummify returned NULL for ", var) )
+ return(NULL)
+ }
+ modtemp <- addDummiesToModel( datemp, var, mod )
+ if (is.null(modtemp)) {
+ print("addDummiesToModel returned NULL")
+ return(NULL)
+ }
+ coeffs <- getOrderedCoeffs( datemp, modtemp, var )
+ if (is.null(coeffs)) {
+ print("getOrderedCoeffs returned NULL")
+ return(NULL)
+ }
+ coeffs
+ }
> # Function to do final data cleaning after variables have been processed into features
> finalCleaning <- function( df ) {
+
+ # Fix numeric variables with missing values in test and/or validation set
+ df$MSSubClass_r[is.na(df$MSSubClass_r)] = mean(df$MSSubClass_r, na.rm=TRUE)
+ df$Exterior1st_r[is.na(df$Exterior1st_r)] = mean(df$Exterior1st_r, na.rm=TRUE)
+ df$Exterior2nd_r[is.na(df$Exterior2nd_r)] = mean(df$Exterior2nd_r, na.rm=TRUE)
+ df$Condition2_r[is.na(df$Condition2_r)] = mean(df$Condition2_r, na.rm=TRUE)
+
+ # Collapse sale condition categories
+ salecon <- as.character(df$SaleCondition)
+ df$SaleMisc <- ifelse( salecon=="Family" | salecon=="Partial", 1, 0 )
+ df$SaleAbnormal <- ifelse( salecon=="Abnorml", 1, 0 )
+ df$SaleCondition <- NULL
+
+ # Collapse sale type categories
+ st <- as.character(df$SaleType)
+ con <- c("Con", "ConLw", "ConLI", "ConLD")
+ wd <- c("WD", "CWD", "VWD")
+ df$Contract <- ifelse( st %in% con, 1, 0 )
+ df$WrntyDeed <- ifelse( st %in% wd, 1, 0 )
+ df$NewSale <- ifelse( st=="New", 1, 0 )
+ df$SaleType <- NULL
+
+ # Only one kind of building type seems to be different
+ df$SingleFam <- ifelse( as.character(df$BldgType)=="1Fam", 1, 0 )
+ df$BldgType <- NULL
+
+ # It matters if you have a garage, but this is captured by "HasGarageYear"
+ # It also matters if it's a real garage or just a car port, so:
+ df$CarPort <- ifelse( as.character(df$GarageType)=="CarPort", 1, 0 )
+ df$GarageType <- NULL
+
+ # Residential vs. nonresidential seems to be only relevant aspect of zoning
+ zo <- as.character(df$MSZoning)
+ res_zone <- c( "FV", "RH", "RL", "RP", "RM" )
+ df$Residential <- ifelse( zo %in% res_zone, 1, 0 )
+ df$MSZoning <- NULL
+
+ # Get rid of RoofMatl. It is an overfit dummy for one case.
+ # Earlier analysis showed all levels got OLS coefficients that were
+ # very significantly different from zero but not different from one another.
+ # "ClyTile" was the omitted category and was only one case.
+ df$RoofMatl <- NULL
+
+ # Get rid of MiscFeature. Per earlier analysis, it's a mess. Don't want to deal with it.
+ df$MiscFeature <- NULL
+
+ # Factors that earlier analyses didn't like and too much of a pain in the neck to keep
+ df$Fence <- NULL
+ df$RoofStyle <- NULL
+ df$Heating <- NULL
+
+ # I didn't see any residual seasonal pattern, so:
+ df$MoSold <- NULL
+
+ # These nonlinearitiesn seem to matter
+ df$LotFrontage2 <- df$LotFrontage^2
+ df$SinceRemod <- df$YrSold - df$YearRemodAdd
+ df$SinceRemod2 <- df$SinceRemod^2
+ df$YrSold <- NULL
+ df$YearRemodAdd <- NULL
+ df$BsmtFinSF1sq <- df$BsmtFinSF1^2
+
+ # The following turn out to be redundant. But may want to bring them back later.
+ df$TotalBsmtSF <- NULL
+ df$HasMasVnr <- NULL
+ df$KitchenAbvGr_r <- NULL
+ df$GarageCond.n_r <- NULL
+
+ df
+ }
> # PRELIMINARIES II. EXTRA DATA (from FHFA website)
>
> # FHFA (formerly OFHEO) House Price Index for West North Central region
> OFHEO = c(209.32, 210.23, 211.68, 212.71, 214.37, 215.37,
+ 216.37, 216.22, 215.45, 214.48, 214.73, 211.92,
+ 212.23, 214.99, 215.82, 216.99, 217.89, 218.28,
+ 218.69, 216.78, 217.27, 212.78, 212.72, 211.6,
+ 208.58, 208.62, 209.68, 210.28, 209.78, 210.87,
+ 209.68, 208.77, 206.08, 206.07, 200.51, 201.47,
+ 201.78, 204.24, 201.05, 203.8, 205.1, 206.55,
+ 205.27, 204.63, 203.47, 204.22, 202.74, 199.78,
+ 196.35, 197.64, 198.89, 202.13, 204.25, 204.61,
+ 200.13, 201.76, 198.03, 197.87, 195.11, 193.46 )
> Year = c( 2006, 2006, 2006, 2006, 2006, 2006,
+ 2006, 2006, 2006, 2006, 2006, 2006,
+ 2007, 2007, 2007, 2007, 2007, 2007,
+ 2007, 2007, 2007, 2007, 2007, 2007,
+ 2008, 2008, 2008, 2008, 2008, 2008,
+ 2008, 2008, 2008, 2008, 2008, 2008,
+ 2009, 2009, 2009, 2009, 2009, 2009,
+ 2009, 2009, 2009, 2009, 2009, 2009,
+ 2010, 2010, 2010, 2010, 2010, 2010,
+ 2010, 2010, 2010, 2010, 2010, 2010 )
> Month = c( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 )
> ofheo <- data.frame( Month, Year, OFHEO )
> # ON TO THE MAIN EVENT
>
> # READ IN AND CLEAN DATA
>
> rawdata <- read.csv("train.csv", na.strings="")
> data1 <- merge(rawdata, ofheo, by.x=c("YrSold","MoSold"), by.y=c("Year","Month"))
> data1 <- cleanData( data1 )
The following `from` values were not present in `x`: Po
The following `from` values were not present in `x`: Po
The following `from` values were not present in `x`: Ex
The following `from` values were not present in `x`: Sal
The following `from` values were not present in `x`: ELO, NoSewr
The following `from` values were not present in `x`: TA
The following `from` values were not present in `x`: Po
> # DIVIDE DATA INTO SUBSESTS
>
> # "train1" (60%) for primary training
> # "validate" (20%) for cross-validation
> # "testing" (20%) for initial testing
>
> set.seed(999)
> inTrain <- createDataPartition(y=data1$RelPrice, p=0.8, list=FALSE)
> training <- data1[inTrain,]
> testing <- data1[-inTrain,]
> inTrain1 <- createDataPartition(y=training$RelPrice, p=0.75, list=FALSE)
> train1 <- training[inTrain1,]
> validate <- training[-inTrain1,]
> # RUN BASELINE LINEAR MODEL AND USE TO RECODE CATEGORICAL VARIABLES
>
> # Make working copy of data
> da <- train1
> # Baseline model
> basemod <- "RelPrice ~ LnOFHEO + Ln1stFlrSF + LnLivArea + OverallQual + OverallCond"
> # Make factors continuous and add continuous versions to baseline model one by one
> factors <- c( "Neighborhood", "MSSubClass", "Condition1", "Exterior1st", "Condition2",
+ "Exterior2nd", "LotConfig", "Foundation")
> mod <- basemod
> coeffs <- list()
> i <- 0
> for (f in factors) {
+ co <- getCoeffs( da, mod, f )
+ i <- i + 1
+ coeffs[[i]] <- co
+ names(coeffs)[i] <- f
+ da <- makeContinuous( da, f, co )
+ mod <- paste0( mod, "+", f, "_r" )
+ }
> # Show output of augmented model
> print( summary( lm( formula=mod, data=da ) ) )
Call:
lm(formula = mod, data = da)
Residuals:
Min 1Q Median 3Q Max
-0.93322 -0.07945 0.00024 0.07383 0.50662
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -2.065e-13 9.642e-01 0.000 1.00000
LnOFHEO -8.445e-01 1.728e-01 -4.888 1.21e-06 ***
Ln1stFlrSF 1.703e-01 1.991e-02 8.551 < 2e-16 ***
LnLivArea 4.096e-01 2.044e-02 20.039 < 2e-16 ***
OverallQual 8.743e-02 5.701e-03 15.336 < 2e-16 ***
OverallCond 5.024e-02 4.563e-03 11.011 < 2e-16 ***
Neighborhood_r 7.546e-01 4.965e-02 15.198 < 2e-16 ***
MSSubClass_r 8.574e-01 1.383e-01 6.201 8.69e-10 ***
Condition1_r 1.109e+00 2.190e-01 5.063 5.05e-07 ***
Exterior1st_r 8.873e-01 1.518e-01 5.847 7.11e-09 ***
Condition2_r 1.016e+00 2.289e-01 4.440 1.02e-05 ***
Exterior2nd_r 9.085e-01 3.704e-01 2.453 0.01438 *
LotConfig_r 1.092e+00 4.203e-01 2.598 0.00954 **
Foundation_r 1.000e+00 2.871e-01 3.483 0.00052 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.1429 on 862 degrees of freedom
Multiple R-squared: 0.8732, Adjusted R-squared: 0.8713
F-statistic: 456.5 on 13 and 862 DF, p-value: < 2.2e-16
> # CONVERT ORDERED CATEGORICAL AND INTEGER VARIABLES TO CONTINUOUS
>
> # Make "OverallQual" continuous.
> mod <- gsub( "+ OverallQual", "", mod, fixed=TRUE ) # Delete from model
> orderedCoeffs <- list() # List that will contain coefficients for all ordered variables
> i <- 1
> co <- makeOrderedCoeffs( da, mod, "OverallQual" )
> orderedCoeffs[[i]] <- co
> names(orderedCoeffs)[[i]] <- "OverallQual"
> da <- makeOrderedContinuous( da, "OverallQual", co )
> mod <- paste0( mod, " + OverallQual_r" ) # Add conintuous version to model
> # Make the rest of the ordered variables continuous, and save coefficients used.
> mod <- gsub( "+ OverallCond", "", mod, fixed=TRUE ) # Remove OverallCond from model
> ordered <- c("OverallCond", "Functional.n", "Fireplaces", "KitchenQual.n",
+ "BsmtExposure.n", "HeatingQC.n", "Utilities.n", "FullBath",
+ "HalfBath", "GarageCars", "BsmtFullBath", "GarageQual.n",
+ "BsmtFinType1.n", "PavedDrive.n", "BsmtCond.n", "GarageCond.n",
+ "FireplaceQu.n", "ExterQual.n", "TotRmsAbvGrd", "LotShape.n",
+ "BsmtHalfBath", "PoolQC.n", "BsmtFinType2.n", "ExterCond.n",
+ "BedroomAbvGr", "BsmtHeight", "KitchenAbvGr", "GarageFinish.n")
> varsToDrop <- c()
> for ( var in ordered ) {
+ co <- makeOrderedCoeffs( da, mod, var )
+ if ( is.null(co) ) {
+ varsToDrop <- c(varsToDrop, var)
+ da[var] <- NULL
+ }
+ else {
+ da <- makeOrderedContinuous( da, var, co )
+ mod <- paste0( mod, " + ", var, "_r")
+ i <- i + 1
+ orderedCoeffs[[i]] <- co
+ names(orderedCoeffs)[[i]] <- var
+ }
+ }
[1] "dummify returned NULL for Utilities.n"
[1] "Variable GarageFinish.n.gt0 removed due to rank deficiency"
> # MAKE THE DATA NICE
>
> da = finalCleaning( da )
> # INSPECT OUTPUT OF FULL MODEL
>
> regmodel = lm( formula="RelPrice ~ .", data=da )
> print( summary( regmodel ) )
Call:
lm(formula = "RelPrice ~ .", data = da)
Residuals:
Min 1Q Median 3Q Max
-0.61087 -0.05362 -0.00056 0.05735 0.39144
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 3.006e+00 1.062e+00 2.830 0.004774 **
Id -6.605e-07 8.832e-06 -0.075 0.940400
LotFrontage 1.509e-03 8.149e-04 1.852 0.064398 .
LotArea 1.680e-06 6.387e-07 2.631 0.008687 **
StreetPave 4.972e-02 6.319e-02 0.787 0.431623
AlleyNA 1.844e-02 2.314e-02 0.797 0.425630
AlleyPave 4.828e-02 3.208e-02 1.505 0.132771
LandContourHLS 5.904e-02 2.845e-02 2.075 0.038321 *
LandContourLow 4.816e-02 3.688e-02 1.306 0.191967
LandContourLvl 4.208e-02 2.218e-02 1.898 0.058127 .
LandSlopeMod 3.299e-02 2.248e-02 1.468 0.142630
LandSlopeSev -1.608e-01 5.257e-02 -3.059 0.002296 **
HouseStyle1.5Unf 1.525e-02 4.576e-02 0.333 0.739077
HouseStyle1Story -9.260e-03 2.544e-02 -0.364 0.715956
HouseStyle2.5Fin 1.541e-02 9.610e-02 0.160 0.872674
HouseStyle2.5Unf -1.691e-02 4.622e-02 -0.366 0.714509
HouseStyle2Story -1.261e-02 1.873e-02 -0.674 0.500823
HouseStyleSFoyer -1.773e-03 3.666e-02 -0.048 0.961452
HouseStyleSLvl -5.055e-03 2.895e-02 -0.175 0.861434
YearBuilt 4.011e-04 3.869e-04 1.037 0.300172
MasVnrTypeBrkFace 3.313e-03 3.947e-02 0.084 0.933131
MasVnrTypeNA -2.679e-02 6.285e-02 -0.426 0.670067
MasVnrTypeNone 1.261e-02 3.981e-02 0.317 0.751515
MasVnrTypeStone 1.135e-02 4.151e-02 0.273 0.784668
MasVnrArea 4.663e-05 3.329e-05 1.401 0.161715
BsmtFinSF1 1.808e-04 3.733e-05 4.842 1.55e-06 ***
BsmtFinSF2 1.047e-04 3.349e-05 3.128 0.001825 **
BsmtUnfSF 4.175e-05 2.547e-05 1.639 0.101531
CentralAirY 2.809e-02 1.969e-02 1.427 0.154037
ElectricalFuseF 7.406e-03 3.289e-02 0.225 0.821893
ElectricalFuseP 2.627e-02 8.674e-02 0.303 0.762097
ElectricalMix 2.089e-01 1.231e-01 1.697 0.090061 .
ElectricalSBrkr -1.262e-02 1.621e-02 -0.778 0.436585
Ln1stFlrSF 5.728e-02 5.416e-02 1.058 0.290553
X2ndFlrSF -1.681e-05 3.945e-05 -0.426 0.670127
LowQualFinSF 1.510e-04 1.158e-04 1.305 0.192379
LnLivArea 3.509e-01 6.458e-02 5.433 7.40e-08 ***
GarageYrBlt -2.766e-04 3.243e-04 -0.853 0.393919
GarageArea 9.026e-05 3.941e-05 2.290 0.022281 *
WoodDeckSF 1.144e-04 3.466e-05 3.302 0.001003 **
OpenPorchSF 1.489e-04 6.767e-05 2.200 0.028069 *
EnclosedPorch 1.499e-04 7.091e-05 2.114 0.034843 *
X3SsnPorch 3.410e-04 1.273e-04 2.678 0.007556 **
ScreenPorch 2.387e-04 6.747e-05 3.538 0.000427 ***
PoolArea -1.176e-05 1.074e-04 -0.110 0.912783
MiscVal -3.575e-06 5.906e-06 -0.605 0.545157
LnOFHEO -9.799e-01 1.351e-01 -7.255 9.73e-13 ***
HasLotFrontage -8.413e-02 3.553e-02 -2.368 0.018145 *
HasGarageYr 5.379e-01 6.317e-01 0.852 0.394737
HasBasement -6.042e-02 5.543e-02 -1.090 0.276037
Neighborhood_r 4.231e-01 4.792e-02 8.830 < 2e-16 ***
MSSubClass_r 2.592e-02 1.986e-01 0.131 0.896203
Condition1_r 1.350e+00 1.747e-01 7.731 3.29e-14 ***
Exterior1st_r 5.007e-01 1.222e-01 4.098 4.59e-05 ***
Condition2_r 1.232e+00 1.788e-01 6.889 1.16e-11 ***
Exterior2nd_r 2.816e-01 3.010e-01 0.935 0.349862
LotConfig_r 8.800e-01 3.405e-01 2.585 0.009932 **
Foundation_r 7.576e-01 2.852e-01 2.656 0.008067 **
OverallQual_r 6.473e-01 5.970e-02 10.842 < 2e-16 ***
OverallCond_r 6.856e-01 8.595e-02 7.976 5.38e-15 ***
Functional.n_r 1.075e+00 1.506e-01 7.135 2.22e-12 ***
Fireplaces_r 7.131e-01 2.438e-01 2.925 0.003543 **
KitchenQual.n_r 2.183e-01 1.744e-01 1.251 0.211225
BsmtExposure.n_r 5.792e-01 1.814e-01 3.193 0.001462 **
HeatingQC.n_r 8.475e-01 2.809e-01 3.018 0.002630 **
FullBath_r 6.087e-01 3.246e-01 1.875 0.061129 .
HalfBath_r 7.264e-01 2.775e-01 2.618 0.009023 **
GarageCars_r 5.436e-01 2.036e-01 2.669 0.007760 **
BsmtFullBath_r 3.384e-01 1.889e-01 1.791 0.073685 .
GarageQual.n_r 6.567e-01 2.569e-01 2.556 0.010766 *
BsmtFinType1.n_r 3.826e-01 2.712e-01 1.411 0.158717
PavedDrive.n_r 1.209e+00 3.419e+00 0.354 0.723716
BsmtCond.n_r 1.301e+00 2.460e+00 0.529 0.597144
FireplaceQu.n_r 3.182e-01 6.621e-01 0.481 0.630993
ExterQual.n_r 8.626e-01 6.316e-01 1.366 0.172407
TotRmsAbvGrd_r 4.253e-01 3.010e-01 1.413 0.158043
LotShape.n_r -4.126e-02 4.207e-01 -0.098 0.921902
BsmtHalfBath_r 3.159e-01 1.086e+00 0.291 0.771292
PoolQC.n_r 2.067e+00 6.735e-01 3.069 0.002221 **
BsmtFinType2.n_r 1.863e+00 8.691e-01 2.144 0.032341 *
ExterCond.n_r 1.070e+00 1.099e+00 0.974 0.330471
BedroomAbvGr_r 6.838e-01 4.817e-01 1.420 0.156147
BsmtHeight_r 7.020e-01 8.446e-01 0.831 0.406140
GarageFinish.n_r 1.333e+00 1.283e+00 1.039 0.299062
SaleMisc 8.602e-03 2.844e-02 0.302 0.762374
SaleAbnormal -4.481e-02 1.633e-02 -2.745 0.006190 **
Contract 8.673e-02 3.971e-02 2.184 0.029233 *
WrntyDeed 1.332e-02 2.222e-02 0.600 0.548983
NewSale 7.665e-02 3.902e-02 1.964 0.049856 *
SingleFam 3.767e-02 1.851e-02 2.036 0.042131 *
CarPort -1.893e-02 4.243e-02 -0.446 0.655552
Residential 2.010e-01 4.998e-02 4.021 6.35e-05 ***
LotFrontage2 -5.834e-06 4.736e-06 -1.232 0.218411
SinceRemod -1.845e-03 1.040e-03 -1.775 0.076322 .
SinceRemod2 1.389e-05 1.680e-05 0.826 0.408816
BsmtFinSF1sq -6.091e-08 1.208e-08 -5.044 5.68e-07 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.1047 on 780 degrees of freedom
Multiple R-squared: 0.9384, Adjusted R-squared: 0.9308
F-statistic: 125 on 95 and 780 DF, p-value: < 2.2e-16
> # FOR A QUICK CHECK, APPLY TRANSFORMAITONS TO CROSS-VALIDATION SET AND PREDICT
>
> # Make working copy of data
> da2 <- validate
> # Process it
> for (f in factors) {
+ co <- coeffs[[f]]
+ da2 <- makeContinuous( da2, f, co )
+ }
> co <- orderedCoeffs[["OverallQual"]]
> da2 <- makeOrderedContinuous( da2, "OverallQual", co )
> for ( var in ordered ) {
+ if ( var %in% varsToDrop ) {
+ da2[var] <- NULL
+ }
+ else {
+ da2 <- makeOrderedContinuous( da2, var, orderedCoeffs[[var]] )
+ }
+ }
> da2 <- finalCleaning( da2 )
> # Make predictions
> prediction <- predict(regmodel, da2, type="response")
> # Fill in missing values
> baselm <- lm(formula=basemod, data=train1)
> basepred <- predict( baselm, validate, type="response")
> prediction[is.na(prediction)] <- basepred[is.na(prediction)]
> # RMSE
> rmse(da2$RelPrice,prediction)
[1] 0.0968051
> # AND HOW ABOUT A QUICKIE VISUAL REGULARIZATION
>
> fo = "RelPrice ~ LotFrontage + LotArea + Alley + LandContour + LandSlope "
> fo = paste0(fo, "+ YearBuilt + MasVnrArea + BsmtFinSF1 + BsmtFinSF2 ")
> fo = paste0(fo, "+ BsmtUnfSF + CentralAir + Ln1stFlrSF + X2ndFlrSF ")
> fo = paste0(fo, "+ LowQualFinSF + LnLivArea + GarageArea + WoodDeckSF ")
> fo = paste0(fo, "+ OpenPorchSF + EnclosedPorch + X3SsnPorch + ScreenPorch ")
> fo = paste0(fo, "+ LnOFHEO + HasLotFrontage + Neighborhood_r + Condition1_r ")
> fo = paste0(fo, "+ Exterior1st_r + Condition2_r + Exterior2nd_r + LotConfig_r ")
> fo = paste0(fo, "+ Foundation_r + OverallQual_r + OverallCond_r + Functional.n_r ")
> fo = paste0(fo, "+ Fireplaces_r + KitchenQual.n_r + BsmtExposure.n_r + HeatingQC.n_r ")
> fo = paste0(fo, "+ FullBath_r + HalfBath_r + GarageCars_r + BsmtFullBath_r ")
> fo = paste0(fo, "+ GarageQual.n_r + BsmtFinType1.n_r + ExterQual.n_r + TotRmsAbvGrd_r ")
> fo = paste0(fo, "+ PoolQC.n_r + BsmtFinType2.n_r + ExterCond.n_r + SaleAbnormal ")
> fo = paste0(fo, "+ Contract + NewSale + SingleFam + Residential + LotFrontage2 ")
> fo = paste0(fo, "+ SinceRemod + SinceRemod2 + BsmtFinSF1sq ")
> mymodel = lm( formula=fo, data=da )
> prediction <- predict(mymodel, da2, type="response")
> prediction[is.na(prediction)] <- basepred[is.na(prediction)]
> rmse(da2$RelPrice,prediction)
[1] 0.09660811
> # RUN FITS AND FIND BEST COMBO OF PREDICTORS
>
> # Set up for multiple cores
> library(parallel)
> library(doParallel)
Loading required package: foreach
foreach: simple, scalable parallel programming from Revolution Analytics
Use Revolution R for scalability, fault tolerance and more.
http://www.revolutionanalytics.com
Loading required package: iterators
> cluster <- makeCluster(detectCores() - 1) # convention to leave 1 core for OS
> registerDoParallel(cluster)
> # Fit the models
> modelnames = c("lars2", # Least Angle Regression
+ "cubist", # Cubist Regression Tree
+ "glmboost", # Boosted Generalized Linear Model
+ "glmnet", # Generalized linear model via penalized maximum likelihood
+ "lasso", # Least absolute shrinkage & selection operator (L1 penalty)
+ "bayesglm", # Bayesian Generalized Linear Model
+ "ridge", # Ridge Regression (L2 penalty)
+ "xgbLinear", # eXtreme Gradient Boosting, linear method
+ "nnls", # Non-Negative Least Squares
+ "icr", # Independent Component Regression
+ "gbm") # Stochastic Gradient Boosting
> modelfits = list()
> for (m in modelnames) {
+ print ( paste("Training model:", m) )
+ fit <- train( as.formula(fo), data=da, method=m )
+ modelfits = c(modelfits, list(fit))
+ }
[1] "Training model: lars2"
Loading required package: lars
Loaded lars 1.2
[1] "Training model: cubist"
Loading required package: Cubist
[1] "Training model: glmboost"
Loading required package: mboost
Loading required package: stabs
This is mboost 2.7-0. See ‘package?mboost’ and ‘news(package = "mboost")’
for a complete list of changes.
Attaching package: ‘mboost’
The following object is masked from ‘package:ggplot2’:
%+%
[1] "Training model: glmnet"
Loading required package: glmnet
Loading required package: Matrix
Loaded glmnet 2.0-5
Attaching package: ‘glmnet’
The following object is masked from ‘package:Metrics’:
auc
[1] "Training model: lasso"
Loading required package: elasticnet
[1] "Training model: bayesglm"
Loading required package: arm
Loading required package: MASS
Loading required package: lme4
arm (Version 1.9-3, built: 2016-11-21)
Working directory is /Users/andy/Documents/workspace/learning/courses/courseraScale/houseProj/ames
[1] "Training model: ridge"
[1] "Training model: xgbLinear"
Loading required package: xgboost
[1] "Training model: nnls"
Loading required package: nnls
[1] "Training model: icr"
Loading required package: fastICA
[1] "Training model: gbm"
Loading required package: gbm
Loading required package: survival
Attaching package: ‘survival’
The following object is masked from ‘package:caret’:
cluster
Loading required package: splines
Loaded gbm 2.1.1
Iter TrainDeviance ValidDeviance StepSize Improve
1 0.1397 nan 0.1000 0.0187
2 0.1239 nan 0.1000 0.0152
3 0.1098 nan 0.1000 0.0125
4 0.0992 nan 0.1000 0.0109
5 0.0898 nan 0.1000 0.0089
6 0.0814 nan 0.1000 0.0071
7 0.0740 nan 0.1000 0.0065
8 0.0678 nan 0.1000 0.0058
9 0.0622 nan 0.1000 0.0052
10 0.0575 nan 0.1000 0.0042
20 0.0315 nan 0.1000 0.0010
40 0.0176 nan 0.1000 0.0001
60 0.0136 nan 0.1000 0.0000
80 0.0118 nan 0.1000 -0.0001
100 0.0107 nan 0.1000 -0.0001
120 0.0099 nan 0.1000 -0.0000
140 0.0092 nan 0.1000 -0.0000
150 0.0089 nan 0.1000 -0.0001
> # Go back to sequential processing
> stopCluster(cluster)
> registerDoSEQ()
> # Do predictions on validation data and find best models
> rmses <- list()
> predicted <- list()
> for (fi in modelfits) {
+ writeLines ( paste("\n\n\nPredicting validation set for model:", fi[[1]]) )
+ p <- predict(fi, newdata=da2)
+ p[is.na(p)] <- basepred[is.na(p)]
+ predicted <- c(predicted, list(p))
+ rmses <- c(rmses, rmse(da2$RelPrice, p))
+ }
Predicting validation set for model: lars2
Predicting validation set for model: cubist
Predicting validation set for model: glmboost
Predicting validation set for model: glmnet
Predicting validation set for model: lasso
Predicting validation set for model: bayesglm
Predicting validation set for model: ridge
Predicting validation set for model: xgbLinear
Predicting validation set for model: nnls
Predicting validation set for model: icr
Predicting validation set for model: gbm
> names(rmses) <- modelnames
> names(predicted) <- modelnames
> print( rmses )
$lars2
[1] 0.09593734
$cubist
[1] 0.09149632
$glmboost
[1] 0.1094718
$glmnet
[1] 0.09619513
$lasso
[1] 0.0960113
$bayesglm
[1] 0.09619938
$ridge
[1] 0.09660811
$xgbLinear
[1] 0.1143767
$nnls
[1] 0.112101
$icr
[1] 0.1514711
$gbm
[1] 0.0993608
> # Run an OLS to weight predictors
> preddf <- cbind( as.data.frame(predicted), da2$RelPrice )
> colnames(preddf) <- c(modelnames, "actual")
> predeq <- lm(actual~., data=preddf)
> summary( predeq )
Call:
lm(formula = actual ~ ., data = preddf)
Residuals:
Min 1Q Median 3Q Max
-0.288476 -0.043044 0.000322 0.050865 0.308198
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.37740 0.11282 3.345 0.000935 ***
lars2 -8.85978 6.84243 -1.295 0.196446
cubist 0.67288 0.16310 4.126 4.88e-05 ***
glmboost -0.21907 0.12222 -1.792 0.074142 .
glmnet 14.70071 6.18535 2.377 0.018141 *
lasso 4.57613 10.10494 0.453 0.651000
bayesglm 0.75979 1.94129 0.391 0.695812
ridge -10.90945 3.72766 -2.927 0.003708 **
xgbLinear 0.20727 0.06307 3.286 0.001145 **
nnls -0.04222 0.10449 -0.404 0.686434
icr -0.10685 0.05221 -2.046 0.041646 *
gbm 0.16349 0.09580 1.707 0.088995 .
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.08366 on 280 degrees of freedom
Multiple R-squared: 0.9489, Adjusted R-squared: 0.9469
F-statistic: 473.1 on 11 and 280 DF, p-value: < 2.2e-16
> # Get rid of the constant and force coefficients to sum to 1
> preddf2 <- preddf
> for (n in names(preddf2)) {
+ preddf2[n] <- preddf2[n] - preddf$glmnet
+ }
> e1 <- lm(
+ actual~lars2+cubist+glmboost+lasso+bayesglm+ridge+xgbLinear+nnls+icr+gbm-1,
+ data=preddf2)
> summary(e1)
Call:
lm(formula = actual ~ lars2 + cubist + glmboost + lasso + bayesglm +
ridge + xgbLinear + nnls + icr + gbm - 1, data = preddf2)
Residuals:
Min 1Q Median 3Q Max
-0.27733 -0.05306 -0.00606 0.05503 0.25883
Coefficients:
Estimate Std. Error t value Pr(>|t|)
lars2 -5.88868 6.87917 -0.856 0.392716
cubist 0.59629 0.16444 3.626 0.000341 ***
glmboost -0.18233 0.12393 -1.471 0.142358
lasso 1.64807 10.19711 0.162 0.871720
bayesglm 0.91178 1.97455 0.462 0.644605
ridge -9.88623 3.78163 -2.614 0.009422 **
xgbLinear 0.21221 0.06408 3.312 0.001048 **
nnls -0.02374 0.10618 -0.224 0.823222
icr -0.02772 0.04734 -0.586 0.558675
gbm 0.19961 0.09689 2.060 0.040294 *
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.08515 on 282 degrees of freedom
Multiple R-squared: 0.2433, Adjusted R-squared: 0.2165
F-statistic: 9.069 on 10 and 282 DF, p-value: 5.707e-13
> # Drop the one with the worst coefficient (ridge) and run again
> e2 <- lm(
+ actual~cubist+glmboost+lasso+bayesglm+lars2+xgbLinear+nnls+icr+gbm-1,
+ data=preddf2)
> summary(e2)
Call:
lm(formula = actual ~ cubist + glmboost + lasso + bayesglm +
lars2 + xgbLinear + nnls + icr + gbm - 1, data = preddf2)
Residuals:
Min 1Q Median 3Q Max
-0.289379 -0.050149 -0.005266 0.047690 0.296395
Coefficients:
Estimate Std. Error t value Pr(>|t|)
cubist 0.59692 0.16613 3.593 0.000385 ***
glmboost -0.24942 0.12249 -2.036 0.042656 *
lasso 1.98223 10.30088 0.192 0.847541
bayesglm -1.72235 1.71553 -1.004 0.316247
lars2 -1.85869 6.77299 -0.274 0.783957