R Markdown

This is a brief introdution on linear regression tree and an application of basic grandient boosting technique in model

rm(list = ls())
#import library
library(rsample)
## Loading required package: tidyr
library(rpart)
library(rpart.plot)
library(ipred)
library(caret)
## Loading required package: lattice
## Loading required package: ggplot2
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
#Using AmesHousing dataset 
set.seed(123)
data_house <- initial_split(AmesHousing::make_ames(), prop = .7)
summary(data_house)
##        Length Class  Mode   
## data     81   tbl_df list   
## in_id  2051   -none- numeric
## out_id    1   -none- logical
## id        1   tbl_df list
data_house %>% head()
## $data
## # A tibble: 2,930 x 81
##    MS_SubClass MS_Zoning Lot_Frontage Lot_Area Street Alley Lot_Shape
##    <fct>       <fct>            <dbl>    <int> <fct>  <fct> <fct>    
##  1 One_Story_~ Resident~          141    31770 Pave   No_A~ Slightly~
##  2 One_Story_~ Resident~           80    11622 Pave   No_A~ Regular  
##  3 One_Story_~ Resident~           81    14267 Pave   No_A~ Slightly~
##  4 One_Story_~ Resident~           93    11160 Pave   No_A~ Regular  
##  5 Two_Story_~ Resident~           74    13830 Pave   No_A~ Slightly~
##  6 Two_Story_~ Resident~           78     9978 Pave   No_A~ Slightly~
##  7 One_Story_~ Resident~           41     4920 Pave   No_A~ Regular  
##  8 One_Story_~ Resident~           43     5005 Pave   No_A~ Slightly~
##  9 One_Story_~ Resident~           39     5389 Pave   No_A~ Slightly~
## 10 Two_Story_~ Resident~           60     7500 Pave   No_A~ Regular  
## # ... with 2,920 more rows, and 74 more variables: Land_Contour <fct>,
## #   Utilities <fct>, Lot_Config <fct>, Land_Slope <fct>,
## #   Neighborhood <fct>, Condition_1 <fct>, Condition_2 <fct>,
## #   Bldg_Type <fct>, House_Style <fct>, Overall_Qual <fct>,
## #   Overall_Cond <fct>, Year_Built <int>, Year_Remod_Add <int>,
## #   Roof_Style <fct>, Roof_Matl <fct>, Exterior_1st <fct>,
## #   Exterior_2nd <fct>, Mas_Vnr_Type <fct>, Mas_Vnr_Area <dbl>,
## #   Exter_Qual <fct>, Exter_Cond <fct>, Foundation <fct>, Bsmt_Qual <fct>,
## #   Bsmt_Cond <fct>, Bsmt_Exposure <fct>, BsmtFin_Type_1 <fct>,
## #   BsmtFin_SF_1 <dbl>, BsmtFin_Type_2 <fct>, BsmtFin_SF_2 <dbl>,
## #   Bsmt_Unf_SF <dbl>, Total_Bsmt_SF <dbl>, Heating <fct>,
## #   Heating_QC <fct>, Central_Air <fct>, Electrical <fct>,
## #   First_Flr_SF <int>, Second_Flr_SF <int>, Low_Qual_Fin_SF <int>,
## #   Gr_Liv_Area <int>, Bsmt_Full_Bath <dbl>, Bsmt_Half_Bath <dbl>,
## #   Full_Bath <int>, Half_Bath <int>, Bedroom_AbvGr <int>,
## #   Kitchen_AbvGr <int>, Kitchen_Qual <fct>, TotRms_AbvGrd <int>,
## #   Functional <fct>, Fireplaces <int>, Fireplace_Qu <fct>,
## #   Garage_Type <fct>, Garage_Finish <fct>, Garage_Cars <dbl>,
## #   Garage_Area <dbl>, Garage_Qual <fct>, Garage_Cond <fct>,
## #   Paved_Drive <fct>, Wood_Deck_SF <int>, Open_Porch_SF <int>,
## #   Enclosed_Porch <int>, Three_season_porch <int>, Screen_Porch <int>,
## #   Pool_Area <int>, Pool_QC <fct>, Fence <fct>, Misc_Feature <fct>,
## #   Misc_Val <int>, Mo_Sold <int>, Year_Sold <int>, Sale_Type <fct>,
## #   Sale_Condition <fct>, Sale_Price <int>, Longitude <dbl>,
## #   Latitude <dbl>
## 
## $in_id
##    [1]    1    3    4    5    6    7   11   12   14   15   17   19   20
##   [14]   21   22   23   25   26   27   28   29   30   32   33   34   35
##   [27]   36   37   38   40   42   43   46   47   50   53   54   55   57
##   [40]   58   59   60   61   62   63   64   65   66   68   69   70   72
##   [53]   73   74   75   78   80   82   84   85   86   87   89   90   91
##   [66]   92   93   96   97   98   99  101  102  103  104  105  106  107
##   [79]  109  110  111  112  113  114  115  116  118  119  121  122  123
##   [92]  124  125  126  128  129  130  131  132  133  135  136  138  140
##  [105]  142  144  145  146  147  149  150  154  155  156  157  158  159
##  [118]  162  164  167  168  169  171  172  173  174  175  176  177  179
##  [131]  181  182  183  184  186  187  188  189  190  192  194  196  197
##  [144]  198  202  203  205  208  209  210  212  213  214  216  219  220
##  [157]  221  222  223  225  226  227  228  230  231  232  233  234  235
##  [170]  236  237  238  239  240  244  245  246  247  248  249  252  253
##  [183]  254  255  257  260  262  263  264  265  266  267  268  269  271
##  [196]  272  273  274  275  276  280  281  282  283  284  285  286  287
##  [209]  288  289  293  295  296  298  299  300  301  302  305  306  307
##  [222]  308  310  312  313  314  315  317  320  321  322  323  324  325
##  [235]  328  329  330  332  333  334  336  338  339  340  341  342  345
##  [248]  346  350  351  352  353  354  356  358  359  360  361  362  363
##  [261]  364  365  366  367  368  369  370  371  375  376  377  380  381
##  [274]  382  384  385  388  389  390  391  392  394  395  396  397  399
##  [287]  401  402  403  404  405  406  408  410  411  412  414  415  416
##  [300]  417  418  420  423  425  426  427  428  429  431  433  434  435
##  [313]  437  438  439  440  441  442  443  444  446  447  451  453  454
##  [326]  455  460  462  464  465  467  468  470  472  474  475  476  478
##  [339]  479  483  484  485  486  488  489  490  491  492  495  496  497
##  [352]  498  500  501  502  505  506  507  508  509  510  511  512  513
##  [365]  514  518  519  520  521  522  525  527  529  530  531  532  533
##  [378]  534  536  538  540  541  542  543  545  546  547  548  550  551
##  [391]  552  553  556  557  558  559  560  561  562  563  565  566  567
##  [404]  568  569  570  571  572  573  574  575  576  578  580  581  582
##  [417]  583  585  587  590  591  592  593  594  595  596  597  598  600
##  [430]  603  604  607  608  609  611  614  616  621  622  623  624  629
##  [443]  630  631  632  634  635  636  637  638  639  640  641  644  645
##  [456]  647  650  651  652  653  655  657  658  659  661  662  663  664
##  [469]  666  673  674  675  676  677  678  679  687  688  689  690  691
##  [482]  692  694  695  697  699  700  701  702  704  705  707  708  709
##  [495]  714  715  717  718  719  721  724  725  726  727  728  729  731
##  [508]  732  733  734  735  736  737  738  739  740  741  744  745  746
##  [521]  747  748  749  750  751  753  756  759  760  761  762  763  764
##  [534]  765  766  767  768  769  770  771  772  773  774  775  776  777
##  [547]  780  783  784  785  787  788  790  792  795  796  797  798  799
##  [560]  800  801  802  805  806  808  809  810  811  813  815  816  818
##  [573]  819  821  822  823  824  826  827  830  832  834  835  837  838
##  [586]  840  841  842  844  845  846  849  850  851  852  853  854  857
##  [599]  858  859  861  862  863  864  865  868  869  870  871  874  875
##  [612]  880  881  882  883  884  885  886  887  888  889  890  892  893
##  [625]  894  895  897  898  899  900  902  903  906  908  909  910  911
##  [638]  913  914  915  916  917  918  920  921  922  923  925  926  927
##  [651]  928  933  934  935  936  937  938  939  940  941  942  943  944
##  [664]  945  946  947  948  949  951  952  954  955  958  959  960  961
##  [677]  962  964  965  966  967  968  969  970  971  972  973  974  975
##  [690]  976  977  978  979  980  984  987  991  992  994  995  996  997
##  [703]  999 1000 1001 1002 1003 1004 1005 1007 1008 1009 1010 1012 1013
##  [716] 1014 1016 1018 1020 1022 1024 1025 1027 1028 1030 1031 1033 1034
##  [729] 1035 1036 1037 1039 1040 1041 1042 1043 1045 1046 1048 1050 1051
##  [742] 1052 1053 1054 1055 1056 1058 1059 1061 1062 1067 1069 1071 1072
##  [755] 1073 1074 1076 1077 1083 1084 1085 1086 1087 1089 1090 1091 1092
##  [768] 1093 1094 1095 1097 1100 1101 1102 1103 1104 1105 1106 1107 1110
##  [781] 1111 1112 1114 1116 1117 1119 1120 1121 1124 1125 1126 1128 1129
##  [794] 1130 1131 1133 1135 1137 1138 1140 1141 1144 1145 1147 1148 1150
##  [807] 1151 1152 1153 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
##  [820] 1166 1168 1170 1171 1172 1173 1174 1175 1176 1177 1178 1180 1181
##  [833] 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1196 1197
##  [846] 1198 1199 1200 1201 1202 1203 1205 1206 1207 1208 1209 1210 1211
##  [859] 1212 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
##  [872] 1226 1228 1229 1232 1236 1237 1238 1239 1240 1244 1245 1252 1254
##  [885] 1255 1257 1259 1260 1263 1266 1267 1269 1270 1273 1275 1276 1277
##  [898] 1278 1279 1280 1281 1282 1283 1284 1285 1287 1288 1289 1290 1291
##  [911] 1292 1293 1294 1296 1297 1298 1299 1300 1301 1303 1304 1305 1306
##  [924] 1307 1308 1309 1310 1312 1317 1318 1319 1320 1321 1323 1324 1329
##  [937] 1330 1331 1334 1335 1337 1338 1340 1342 1343 1344 1348 1349 1351
##  [950] 1353 1354 1356 1357 1359 1360 1361 1364 1367 1368 1369 1371 1372
##  [963] 1373 1374 1375 1376 1377 1378 1380 1383 1384 1385 1387 1388 1389
##  [976] 1390 1391 1392 1393 1396 1398 1399 1402 1403 1407 1408 1409 1410
##  [989] 1411 1414 1416 1417 1418 1419 1420 1421 1422 1423 1424 1426 1427
## [1002] 1428 1429 1430 1431 1432 1433 1434 1438 1439 1441 1443 1444 1447
## [1015] 1449 1451 1453 1454 1455 1456 1457 1459 1460 1462 1463 1466 1467
## [1028] 1468 1470 1472 1473 1474 1476 1477 1478 1479 1480 1481 1482 1483
## [1041] 1484 1485 1486 1488 1489 1490 1491 1493 1495 1496 1497 1499 1502
## [1054] 1503 1504 1505 1506 1508 1510 1511 1513 1514 1515 1516 1518 1519
## [1067] 1520 1521 1523 1524 1525 1526 1527 1528 1529 1530 1532 1533 1534
## [1080] 1535 1536 1537 1538 1539 1540 1541 1542 1543 1545 1546 1548 1550
## [1093] 1551 1554 1556 1558 1563 1564 1567 1568 1570 1571 1572 1573 1574
## [1106] 1575 1576 1577 1578 1579 1580 1581 1582 1583 1585 1587 1588 1590
## [1119] 1591 1592 1593 1594 1595 1596 1597 1598 1601 1604 1606 1607 1608
## [1132] 1610 1611 1615 1616 1617 1618 1619 1620 1622 1623 1625 1626 1628
## [1145] 1629 1631 1633 1635 1637 1640 1641 1642 1643 1644 1645 1647 1648
## [1158] 1649 1653 1654 1657 1659 1660 1661 1662 1663 1664 1667 1668 1669
## [1171] 1671 1672 1674 1675 1676 1677 1678 1679 1680 1681 1683 1684 1685
## [1184] 1686 1687 1688 1689 1691 1692 1693 1694 1696 1699 1700 1701 1702
## [1197] 1704 1707 1712 1713 1714 1715 1716 1717 1719 1720 1721 1724 1725
## [1210] 1726 1728 1729 1730 1732 1734 1735 1736 1737 1739 1740 1741 1742
## [1223] 1744 1745 1746 1748 1749 1750 1751 1753 1754 1755 1756 1757 1759
## [1236] 1761 1763 1764 1765 1766 1767 1768 1769 1770 1771 1773 1775 1776
## [1249] 1777 1778 1779 1780 1783 1785 1786 1789 1791 1792 1794 1795 1797
## [1262] 1798 1800 1801 1802 1803 1804 1805 1806 1809 1810 1812 1813 1815
## [1275] 1816 1817 1818 1819 1821 1822 1823 1825 1826 1827 1829 1830 1833
## [1288] 1834 1836 1837 1838 1839 1840 1841 1843 1844 1845 1846 1847 1848
## [1301] 1849 1850 1853 1855 1856 1857 1858 1860 1861 1863 1865 1867 1868
## [1314] 1870 1872 1873 1874 1875 1876 1877 1878 1879 1880 1882 1883 1884
## [1327] 1887 1888 1890 1891 1892 1893 1894 1896 1897 1898 1900 1901 1902
## [1340] 1904 1907 1908 1909 1910 1913 1915 1917 1918 1921 1924 1925 1926
## [1353] 1929 1930 1931 1932 1933 1935 1936 1938 1939 1940 1941 1943 1944
## [1366] 1945 1947 1949 1951 1952 1953 1954 1955 1957 1958 1959 1962 1964
## [1379] 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978
## [1392] 1979 1980 1981 1983 1984 1985 1986 1988 1989 1991 1993 1995 1996
## [1405] 1997 1998 2000 2001 2003 2006 2007 2009 2010 2011 2012 2014 2015
## [1418] 2016 2017 2018 2019 2020 2021 2022 2023 2025 2026 2027 2029 2030
## [1431] 2031 2032 2034 2036 2042 2043 2044 2045 2046 2047 2048 2049 2050
## [1444] 2051 2052 2053 2055 2057 2058 2060 2061 2062 2063 2064 2066 2068
## [1457] 2069 2070 2071 2073 2075 2076 2078 2079 2080 2081 2084 2090 2091
## [1470] 2092 2094 2095 2097 2098 2099 2100 2101 2104 2105 2106 2107 2108
## [1483] 2110 2111 2113 2114 2116 2118 2119 2121 2122 2123 2124 2125 2127
## [1496] 2130 2131 2133 2135 2136 2137 2140 2142 2143 2144 2145 2146 2147
## [1509] 2148 2149 2150 2151 2152 2155 2156 2157 2158 2159 2161 2162 2164
## [1522] 2165 2166 2168 2171 2173 2174 2176 2177 2178 2179 2180 2181 2182
## [1535] 2183 2184 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
## [1548] 2197 2198 2199 2200 2201 2202 2204 2205 2206 2207 2209 2212 2214
## [1561] 2215 2217 2219 2221 2222 2223 2226 2228 2229 2230 2231 2232 2233
## [1574] 2235 2236 2239 2240 2241 2243 2245 2246 2247 2249 2250 2251 2252
## [1587] 2254 2255 2256 2258 2259 2261 2262 2263 2264 2265 2267 2268 2270
## [1600] 2271 2272 2273 2274 2275 2276 2278 2280 2282 2287 2288 2289 2292
## [1613] 2294 2295 2296 2298 2299 2300 2301 2303 2304 2305 2306 2307 2308
## [1626] 2309 2310 2311 2314 2315 2316 2317 2318 2320 2322 2323 2324 2326
## [1639] 2327 2329 2331 2333 2335 2336 2337 2338 2340 2341 2342 2343 2344
## [1652] 2345 2346 2347 2349 2350 2351 2352 2355 2356 2357 2358 2359 2360
## [1665] 2361 2364 2365 2366 2368 2369 2370 2372 2373 2375 2376 2377 2379
## [1678] 2380 2381 2382 2383 2384 2385 2387 2388 2389 2391 2392 2393 2396
## [1691] 2397 2398 2399 2400 2401 2403 2405 2407 2408 2409 2410 2411 2412
## [1704] 2414 2415 2416 2417 2418 2419 2420 2423 2424 2425 2426 2427 2428
## [1717] 2430 2433 2434 2435 2436 2437 2438 2439 2441 2442 2443 2444 2447
## [1730] 2448 2452 2453 2454 2456 2459 2460 2461 2462 2464 2465 2467 2469
## [1743] 2471 2472 2473 2475 2476 2478 2480 2481 2482 2484 2485 2487 2490
## [1756] 2491 2493 2494 2496 2497 2498 2499 2500 2501 2502 2509 2513 2514
## [1769] 2515 2518 2519 2520 2521 2522 2524 2525 2526 2529 2530 2531 2532
## [1782] 2533 2534 2535 2537 2539 2540 2541 2542 2544 2546 2549 2551 2552
## [1795] 2553 2555 2557 2558 2559 2560 2561 2563 2564 2565 2566 2568 2569
## [1808] 2571 2572 2573 2574 2575 2577 2579 2581 2583 2584 2586 2587 2588
## [1821] 2589 2590 2591 2593 2594 2595 2597 2598 2599 2600 2601 2603 2604
## [1834] 2606 2608 2609 2610 2611 2612 2613 2614 2616 2617 2618 2620 2622
## [1847] 2624 2625 2627 2628 2631 2633 2635 2636 2637 2638 2639 2640 2642
## [1860] 2643 2644 2647 2649 2652 2653 2654 2655 2656 2657 2658 2659 2660
## [1873] 2661 2662 2664 2665 2670 2671 2672 2674 2677 2679 2680 2684 2685
## [1886] 2686 2687 2688 2689 2690 2691 2692 2693 2695 2700 2701 2702 2704
## [1899] 2706 2707 2708 2710 2711 2712 2713 2716 2717 2718 2721 2722 2724
## [1912] 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737
## [1925] 2738 2739 2740 2741 2742 2743 2745 2748 2749 2750 2751 2753 2754
## [1938] 2755 2761 2762 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773
## [1951] 2775 2778 2779 2781 2783 2785 2788 2790 2792 2793 2794 2796 2798
## [1964] 2799 2800 2801 2805 2806 2807 2808 2809 2810 2811 2813 2816 2817
## [1977] 2820 2821 2824 2825 2826 2827 2830 2832 2833 2834 2835 2836 2837
## [1990] 2839 2840 2841 2844 2845 2849 2851 2852 2854 2855 2856 2858 2859
## [2003] 2861 2862 2864 2865 2866 2867 2868 2870 2871 2872 2873 2875 2876
## [2016] 2877 2878 2879 2881 2882 2884 2885 2887 2889 2890 2891 2893 2894
## [2029] 2895 2896 2898 2899 2900 2902 2904 2906 2907 2909 2910 2911 2912
## [2042] 2914 2915 2916 2917 2919 2921 2923 2924 2927 2928
## 
## $out_id
## [1] NA
## 
## $id
## # A tibble: 1 x 1
##   id       
##   <chr>    
## 1 Resample1
#Split train and test
data_train <- training(data_house)
data_train %>% head(n=6)
## # A tibble: 6 x 81
##   MS_SubClass MS_Zoning Lot_Frontage Lot_Area Street Alley Lot_Shape
##   <fct>       <fct>            <dbl>    <int> <fct>  <fct> <fct>    
## 1 One_Story_~ Resident~          141    31770 Pave   No_A~ Slightly~
## 2 One_Story_~ Resident~           81    14267 Pave   No_A~ Slightly~
## 3 One_Story_~ Resident~           93    11160 Pave   No_A~ Regular  
## 4 Two_Story_~ Resident~           74    13830 Pave   No_A~ Slightly~
## 5 Two_Story_~ Resident~           78     9978 Pave   No_A~ Slightly~
## 6 One_Story_~ Resident~           41     4920 Pave   No_A~ Regular  
## # ... with 74 more variables: Land_Contour <fct>, Utilities <fct>,
## #   Lot_Config <fct>, Land_Slope <fct>, Neighborhood <fct>,
## #   Condition_1 <fct>, Condition_2 <fct>, Bldg_Type <fct>,
## #   House_Style <fct>, Overall_Qual <fct>, Overall_Cond <fct>,
## #   Year_Built <int>, Year_Remod_Add <int>, Roof_Style <fct>,
## #   Roof_Matl <fct>, Exterior_1st <fct>, Exterior_2nd <fct>,
## #   Mas_Vnr_Type <fct>, Mas_Vnr_Area <dbl>, Exter_Qual <fct>,
## #   Exter_Cond <fct>, Foundation <fct>, Bsmt_Qual <fct>, Bsmt_Cond <fct>,
## #   Bsmt_Exposure <fct>, BsmtFin_Type_1 <fct>, BsmtFin_SF_1 <dbl>,
## #   BsmtFin_Type_2 <fct>, BsmtFin_SF_2 <dbl>, Bsmt_Unf_SF <dbl>,
## #   Total_Bsmt_SF <dbl>, Heating <fct>, Heating_QC <fct>,
## #   Central_Air <fct>, Electrical <fct>, First_Flr_SF <int>,
## #   Second_Flr_SF <int>, Low_Qual_Fin_SF <int>, Gr_Liv_Area <int>,
## #   Bsmt_Full_Bath <dbl>, Bsmt_Half_Bath <dbl>, Full_Bath <int>,
## #   Half_Bath <int>, Bedroom_AbvGr <int>, Kitchen_AbvGr <int>,
## #   Kitchen_Qual <fct>, TotRms_AbvGrd <int>, Functional <fct>,
## #   Fireplaces <int>, Fireplace_Qu <fct>, Garage_Type <fct>,
## #   Garage_Finish <fct>, Garage_Cars <dbl>, Garage_Area <dbl>,
## #   Garage_Qual <fct>, Garage_Cond <fct>, Paved_Drive <fct>,
## #   Wood_Deck_SF <int>, Open_Porch_SF <int>, Enclosed_Porch <int>,
## #   Three_season_porch <int>, Screen_Porch <int>, Pool_Area <int>,
## #   Pool_QC <fct>, Fence <fct>, Misc_Feature <fct>, Misc_Val <int>,
## #   Mo_Sold <int>, Year_Sold <int>, Sale_Type <fct>, Sale_Condition <fct>,
## #   Sale_Price <int>, Longitude <dbl>, Latitude <dbl>
data_train %>% str()
## Classes 'tbl_df', 'tbl' and 'data.frame':    2051 obs. of  81 variables:
##  $ MS_SubClass       : Factor w/ 16 levels "One_Story_1946_and_Newer_All_Styles",..: 1 1 1 6 6 12 6 1 1 12 ...
##  $ MS_Zoning         : Factor w/ 7 levels "Floating_Village_Residential",..: 3 3 3 3 3 3 3 3 3 3 ...
##  $ Lot_Frontage      : num  141 81 93 74 78 41 75 0 85 0 ...
##  $ Lot_Area          : int  31770 14267 11160 13830 9978 4920 10000 7980 10176 6820 ...
##  $ Street            : Factor w/ 2 levels "Grvl","Pave": 2 2 2 2 2 2 2 2 2 2 ...
##  $ Alley             : Factor w/ 3 levels "Gravel","No_Alley_Access",..: 2 2 2 2 2 2 2 2 2 2 ...
##  $ Lot_Shape         : Factor w/ 4 levels "Regular","Slightly_Irregular",..: 2 2 1 2 2 1 2 2 1 2 ...
##  $ Land_Contour      : Factor w/ 4 levels "Bnk","HLS","Low",..: 4 4 4 4 4 4 4 4 4 4 ...
##  $ Utilities         : Factor w/ 3 levels "AllPub","NoSeWa",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ Lot_Config        : Factor w/ 5 levels "Corner","CulDSac",..: 1 1 1 5 5 5 1 5 5 1 ...
##  $ Land_Slope        : Factor w/ 3 levels "Gtl","Mod","Sev": 1 1 1 1 1 1 1 1 1 1 ...
##  $ Neighborhood      : Factor w/ 28 levels "North_Ames","College_Creek",..: 1 1 1 7 7 17 7 7 7 17 ...
##  $ Condition_1       : Factor w/ 9 levels "Artery","Feedr",..: 3 3 3 3 3 3 3 3 3 3 ...
##  $ Condition_2       : Factor w/ 8 levels "Artery","Feedr",..: 3 3 3 3 3 3 3 3 3 3 ...
##  $ Bldg_Type         : Factor w/ 5 levels "OneFam","TwoFmCon",..: 1 1 1 1 1 5 1 1 1 5 ...
##  $ House_Style       : Factor w/ 8 levels "One_and_Half_Fin",..: 3 3 3 8 8 3 8 3 3 3 ...
##  $ Overall_Qual      : Factor w/ 10 levels "Very_Poor","Poor",..: 6 6 7 5 6 8 6 6 7 8 ...
##  $ Overall_Cond      : Factor w/ 10 levels "Very_Poor","Poor",..: 5 6 5 5 6 5 5 7 5 5 ...
##  $ Year_Built        : int  1960 1958 1968 1997 1998 2001 1993 1992 1990 1985 ...
##  $ Year_Remod_Add    : int  1960 1958 1968 1998 1998 2001 1994 2007 1990 1985 ...
##  $ Roof_Style        : Factor w/ 6 levels "Flat","Gable",..: 4 4 4 2 2 2 2 2 2 2 ...
##  $ Roof_Matl         : Factor w/ 8 levels "ClyTile","CompShg",..: 2 2 2 2 2 2 2 2 2 2 ...
##  $ Exterior_1st      : Factor w/ 16 levels "AsbShng","AsphShn",..: 4 15 4 14 14 6 7 7 7 7 ...
##  $ Exterior_2nd      : Factor w/ 17 levels "AsbShng","AsphShn",..: 11 16 4 15 15 6 7 7 7 7 ...
##  $ Mas_Vnr_Type      : Factor w/ 5 levels "BrkCmn","BrkFace",..: 5 2 4 4 2 4 4 4 4 4 ...
##  $ Mas_Vnr_Area      : num  112 108 0 0 20 0 0 0 0 0 ...
##  $ Exter_Qual        : Factor w/ 4 levels "Excellent","Fair",..: 4 4 3 4 4 3 4 4 4 3 ...
##  $ Exter_Cond        : Factor w/ 5 levels "Excellent","Fair",..: 5 5 5 5 5 5 5 3 5 5 ...
##  $ Foundation        : Factor w/ 6 levels "BrkTil","CBlock",..: 2 2 2 3 3 3 3 3 3 3 ...
##  $ Bsmt_Qual         : Factor w/ 6 levels "Excellent","Fair",..: 6 6 6 3 6 3 3 3 3 3 ...
##  $ Bsmt_Cond         : Factor w/ 6 levels "Excellent","Fair",..: 3 6 6 6 6 6 6 6 6 6 ...
##  $ Bsmt_Exposure     : Factor w/ 5 levels "Av","Gd","Mn",..: 2 4 4 4 4 3 4 4 2 1 ...
##  $ BsmtFin_Type_1    : Factor w/ 7 levels "ALQ","BLQ","GLQ",..: 2 1 1 3 3 3 7 1 3 3 ...
##  $ BsmtFin_SF_1      : num  2 1 1 3 3 3 7 1 3 3 ...
##  $ BsmtFin_Type_2    : Factor w/ 7 levels "ALQ","BLQ","GLQ",..: 7 7 7 7 7 7 7 7 7 2 ...
##  $ BsmtFin_SF_2      : num  0 0 0 0 0 0 0 0 0 1120 ...
##  $ Bsmt_Unf_SF       : num  441 406 1045 137 324 ...
##  $ Total_Bsmt_SF     : num  1080 1329 2110 928 926 ...
##  $ Heating           : Factor w/ 6 levels "Floor","GasA",..: 2 2 2 2 2 2 2 2 2 2 ...
##  $ Heating_QC        : Factor w/ 5 levels "Excellent","Fair",..: 2 5 1 3 1 1 3 1 3 5 ...
##  $ Central_Air       : Factor w/ 2 levels "N","Y": 2 2 2 2 2 2 2 2 2 2 ...
##  $ Electrical        : Factor w/ 6 levels "FuseA","FuseF",..: 5 5 5 5 5 5 5 5 5 5 ...
##  $ First_Flr_SF      : int  1656 1329 2110 928 926 1338 763 1187 1341 1502 ...
##  $ Second_Flr_SF     : int  0 0 0 701 678 0 892 0 0 0 ...
##  $ Low_Qual_Fin_SF   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ Gr_Liv_Area       : int  1656 1329 2110 1629 1604 1338 1655 1187 1341 1502 ...
##  $ Bsmt_Full_Bath    : num  1 0 1 0 0 1 0 1 1 1 ...
##  $ Bsmt_Half_Bath    : num  0 0 0 0 0 0 0 0 0 0 ...
##  $ Full_Bath         : int  1 1 2 2 2 2 2 2 1 1 ...
##  $ Half_Bath         : int  0 1 1 1 1 0 1 0 1 1 ...
##  $ Bedroom_AbvGr     : int  3 3 3 3 3 2 3 3 2 1 ...
##  $ Kitchen_AbvGr     : int  1 1 1 1 1 1 1 1 1 1 ...
##  $ Kitchen_Qual      : Factor w/ 5 levels "Excellent","Fair",..: 5 3 1 5 3 3 5 5 3 3 ...
##  $ TotRms_AbvGrd     : int  7 6 8 6 7 6 7 6 5 4 ...
##  $ Functional        : Factor w/ 8 levels "Maj1","Maj2",..: 8 8 8 8 8 8 8 8 8 8 ...
##  $ Fireplaces        : int  2 0 2 1 1 0 1 0 1 0 ...
##  $ Fireplace_Qu      : Factor w/ 6 levels "Excellent","Fair",..: 3 4 6 6 3 4 6 4 5 4 ...
##  $ Garage_Type       : Factor w/ 7 levels "Attchd","Basment",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ Garage_Finish     : Factor w/ 4 levels "Fin","No_Garage",..: 1 4 1 1 1 1 1 1 4 3 ...
##  $ Garage_Cars       : num  2 1 2 2 2 2 2 2 2 2 ...
##  $ Garage_Area       : num  528 312 522 482 470 582 440 420 506 528 ...
##  $ Garage_Qual       : Factor w/ 6 levels "Excellent","Fair",..: 6 6 6 6 6 6 6 6 6 6 ...
##  $ Garage_Cond       : Factor w/ 6 levels "Excellent","Fair",..: 6 6 6 6 6 6 6 6 6 6 ...
##  $ Paved_Drive       : Factor w/ 3 levels "Dirt_Gravel",..: 2 3 3 3 3 3 3 3 3 3 ...
##  $ Wood_Deck_SF      : int  210 393 0 212 360 0 157 483 192 0 ...
##  $ Open_Porch_SF     : int  62 36 0 34 36 0 84 21 0 54 ...
##  $ Enclosed_Porch    : int  0 0 0 0 0 170 0 0 0 0 ...
##  $ Three_season_porch: int  0 0 0 0 0 0 0 0 0 0 ...
##  $ Screen_Porch      : int  0 0 0 0 0 0 0 0 0 140 ...
##  $ Pool_Area         : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ Pool_QC           : Factor w/ 5 levels "Excellent","Fair",..: 4 4 4 4 4 4 4 4 4 4 ...
##  $ Fence             : Factor w/ 5 levels "Good_Privacy",..: 5 5 5 3 5 5 5 1 5 5 ...
##  $ Misc_Feature      : Factor w/ 6 levels "Elev","Gar2",..: 3 2 3 3 3 3 3 5 3 3 ...
##  $ Misc_Val          : int  0 12500 0 0 0 0 0 500 0 0 ...
##  $ Mo_Sold           : int  5 6 4 3 6 4 4 3 2 6 ...
##  $ Year_Sold         : int  2010 2010 2010 2010 2010 2010 2010 2010 2010 2010 ...
##  $ Sale_Type         : Factor w/ 10 levels "COD","Con","ConLD",..: 10 10 10 10 10 10 10 10 10 10 ...
##  $ Sale_Condition    : Factor w/ 6 levels "Abnorml","AdjLand",..: 5 5 5 5 5 5 5 5 5 5 ...
##  $ Sale_Price        : int  215000 172000 244000 189900 195500 213500 175900 185000 171500 212000 ...
##  $ Longitude         : num  -93.6 -93.6 -93.6 -93.6 -93.6 ...
##  $ Latitude          : num  42.1 42.1 42.1 42.1 42.1 ...
data_test <- testing(data_house)

#Basic linear tree regression model to predict the house price
m1 <- rpart(
  formula = Sale_Price ~ .,
  data = data_train,
  method = "anova"
)
m1
## n= 2051 
## 
## node), split, n, deviance, yval
##       * denotes terminal node
## 
##  1) root 2051 1.273987e+13 180775.50  
##    2) Overall_Qual=Very_Poor,Poor,Fair,Below_Average,Average,Above_Average,Good 1703 4.032269e+12 156431.40  
##      4) Neighborhood=North_Ames,Old_Town,Edwards,Sawyer,Mitchell,Brookside,Iowa_DOT_and_Rail_Road,South_and_West_of_Iowa_State_University,Meadow_Village,Briardale,Northpark_Villa,Blueste 1015 1.360332e+12 131803.50  
##        8) First_Flr_SF< 1048.5 611 4.924281e+11 118301.50  
##         16) Overall_Qual=Very_Poor,Poor,Fair,Below_Average 152 1.053743e+11  91652.57 *
##         17) Overall_Qual=Average,Above_Average,Good 459 2.433622e+11 127126.40 *
##        9) First_Flr_SF>=1048.5 404 5.880574e+11 152223.50  
##         18) Gr_Liv_Area< 2007.5 359 2.957141e+11 145749.50 *
##         19) Gr_Liv_Area>=2007.5 45 1.572566e+11 203871.90 *
##      5) Neighborhood=College_Creek,Somerset,Northridge_Heights,Gilbert,Northwest_Ames,Sawyer_West,Crawford,Timberland,Northridge,Stone_Brook,Clear_Creek,Bloomington_Heights,Veenker,Green_Hills 688 1.148069e+12 192764.70  
##       10) Gr_Liv_Area< 1725.5 482 5.162415e+11 178531.00  
##         20) Total_Bsmt_SF< 1331 352 2.315412e+11 167759.00 *
##         21) Total_Bsmt_SF>=1331 130 1.332603e+11 207698.30 *
##       11) Gr_Liv_Area>=1725.5 206 3.056877e+11 226068.80 *
##    3) Overall_Qual=Very_Good,Excellent,Very_Excellent 348 2.759339e+12 299907.90  
##      6) Overall_Qual=Very_Good 249 9.159879e+11 268089.10  
##       12) Gr_Liv_Area< 1592.5 78 1.339905e+11 220448.90 *
##       13) Gr_Liv_Area>=1592.5 171 5.242201e+11 289819.70 *
##      7) Overall_Qual=Excellent,Very_Excellent 99 9.571896e+11 379937.20  
##       14) Gr_Liv_Area< 1947 42 7.265064e+10 325865.10 *
##       15) Gr_Liv_Area>=1947 57 6.712559e+11 419779.80  
##         30) Neighborhood=Old_Town,Edwards,Timberland 7 8.073100e+10 295300.00 *
##         31) Neighborhood=College_Creek,Somerset,Northridge_Heights,Northridge,Stone_Brook 50 4.668730e+11 437207.00  
##           62) Total_Bsmt_SF< 2168.5 40 1.923959e+11 408996.90 *
##           63) Total_Bsmt_SF>=2168.5 10 1.153154e+11 550047.30 *
## Plots

rpart.plot(m1)

#There are ~80 variables in the train set, however, our tree contains only 12 nodes. Why?
#In this example we find diminishing returns after 12 terminal nodes as illustrated below (y-axis is cross validation error, lower x-axis is cost complexity (α) value, upper x-axis is the number of terminal nodes (tree size = |T|). You may also notice the dashed line which goes through the point |T|=9. Breiman et al. (1984) suggested that in actual practice, its common to instead use the smallest tree within 1 standard deviation of the minimum cross validation error (aka the 1-SE rule). Thus, we could use a tree with 9 terminal nodes and reasonably expect to experience similar results within a small margin of error.

plotcp(m1)

#In case we do not go with 1-SE rule (node = 9), we wull create a full tree (with 12 nodes) by using cp=0 (no penalty results in a fully grown tree).We can see that after 12 terminal nodes, we see diminishing returns in error reduction as the tree grows deeper. Thus, we can signifcantly prune our tree and still achieve minimal expected error.

m2 <- rpart(
    formula = Sale_Price ~ .,
    data    = data_train,
    method  = "anova", 
    control = list(cp = 0, xval = 10)
)

plotcp(m2)
abline(v = 12, lty = "dashed")

#So, by default, rpart is performing some automated tuning, with an optimal subtree of 11 splits, 12 terminal nodes, and a cross-validated error of 0.262 (note that this error is equivalent to the PRESS statistic but not the MSE). However, we can perform additional tuning to try improve model performance.

m1$cptable
##            CP nsplit rel error    xerror       xstd
## 1  0.46690132      0 1.0000000 1.0009222 0.05855161
## 2  0.11961409      1 0.5330987 0.5347929 0.03116217
## 3  0.06955813      2 0.4134846 0.4151417 0.03058554
## 4  0.02559992      3 0.3439265 0.3461258 0.02207839
## 5  0.02196620      4 0.3183265 0.3242197 0.02182111
## 6  0.02023390      5 0.2963603 0.3074877 0.02129292
## 7  0.01674138      6 0.2761264 0.2963372 0.02106996
## 8  0.01188709      7 0.2593850 0.2795199 0.01903482
## 9  0.01127889      8 0.2474980 0.2762666 0.01936472
## 10 0.01109955      9 0.2362191 0.2699895 0.01902217
## 11 0.01060346     11 0.2140200 0.2672133 0.01883219
## 12 0.01000000     12 0.2034165 0.2635207 0.01881691
m2$cptable
##               CP nsplit  rel error    xerror       xstd
## 1   4.669013e-01      0 1.00000000 1.0011255 0.05856958
## 2   1.196141e-01      1 0.53309868 0.5347800 0.03116362
## 3   6.955813e-02      2 0.41348458 0.4155131 0.03060394
## 4   2.559992e-02      3 0.34392645 0.3462873 0.02202255
## 5   2.196620e-02      4 0.31832653 0.3264198 0.02176383
## 6   2.023390e-02      5 0.29636033 0.3148141 0.02148575
## 7   1.674138e-02      6 0.27612643 0.3009990 0.02163089
## 8   1.188709e-02      7 0.25938505 0.2867883 0.02122175
## 9   1.127889e-02      8 0.24749795 0.2791822 0.01990810
## 10  1.109955e-02      9 0.23621906 0.2759492 0.01987842
## 11  1.060346e-02     11 0.21401997 0.2765057 0.01990076
## 12  7.577966e-03     12 0.20341650 0.2619317 0.02057854
## 13  6.296226e-03     13 0.19583854 0.2481373 0.01953078
## 14  5.744170e-03     14 0.18954231 0.2450549 0.01943067
## 15  4.853620e-03     15 0.18379814 0.2344939 0.01889124
## 16  4.124399e-03     16 0.17894452 0.2293131 0.01871177
## 17  3.988242e-03     17 0.17482012 0.2269649 0.01868155
## 18  3.772794e-03     18 0.17083188 0.2244837 0.01863698
## 19  3.692640e-03     19 0.16705909 0.2260958 0.01873527
## 20  3.643603e-03     20 0.16336645 0.2260958 0.01873527
## 21  3.538345e-03     21 0.15972284 0.2243087 0.01872190
## 22  2.806104e-03     22 0.15618450 0.2212321 0.01871292
## 23  2.425512e-03     23 0.15337839 0.2196958 0.01875116
## 24  2.412082e-03     24 0.15095288 0.2208942 0.01885057
## 25  2.277793e-03     25 0.14854080 0.2211877 0.01886094
## 26  2.175674e-03     26 0.14626301 0.2209282 0.01888170
## 27  2.133769e-03     27 0.14408733 0.2197239 0.01887788
## 28  2.115957e-03     28 0.14195357 0.2199990 0.01887750
## 29  2.042825e-03     30 0.13772165 0.2190071 0.01886396
## 30  1.970846e-03     31 0.13567883 0.2195337 0.01888253
## 31  1.805990e-03     32 0.13370798 0.2196190 0.01883633
## 32  1.774013e-03     33 0.13190199 0.2191471 0.01883914
## 33  1.770661e-03     34 0.13012798 0.2185081 0.01882906
## 34  1.745514e-03     35 0.12835732 0.2185081 0.01882906
## 35  1.682132e-03     36 0.12661180 0.2184725 0.01881886
## 36  1.511900e-03     37 0.12492967 0.2166010 0.01877869
## 37  1.381073e-03     39 0.12190587 0.2156534 0.01878737
## 38  1.334026e-03     40 0.12052480 0.2153736 0.01878522
## 39  1.125284e-03     41 0.11919077 0.2134013 0.01867888
## 40  1.113833e-03     42 0.11806549 0.2131679 0.01864780
## 41  1.092438e-03     43 0.11695165 0.2134536 0.01865192
## 42  1.090153e-03     44 0.11585922 0.2121109 0.01863370
## 43  1.068229e-03     45 0.11476906 0.2120817 0.01863468
## 44  1.062000e-03     46 0.11370083 0.2115608 0.01863484
## 45  1.061897e-03     48 0.11157683 0.2115577 0.01863445
## 46  1.057263e-03     49 0.11051494 0.2115577 0.01863445
## 47  9.620782e-04     50 0.10945767 0.2101311 0.01862051
## 48  9.601591e-04     51 0.10849560 0.2090778 0.01862027
## 49  9.471995e-04     52 0.10753544 0.2088892 0.01861673
## 50  8.974522e-04     53 0.10658824 0.2074964 0.01857536
## 51  8.216746e-04     54 0.10569079 0.2071210 0.01861152
## 52  8.201798e-04     55 0.10486911 0.2070166 0.01865462
## 53  8.062067e-04     56 0.10404893 0.2067341 0.01865898
## 54  7.992162e-04     57 0.10324272 0.2071253 0.01866471
## 55  7.775615e-04     58 0.10244351 0.2063986 0.01860668
## 56  6.626670e-04     59 0.10166595 0.2065892 0.01869566
## 57  6.605972e-04     60 0.10100328 0.2050349 0.01868590
## 58  6.547157e-04     61 0.10034268 0.2049580 0.01868440
## 59  6.243862e-04     62 0.09968797 0.2049737 0.01868909
## 60  6.049884e-04     63 0.09906358 0.2053055 0.01869403
## 61  5.992004e-04     64 0.09845859 0.2053016 0.01869377
## 62  5.818262e-04     65 0.09785939 0.2051343 0.01868706
## 63  5.791498e-04     66 0.09727757 0.2050844 0.01868759
## 64  5.717702e-04     67 0.09669842 0.2050527 0.01868763
## 65  5.383249e-04     68 0.09612665 0.2051823 0.01868969
## 66  5.367311e-04     69 0.09558832 0.2050255 0.01868764
## 67  5.357103e-04     70 0.09505159 0.2050255 0.01868764
## 68  5.096921e-04     71 0.09451588 0.2054431 0.01869119
## 69  4.649323e-04     72 0.09400619 0.2046262 0.01866286
## 70  4.561367e-04     73 0.09354125 0.2045332 0.01866733
## 71  4.542155e-04     74 0.09308512 0.2040116 0.01863305
## 72  4.524856e-04     75 0.09263090 0.2039693 0.01863310
## 73  4.451688e-04     76 0.09217842 0.2039791 0.01863307
## 74  4.330045e-04     77 0.09173325 0.2036679 0.01863064
## 75  3.979093e-04     78 0.09130024 0.2031072 0.01862413
## 76  3.901912e-04     79 0.09090233 0.2038487 0.01864708
## 77  3.872287e-04     80 0.09051214 0.2038321 0.01864633
## 78  3.666033e-04     81 0.09012491 0.2036472 0.01863984
## 79  3.639055e-04     82 0.08975831 0.2039007 0.01863752
## 80  3.578792e-04     83 0.08939441 0.2040826 0.01863406
## 81  3.559655e-04     84 0.08903653 0.2040826 0.01863406
## 82  3.375310e-04     85 0.08868056 0.2043108 0.01864632
## 83  3.369847e-04     86 0.08834303 0.2044716 0.01864833
## 84  3.341938e-04     87 0.08800605 0.2046155 0.01865237
## 85  3.151826e-04     88 0.08767185 0.2046018 0.01865464
## 86  3.136833e-04     89 0.08735667 0.2037727 0.01865468
## 87  3.092828e-04     90 0.08704299 0.2035603 0.01865254
## 88  3.073751e-04     91 0.08673370 0.2035346 0.01865279
## 89  2.992491e-04     92 0.08642633 0.2033373 0.01865234
## 90  2.984140e-04     93 0.08612708 0.2033829 0.01865297
## 91  2.969565e-04     94 0.08582866 0.2033477 0.01865221
## 92  2.966707e-04     95 0.08553171 0.2033667 0.01865161
## 93  2.960274e-04     96 0.08523504 0.2033667 0.01865161
## 94  2.954842e-04     97 0.08493901 0.2033667 0.01865161
## 95  2.932547e-04     98 0.08464353 0.2033667 0.01865161
## 96  2.832928e-04     99 0.08435027 0.2036407 0.01865220
## 97  2.743727e-04    100 0.08406698 0.2042114 0.01866954
## 98  2.728261e-04    101 0.08379261 0.2042919 0.01866943
## 99  2.459325e-04    102 0.08351978 0.2036927 0.01866382
## 100 2.403570e-04    103 0.08327385 0.2040357 0.01866360
## 101 2.381549e-04    104 0.08303349 0.2039966 0.01866350
## 102 2.229447e-04    105 0.08279534 0.2039836 0.01866240
## 103 2.223638e-04    106 0.08257239 0.2042366 0.01866551
## 104 2.146685e-04    107 0.08235003 0.2044863 0.01866581
## 105 2.087758e-04    108 0.08213536 0.2047614 0.01866674
## 106 1.998862e-04    109 0.08192658 0.2044301 0.01866681
## 107 1.909598e-04    110 0.08172670 0.2048230 0.01867644
## 108 1.868787e-04    111 0.08153574 0.2046733 0.01867754
## 109 1.868449e-04    112 0.08134886 0.2047041 0.01867762
## 110 1.826530e-04    113 0.08116201 0.2044775 0.01867768
## 111 1.773220e-04    114 0.08097936 0.2044872 0.01867815
## 112 1.756532e-04    115 0.08080204 0.2044717 0.01867871
## 113 1.710976e-04    116 0.08062638 0.2043461 0.01867794
## 114 1.695621e-04    117 0.08045529 0.2045395 0.01867741
## 115 1.685309e-04    118 0.08028572 0.2045191 0.01867741
## 116 1.679653e-04    119 0.08011719 0.2045191 0.01867741
## 117 1.585856e-04    120 0.07994923 0.2046089 0.01867915
## 118 1.560240e-04    121 0.07979064 0.2045037 0.01868079
## 119 1.504075e-04    122 0.07963462 0.2045062 0.01868091
## 120 1.426703e-04    123 0.07948421 0.2046829 0.01868618
## 121 1.407895e-04    124 0.07934154 0.2046019 0.01868757
## 122 1.384368e-04    125 0.07920075 0.2045871 0.01868680
## 123 1.371759e-04    126 0.07906231 0.2047355 0.01868725
## 124 1.284042e-04    127 0.07892514 0.2048314 0.01868772
## 125 1.277963e-04    129 0.07866833 0.2048412 0.01868711
## 126 1.266223e-04    130 0.07854053 0.2049103 0.01868743
## 127 1.215251e-04    131 0.07841391 0.2050651 0.01869056
## 128 1.189527e-04    132 0.07829239 0.2052480 0.01869033
## 129 1.188185e-04    133 0.07817343 0.2053125 0.01869022
## 130 1.169362e-04    134 0.07805462 0.2053125 0.01869022
## 131 1.142789e-04    135 0.07793768 0.2053716 0.01869214
## 132 1.135171e-04    136 0.07782340 0.2053721 0.01869215
## 133 1.084227e-04    137 0.07770988 0.2054973 0.01869306
## 134 1.065746e-04    138 0.07760146 0.2056857 0.01869378
## 135 1.031086e-04    139 0.07749489 0.2058704 0.01869821
## 136 9.581480e-05    140 0.07739178 0.2057606 0.01869683
## 137 9.116699e-05    141 0.07729596 0.2058457 0.01869662
## 138 8.589119e-05    142 0.07720480 0.2058768 0.01869671
## 139 8.465769e-05    143 0.07711890 0.2059265 0.01869667
## 140 8.227245e-05    144 0.07703425 0.2058369 0.01869699
## 141 8.046237e-05    145 0.07695197 0.2058877 0.01869719
## 142 7.924956e-05    146 0.07687151 0.2058647 0.01869732
## 143 7.204712e-05    147 0.07679226 0.2057658 0.01869544
## 144 6.754013e-05    148 0.07672022 0.2059855 0.01869395
## 145 6.740130e-05    149 0.07665267 0.2059905 0.01869395
## 146 6.495333e-05    150 0.07658527 0.2059939 0.01869398
## 147 6.154352e-05    151 0.07652032 0.2060759 0.01869413
## 148 5.524682e-05    153 0.07639723 0.2060241 0.01869395
## 149 5.176291e-05    154 0.07634199 0.2060751 0.01869418
## 150 4.948611e-05    155 0.07629022 0.2060588 0.01869415
## 151 4.722652e-05    156 0.07624074 0.2060082 0.01869395
## 152 4.494622e-05    157 0.07619351 0.2059602 0.01869400
## 153 4.471005e-05    158 0.07614856 0.2059826 0.01869395
## 154 4.416516e-05    159 0.07610385 0.2059998 0.01869389
## 155 4.335957e-05    160 0.07605969 0.2059931 0.01869388
## 156 4.169868e-05    161 0.07601633 0.2060673 0.01869369
## 157 3.730154e-05    162 0.07597463 0.2059714 0.01869374
## 158 3.405825e-05    163 0.07593733 0.2059714 0.01869374
## 159 3.266666e-05    164 0.07590327 0.2059905 0.01869373
## 160 2.944971e-05    165 0.07587060 0.2058795 0.01869393
## 161 2.851429e-05    166 0.07584116 0.2058670 0.01869396
## 162 2.756886e-05    167 0.07581264 0.2058670 0.01869396
## 163 2.677710e-05    168 0.07578507 0.2058670 0.01869396
## 164 2.490880e-05    169 0.07575829 0.2058670 0.01869396
## 165 1.870440e-05    170 0.07573339 0.2058298 0.01869403
## 166 1.677394e-05    171 0.07571468 0.2058390 0.01869383
## 167 0.000000e+00    173 0.07568113 0.2058687 0.01869371
#Instead of automated chosen by rpart model, we can adjust manually tuning to improve model performance
#minsplit: the minimum number of data points required to attempt a split before it is forced to create a terminal node. The default is 20. Making this smaller allows for terminal nodes that may contain only a handful of observations to create the predicted value.
#maxdepth: the maximum number of internal nodes between the root node and the terminal nodes. The default is 30, which is quite liberal and allows for fairly large trees to be built.
#For instance, if we wanted to assess a model with minsplit = 10 and maxdepth = 12, we could execute the following:

m3 <- rpart(
    formula = Sale_Price ~ .,
    data    = data_train,
    method  = "anova", 
    control = list(minsplit = 10, maxdepth = 12, xval = 10)
)

m3$cptable
##            CP nsplit rel error    xerror       xstd
## 1  0.46690132      0 1.0000000 1.0004448 0.05850012
## 2  0.11961409      1 0.5330987 0.5343156 0.03093134
## 3  0.06955813      2 0.4134846 0.4148699 0.03035832
## 4  0.02559992      3 0.3439265 0.3455539 0.02190359
## 5  0.02196620      4 0.3183265 0.3259151 0.02168056
## 6  0.02023390      5 0.2963603 0.3062045 0.02114604
## 7  0.01674138      6 0.2761264 0.3061135 0.02176061
## 8  0.01188709      7 0.2593850 0.2917534 0.02058535
## 9  0.01127889      8 0.2474980 0.2872380 0.02441006
## 10 0.01109955      9 0.2362191 0.2850234 0.02440721
## 11 0.01060346     11 0.2140200 0.2829790 0.02334151
## 12 0.01000000     12 0.2034165 0.2735069 0.02260957
#To avoid wasting time and health, we can develop an automated function. In this example, I search a range of minsplit from 5-20 and vary maxdepth from 8-15 (since our original model found an optimal depth of 12). What results is 128 different combinations, which requires 128 different models.

hyper_grid <- expand.grid(
  minsplit = seq(5, 20, 1),
  maxdepth = seq(8, 15, 1)
)

head(hyper_grid)
##   minsplit maxdepth
## 1        5        8
## 2        6        8
## 3        7        8
## 4        8        8
## 5        9        8
## 6       10        8
# total number of combinations
nrow(hyper_grid)
## [1] 128
#To automate the modeling we simply set up a for loop and iterate through each minsplit and maxdepth combination. We save each model into its own list item.
models <- list()

for (i in 1:nrow(hyper_grid)) {
  
  # get minsplit, maxdepth values at row i
  minsplit <- hyper_grid$minsplit[i]
  maxdepth <- hyper_grid$maxdepth[i]

  # train a model and store in the list
  models[[i]] <- rpart(
    formula = Sale_Price ~ .,
    data    = data_train,
    method  = "anova",
    control = list(minsplit = minsplit, maxdepth = maxdepth)
    )
}

# To create a function to extract the minimum error associated with the optimal cost complexity α value for each model.After a little data wrangling to extract the optimal α value and its respective error, adding it back to our grid, and filter for the top 5 minimal error values we see that the optimal model makes a slight improvement over our earlier model (xerror of 0.242 versus 0.262).

# function to get optimal cp
get_cp <- function(x) {
  min    <- which.min(x$cptable[, "xerror"])
  cp <- x$cptable[min, "CP"] 
}

# function to get minimum error
get_min_error <- function(x) {
  min    <- which.min(x$cptable[, "xerror"])
  xerror <- x$cptable[min, "xerror"] 
}

#*delete "#" when use this code
#hyper_grid %>%
#  mutate(
#    cp    = purrr::map_dbl(models, get_cp),
#    error = purrr::map_dbl(models, get_min_error)
#    ) %>%
#  arrange(error) %>%
#  top_n(-5, wt = error)

#Chose the optimal model and predict on the testset
#The final RMSE is 39145.39 which suggests that, on average, our predicted sales prices are about $39,145 off from the actual sales price.

optimal_tree <- rpart(
    formula = Sale_Price ~ .,
    data    = data_train,
    method  = "anova",
    control = list(minsplit = 11, maxdepth = 8, cp = 0.01)
    )

pred <- predict(optimal_tree, newdata = data_test)
RMSE(pred = pred, obs = data_test$Sale_Price)
## [1] 39852.01
rpart.plot(optimal_tree)

############################################################################################
#We can use another way to improve the model performance by using gradient boostrap technique
#This is very simple/ basic way to do it
#we perform a 10-fold cross-validated model. We see that the cross-validated RMSE is $36,477. We also assess the top 20 variables from our model. Variable importance for regression trees is measured by assessing the total amount SSE is decreased by splits over a given predictor, averaged over all m trees. The predictors with the largest average impact to SSE are considered most important. The importance value is simply the relative mean decrease in SSE compared to the most important variable (provides a 0-100 scale).

# Specify 10-fold cross validation
ctrl <- trainControl(method = "cv",  number = 10) 

# CV bagged model
bagged_cv <- train(
  Sale_Price ~ .,
  data = data_train,
  method = "treebag",
  trControl = ctrl,
  importance = TRUE
  )

# assess results
#bagged_cv
head(bagged_cv)
## $method
## [1] "treebag"
## 
## $modelInfo
## $modelInfo$label
## [1] "Bagged CART"
## 
## $modelInfo$library
## [1] "ipred" "plyr"  "e1071"
## 
## $modelInfo$loop
## NULL
## 
## $modelInfo$type
## [1] "Regression"     "Classification"
## 
## $modelInfo$parameters
##   parameter     class     label
## 1 parameter character parameter
## 
## $modelInfo$grid
## function(x, y, len = NULL, search = "grid") data.frame(parameter = "none")
## 
## $modelInfo$fit
## function(x, y, wts, param, lev, last,classProbs, ...) {
##                     theDots <- list(...)
##                     if(!any(names(theDots) == "keepX")) theDots$keepX <- FALSE   
##                     modelArgs <- c(list(X = x, y = y), theDots)
##                     if(!is.null(wts)) modelArgs$weights <- wts
##                     do.call(ipred::ipredbagg, modelArgs)
##                   }
## <bytecode: 0x00000000235d8e58>
## 
## $modelInfo$predict
## function(modelFit, newdata, submodels = NULL) 
##                     predict(modelFit, newdata)
## <bytecode: 0x000000001ea2b308>
## 
## $modelInfo$prob
## function(modelFit, newdata, submodels = NULL)
##                     predict(modelFit, newdata, type = "prob")
## 
## $modelInfo$predictors
## function(x, surrogate = TRUE, ...) {
##                     code <- getModelInfo("rpart", regex = FALSE)[[1]]$predictors
##                     eachTree <- lapply(x$mtree,
##                                        function(u, surr) code(u$btree, surrogate = surr),
##                                        surr = surrogate)
##                     unique(unlist(eachTree))
##                   }
## 
## $modelInfo$varImp
## function(object, ...) {
##                     allImp <- lapply(object$mtrees, function(x) varImp(x$btree), ...)
##                     allImp <- lapply(allImp, 
##                                      function(x) {
##                                        x$variable <- rownames(x)
##                                        x
##                                      })
##                     allImp <- do.call("rbind", allImp)
##                     meanImp <- plyr::ddply(allImp, plyr::`.`(variable),
##                                      function(x) c(Overall = mean(x$Overall)))
##                     out <- data.frame(Overall = meanImp$Overall)
##                     rownames(out) <- meanImp$variable
##                     out
##                   }
## 
## $modelInfo$trim
## function(x) {
##                     trim_rpart <- function(x) {
##                       x$call <- list(na.action = (x$call)$na.action)
##                       x$x <- NULL
##                       x$y <- NULL
##                       x$where <- NULL
##                       x
##                     }
##                     x$mtrees <- lapply(x$mtrees, 
##                                        function(x){
##                                          x$bindx <- NULL
##                                          x$btree <- trim_rpart(x$btree)
##                                          x
##                                        } )
##                     x
##                   }
## 
## $modelInfo$tags
## [1] "Tree-Based Model"     "Ensemble Model"       "Bagging"             
## [4] "Accepts Case Weights"
## 
## $modelInfo$levels
## function(x) levels(x$y)
## 
## $modelInfo$sort
## function(x) x
## 
## $modelInfo$oob
## function(x) {
##                     if(is.null(x$X)) stop("to get OOB stats, keepX must be TRUE when calling the bagging function")
##                     foo <- function(object, y, x) {
##                       holdY <- y[-object$bindx]
##                       tmp_x <- x[-object$bindx,,drop = FALSE]
##                       if(!is.data.frame(tmp_x)) tmp_x <- as.data.frame(tmp_x)
##                       if(is.factor(y)) {
##                         tmp <- predict(object$btree, tmp_x, type = "class")
##                         tmp <- factor(as.character(tmp), levels = levels(y))
##                         out <- c(mean(holdY == tmp), e1071::classAgreement(table(holdY, tmp))$kappa)
##                       } else {
##                         tmp <- predict(object$btree, tmp_x)
##                         out <- c(sqrt(mean((tmp - holdY)^2, na.rm = TRUE)),
##                                  cor(holdY, tmp, use = "pairwise.complete.obs")^2)
##                       }
##                       out
##                     }
##                     eachStat <- lapply(x$mtrees, foo, y = x$y, x = x$X)
##                     eachStat <- matrix(unlist(eachStat), nrow = length(eachStat[[1]]))
##                     out <- c(apply(eachStat, 1, mean, na.rm = TRUE),
##                              apply(eachStat, 1, sd, na.rm = TRUE))
##                     names(out) <- if(is.factor(x$y)) c("Accuracy", "Kappa", "AccuracySD", "KappaSD") else c("RMSE", "Rsquared", "RMSESD", "RsquaredSD")
##                     out
##                   }
## 
## 
## $modelType
## [1] "Regression"
## 
## $results
##   parameter     RMSE  Rsquared      MAE   RMSESD RsquaredSD    MAESD
## 1      none 36834.63 0.7901117 24197.65 5669.688 0.06419819 2195.575
## 
## $pred
## NULL
## 
## $bestTune
##   parameter
## 1      none
#http://uc-r.github.io/regression_trees