-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCh3_Regression_Python.Rmd
1448 lines (1065 loc) · 53.3 KB
/
Ch3_Regression_Python.Rmd
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
---
title: "Regression"
author: "Your Name"
date: "2023-12-21"
output: html_document
---
```{R setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE,message=FALSE,fig.align="center",fig.width=7,fig.height=2.5)
```
```{css,echo=FALSE}
.btn {
border-width: 0 0px 0px 0px;
font-weight: normal;
text-transform: ;
}
.btn-default {
color: #2ecc71;
background-color: #ffffff;
border-color: #ffffff;
}
```
```{python,echo=FALSE}
# Global parameter
show_code = True
```
# Class Workbook {.tabset .tabset-fade .tabset-pills}
## In class activity
```{python}
import numpy as np
import pandas as pd
import math
from matplotlib.pyplot import subplots
#import statsmodels.api as sm
from plotnine import *
import plotly.express as px
import statsmodels.formula.api as sm
#import ISLP as islp
```
### Ames Housing data
Please take a look at the Ames Hoursing data.
```{python}
ames_raw=pd.read_csv("ames_raw.csv")
```
The goal of this exercise is to predict the price of the house.
Here is a histogram of the sales price with red line showing the mean.
```{python,fig.width=7,fig.height=4.5}
(
ggplot(ames_raw)+geom_histogram(fill="skyblue")+aes(x="SalePrice")+
geom_vline(xintercept = ames_raw.loc[:,"SalePrice"].mean(),colour="red")
)
```
Initial linear model without a predictor
```{python}
y = 'SalePrice'
x = "1"
formula = '%s ~ %s' % (y, x)
lmfit_null = sm.ols(formula, data=ames_raw).fit()
print(lmfit_null.summary())
```
How good is this result? Let's look at RMSE.
```{python}
pow(lmfit_null.resid.pow(2).mean(),1/2)
```
Since the price is right skewed lets log transformation the outcome
```{python,fig.width=7,fig.height=4.5}
(
ggplot(ames_raw)+geom_histogram(fill="skyblue")
+aes(x="SalePrice")+geom_vline(xintercept =math.exp(np.log(ames_raw.loc[:,"SalePrice"]).mean()),colour="red")
+scale_x_log10()
)
```
Fitting the same model on the log transformed outcome
```{python}
ames_raw_temp=ames_raw.copy(deep=False)
ames_raw_temp.loc[:,"SalePrice"]=np.log(ames_raw_temp.loc[:,"SalePrice"])
y = 'SalePrice'
x = "1"
logformula = '%s ~ %s' % (y, x)
lmfit_null_log = sm.ols(logformula, data=ames_raw_temp).fit()
print(lmfit_null_log.summary())
```
RMSE is
```{python}
logresid=ames_raw.loc[:,"SalePrice"]-np.exp(lmfit_null_log.predict())
pow(logresid.pow(2).mean(),1/2)
```
Notice that the RMSE is actually bigger with log transformed model.
So should we not transform? What do we get from the transformation?
Here is the prediction uncertainty overlayed on the histogram.
```{python,fig.width=7,fig.height=4.5}
dt =lmfit_null.get_prediction(ames_raw.iloc[1,1:2]).summary_frame(alpha = 0.05)
y_prd = dt['mean']
yprd_ci_lower = dt['obs_ci_lower']
yprd_ci_upper = dt['obs_ci_upper']
(
ggplot(ames_raw)+geom_histogram(fill="skyblue")
+aes(x="SalePrice")
+geom_vline(xintercept = y_prd,colour="red")
+geom_vline(xintercept = yprd_ci_lower,colour="red",linetype="dotted")
+geom_vline(xintercept = yprd_ci_upper,colour="red",linetype="dotted")
)
```
```{python,fig.width=7,fig.height=4.5}
logdt =lmfit_null_log.get_prediction(ames_raw.iloc[1,1:2]).summary_frame(alpha = 0.05)
logy_prd = (logdt['mean'])
logyprd_ci_lower = (logdt['obs_ci_lower'])
logyprd_ci_upper = (logdt['obs_ci_upper'])
(
ggplot(ames_raw_temp)+geom_histogram(fill="skyblue")
+aes(x="SalePrice")
+geom_vline(xintercept = logy_prd,colour="red")
+geom_vline(xintercept = logyprd_ci_lower,colour="red",linetype="dotted")
+geom_vline(xintercept = logyprd_ci_upper,colour="red",linetype="dotted")
)
```
The log model seem to have a better uncertainty estimate. What good does that do?
Let’s say the model is for an algorithm that buys the house. If you pay more than the true price the company buys. If the price is lower, then the company fails to buy.
- If you bought for more than the true value you’ve over paid.
- If you bid less and lost, you lost a profit of the 10% of the house price.
Based on such loss function what is our overall loss if we base our decision on this model?
```{python}
allres=lmfit_null.resid
abs(sum(allres[allres<0]))+sum(0.1*(lmfit_null.params["Intercept"]+allres[allres>0]))
```
```{python}
allreslog=ames_raw.loc[:,"SalePrice"]-np.exp(lmfit_null_log.predict(ames_raw_temp))
abs(sum(allreslog[allreslog<0]))+sum(0.1*(math.exp(lmfit_null_log.params["Intercept"])+allreslog[allreslog>0]))
```
As you can see with a better calibrated model you have a better performance for more realistic loss.
### Adding predictor `Gr Liv Area`
We add a predictor `Gr Liv Area`
```{python,fig.width=7,fig.height=4,fig.width=7,fig.height=5.5}
fig = px.scatter(ames_raw, x="Gr Liv Area", y="SalePrice", marginal_x="histogram", marginal_y="histogram")
fig.show()
```
Using `Gr Liv Area` as predictor
```{python}
lmfit_liv_area_0 = sm.ols("SalePrice ~ Q('Gr Liv Area')", data=ames_raw).fit()
lmfit_liv_area_1 = sm.ols("np.log(SalePrice)~Q('Gr Liv Area')", data=ames_raw).fit()
lmfit_liv_area_2 = sm.ols("np.log(SalePrice) ~np.log(Q('Gr Liv Area'))", data=ames_raw).fit()
print(lmfit_liv_area_0.summary())
print(lmfit_liv_area_1.summary())
print(lmfit_liv_area_2.summary())
```
```{python,fig.width=9,fig.height=6}
import patchworklib as pw
g = (
ggplot(ames_raw)+geom_point()+aes(x="Gr Liv Area",y="SalePrice")
+xlab("Above grade (ground) living area square feet")+ylab("Sale Price")
+geom_smooth(method="lm",se=False)
)
g1 = pw.load_ggplot(g, figsize=(4,4))
g = (
ggplot(ames_raw)+geom_point()+aes(x="Gr Liv Area",y="SalePrice")
+xlab("Above grade (ground) living area square feet")+ylab("Sale Price")+geom_smooth(method="lm",se=False)+scale_y_log10()
)
g2 = pw.load_ggplot(g, figsize=(4,4))
g = (
ggplot(ames_raw)+geom_point()+aes(x="Gr Liv Area",y="SalePrice")+xlab("Above grade (ground) living area square feet")+ylab("Sale Price")+geom_smooth(method="lm",se=False)+scale_y_log10()+scale_x_log10()
)
g3 = pw.load_ggplot(g, figsize=(4,4))
g12 = (g1|g2|g3)
g12.savefig("./Images/multiplots.png")
#knitr::include_graphics("./multiplots.png")
```
![fig](Images/multiplots.png)
```{python}
df = pd.DataFrame({'prediction':lmfit_liv_area_0.predict, 'residual':lmfit_liv_area_0.resid})
g = (
ggplot(df)+aes(x="prediction",y="residual")+geom_smooth()+geom_hline(yintercept = 0,linetype="dotted"),
)
df2 = pd.DataFrame({'prediction':lmfit_liv_area_1.predict(), 'residual':lmfit_liv_area_1.resid})
g = (
ggplot(df2)+aes(x="prediction",y="residual")+geom_smooth()+geom_hline(yintercept = 0,linetype="dotted"),
)
df3 = pd.DataFrame({'prediction':lmfit_liv_area_2.predict(), 'residual':lmfit_liv_area_2.resid})
g = (
ggplot(df3)+aes(x="prediction",y="residual")+geom_smooth()+geom_hline(yintercept = 0,linetype="dotted")
)
```
Because of the skewness it's better to take log on both x and y.
```{python,fig.width=7,fig.height=4,fig.width=7,fig.height=5.5}
px_fig_log = px.scatter(ames_raw, x="Gr Liv Area", y="SalePrice", marginal_x="histogram", marginal_y="histogram", log_x=True, log_y=True)
px_fig_log.show()
```
```{python,fig.width=6,fig.height=4}
lm_mod_1 = sm.ols("np.log(SalePrice) ~np.log(Q('Gr Liv Area'))", data=ames_raw).fit()
print(lm_mod_1.summary())
```
However, the residual still shows heterogeneous spread.
```{python,fig.width=7,fig.height=4.5}
from matplotlib.pyplot import subplots
fig , ax = subplots(figsize=(8, 8))
x = lm_mod_1.predict(ames_raw)
y = lm_mod_1.resid
ax.scatter(x, y);
ax.set_xlabel("predicted")
ax.set_ylabel("residual")
ax.set_title("residual plot");
ax.axhline(0, c='k', ls='--');
fig.tight_layout()
fig.show()
# abline(h=0,lty=2,col="grey")
# library(quantreg)
# qu<-rq(resid(lm_mod_1)~predict(lm_mod_1),tau = c(0.1, 0.9))
#
# colors <- c("#ffe6e6", "#ffcccc", "#ff9999", "#ff6666", "#ff3333",
# "#ff0000", "#cc0000", "#b30000", "#800000", "#4d0000", "#000000")
# for (j in 1:ncol(qu$coefficients)) {
# abline(coef(qu)[, j], col = colors[j])
# }
```
Did we reduce the residual variability?
```{python,fig.width=7,fig.height=4,fig.width=7,fig.height=4.5}
logSalePrice=np.log(ames_raw.loc[:,"SalePrice"])
clogSalePricec = logSalePrice-logSalePrice.mean()
rlogSalePricec = lm_mod_1.resid
#labs<-c("mean","regression")
#names(labs)<-c("clogSalePricec","rlogSalePricec")
df = pd.DataFrame({"mean": clogSalePricec,
"regression": rlogSalePricec})
(
ggplot(pd.melt(df))+
geom_histogram(fill="skyblue")+
aes(x="value",color="variable")+geom_vline(xintercept = 0,colour="red")+
facet_grid('variable~.')
)
```
```{python}
from statsmodels.stats.anova import anova_lm
anova_lm(lm_mod_1)
```
Looking at correlation with predictors.
```{python,fig.width=9,fig.height=7}
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme(style="white")
# Compute the correlation matrix
ames_corr = ames_raw.loc[:,["Lot Area","Year Built","Year Remod/Add","Total Bsmt SF","1st Flr SF","2nd Flr SF","Low Qual Fin SF","Gr Liv Area","Full Bath","Half Bath","Bsmt Full Bath","Bsmt Half Bath","TotRms AbvGrd","Garage Area","Wood Deck SF","Open Porch SF","Pool Area","SalePrice"]].corr()
# Generate a mask for the upper triangle
mask = np.triu(np.ones_like(ames_corr, dtype=bool))
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(230, 20, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
ss=sns.heatmap(ames_corr, mask=mask, cmap=cmap, vmax=.3, center=0,
square=True, linewidths=.5, cbar_kws={"shrink": .5})
#ss.savefig('correlation_heatmap.png')
plt.show()
```
```{python,fig.width=9,fig.height=7}
mames=ames_raw.loc[:,["Lot Area","Year Built","Year Remod/Add","Total Bsmt SF","1st Flr SF","2nd Flr SF","Low Qual Fin SF","Gr Liv Area","Full Bath","Half Bath","Bsmt Full Bath","Bsmt Half Bath","TotRms AbvGrd","Garage Area","Wood Deck SF","Open Porch SF","Pool Area","SalePrice"]].melt(id_vars = "SalePrice")
(ggplot(mames)+geom_point()+aes(x="value",y="SalePrice")+facet_wrap('~variable',scales = "free"))
```
### thinking about the `Lot Area`
When looking at lot area, its no surprise to have some relationship with the price.
But the relationship is not clear linear one. Why?
```{python,fig.width=6,fig.height=4}
(
ggplot(ames_raw)+geom_point()+aes(x="Lot Area",y="SalePrice")+xlab("Lot size in square feet")+ylab("Sale Price")+geom_smooth(method="lm",se=False)+scale_y_log10()+scale_x_log10()#+facet_grid(~`Bedroom AbvGr`)
)
```
If you look at this by the neighborhood it become obvious how in some places size matters more than others.
```{python,fig.width=9,fig.height=7}
(
ggplot(ames_raw)+geom_point(alpha=0.3)
+aes(x="Lot Area",y="SalePrice",color="Neighborhood")+xlab("Above grade (ground) living area square feet")+ylab("Sale Price")
+geom_smooth(method="lm",se=False)+scale_y_log10()+scale_x_log10()
+facet_wrap('~Neighborhood')
)
```
### Prediction of future price based on data upto 2008
To make the project more realistic, I will split the data into before 2008 and after.
The data up to 2008 will be the training data nd after will be the testing data.
```{python}
ames_raw_2009, ames_raw_2008= ames_raw.query('`Yr Sold`>=2008').copy(), ames_raw.query('`Yr Sold` <2008').copy()
```
If you look at the time trend, it seems the price is fairly stable over the years.
```{python,warning=FALSE}
ames_raw['saledt'] = pd.to_datetime(dict(year=ames_raw.loc[:,"Yr Sold"], month=ames_raw.loc[:,"Mo Sold"],day=1))
fig = px.scatter(ames_raw, x="saledt",y="SalePrice", marginal_x="histogram", marginal_y="histogram", trendline="lowess")
fig.add_vline(x="2008-01-01", line_width=3, line_dash="dash", line_color="orange")
fig.show()
```
Fitting the null model on the training data
```{python}
lmfit_null_2008 = sm.ols("SalePrice~1",ames_raw_2008).fit()
lmfit_null_log_2008 = sm.ols("np.log(SalePrice)~1",ames_raw_2008).fit()
```
Comparing the MSE
```{python}
allres_2009=ames_raw_2009.loc[:,"SalePrice"]-lmfit_null_2008.predict(ames_raw_2009)
pow(allres_2009.pow(2).mean(),1/2)
allres_2009_log=ames_raw_2009.loc[:,"SalePrice"]-np.exp(lmfit_null_log_2008.predict(ames_raw_2009))
pow(allres_2009_log.pow(2).mean(),1/2)
# sqrt(mean((ames_raw_2009$SalePrice-predict(lmfit_null,newdata=ames_raw_2009))^2))
# sqrt(mean((ames_raw_2009$SalePrice-exp(predict(lmfit_null_log,newdata=ames_raw_2009)))^2))
```
Comparing the business loss
```{python}
abs(sum(allres_2009[allres_2009<0]))+sum(0.1*(lmfit_null_2008.params["Intercept"]+allres_2009[allres_2009>0]))
abs(sum(allres_2009_log[allres_2009_log<0]))+sum(0.1*(lmfit_null_log_2008.params["Intercept"]+allres_2009_log[allres_2009_log>0]))
# allres_2009=ames_raw_2009$SalePrice-predict(lmfit_null,newdata=ames_raw_2009)
# abs(sum(allres_2009[allres_2009<0]))+sum(0.1*(coef(lmfit_null_2008)+allres_2009[allres_2009>0]))
#
# allreslog_2009<-(ames_raw_2009$SalePrice-exp(predict(lmfit_null_log,newdata=ames_raw_2009)))
# abs(sum(allreslog_2009[allreslog_2009<0]))+sum(0.1*(exp(coef(lmfit_null_log_2008))+allreslog_2009[allreslog_2009>0]))
```
### In class activity
Use data of `ames_raw` up to 2008 predict the housing price for the later years.
```{python}
ames_raw_2009, ames_raw_2008= ames_raw.query('`Yr Sold`>=2008').copy(), ames_raw.query('`Yr Sold` <2008').copy()
```
Use the following loss function calculator.
```{python}
def calc_loss(prediction,actual):
difpred = actual-prediction
RMSE =pow(difpred.pow(2).mean(),1/2)
operation_loss=abs(sum(difpred[difpred<0]))+sum(0.1*actual[difpred>0])
return RMSE,operation_loss
```
Here are few rules:
- You are not allowed to use the test data.
- You cannot use automatic variable selection.
- You need to explain why you added each variable.
```{python,eval=FALSE}
lmfit_2008= # ["your model here"] # use ames_raw_2008
```
When you decide on your model use the following to come up with your test loss.
```{python,eval=FALSE}
pred_2009=exp(lmfit_2008.predict(ames_raw_2009))
calc_loss(pred_2009,ames_raw_2009.loc[:,"SalePrice"])
```
Try to answer the following additional questions.
- Does your model indicate a good fit? If not where is the fit off?
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
- Should you include all the predictors? Why?
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
- What interaction makes sense? Does your model indicate signs of interaction?
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
- Is there evidence of non-linear association between any of the predictors and the response? To answer this question, for each predictor, fit a model with polynomial terms up to 3rd order.
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
- What are the top 5 houses that are most over priced based on your model?
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
- What are the top 5 most good deal based on your model?
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
## Problem Set
### [Problems] Linear Regression Problems
8. This question involves the use of simple linear regression on the Auto
data set.
8. This question involves the use of simple linear regression on the `Auto` data set.
(a) Use the sm.OLS() function to perform a simple linear regression
with mpg as the response and horsepower as the predictor. Use
the summarize() function to print the results.
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
Comment on the output.
For example:
i. Is there a relationship between the predictor and the response?
ii. How strong is the relationship between the predictor and the response?
iii. Is the relationship between the predictor and the response positive or negative?
iv. What is the predicted mpg associated with a horsepower of 98? What are the associated 95% confidence and prediction intervals?
(b) Plot the response and the predictor in a new set of axes ax. Use
the ax.axline() method or the abline() function defined in the
lab to display the least squares regression line.
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(c) Produce some of diagnostic plots of the least squares regression
fit as described in the lab. Comment on any problems you see
with the fit.
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
9. This question involves the use of multiple linear regression on the `Auto` data set.
(a) Produce a scatterplot matrix which includes all of the variables in the data set.
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(b) Compute the matrix of correlations between the variables using
the DataFrame.corr() method.
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(c) Use the sm.OLS() function to perform a multiple linear regression
with mpg as the response and all other variables except name as
the predictors. Use the summarize() function to print the results.
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
Comment on the output. For instance:
i. Is there a relationship between the predictors and the response?
Use the anova_lm() function from statsmodels to
answer this question.
ii. Which predictors appear to have a statistically significant
relationship to the response?
iii. What does the coefficient for the year variable suggest?
(d) Produce some of diagnostic plots of the linear regression fit as
described in the lab. Comment on any problems you see with the
fit. Do the residual plots suggest any unusually large outliers?
Does the leverage plot identify any observations with unusually
high leverage?
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(e) Fit some models with interactions as described in the lab. Do any interactions appear to be statistically significant?
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(f) Try a few different transformations of the variables, such as log(X), 'X, X2. Comment on your findings.
10 This question should be answered using the Carseats data set.
(a) Fit a multiple regression model to predict Sales using Price, Urban, and US.
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(b) Provide an interpretation of each coefficient in the model. Be careful—some of the variables in the model are qualitative!
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(c) Write out the model in equation form, being careful to handle the qualitative variables properly.
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(d) For which of the predictors can you reject the null hypothesis $H_0 :\beta_j = 0$?
Your answer:
~~~
Please write your answer in full sentences.
~~~
(e) On the basis of your response to the previous question, fit a smaller model that only uses the predictors for which there is evidence of association with the outcome.
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(f) How well do the models in (a) and (e) fit the data?
Your answer:
~~~
Please write your answer in full sentences.
~~~
(g) Using the model from (e), obtain 95% confidence intervals for the coefficient(s).
Your code:
```{python,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(h) Is there evidence of outliers or high leverage observations in the model from (e)?
Your answer:
~~~
Please write your answer in full sentences.
~~~
## Additional Material
In Python, most of the functions used for Machine Learning is in the sklearn package.
https://scikit-learn.org/stable/tutorial/basic/tutorial.html
### K-nn regression
You can do KNN regression using sklearn.neighbors.KNeighborsRegressor.
Read more about it here:
https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsRegressor.html
```{python, eval=TRUE, echo=TRUE}
X = [[0], [1], [2], [3]]
y = [0, 0, 1, 1]
from sklearn.neighbors import KNeighborsRegressor
neigh = KNeighborsRegressor(n_neighbors=2)
neigh.fit(X, y)
```
### [Advanced] Predictive Modeling Platforms in Python
There are few platforms in Python that does predictive modeling.
These platforms are wrappers around other packages that makes it easy to do routine tasks.
- scikit-learn (https://scikit-learn.org/stable/)
- PySpark (https://spark.apache.org/docs/latest/api/python/index.html)
- h2o (https://docs.h2o.ai/h2o/latest-stable/h2o-r/docs/index.html)
#### scikit-learn
```{python, echo=TRUE}
from sklearn.model_selection import train_test_split
# split the data
X_train, X_test, y_train, y_test = train_test_split(ames_raw.loc[:,ames_raw.columns != "SalePrice"], ames_raw.loc[:,"SalePrice"], test_size=0.33, random_state=42)
train_df = pd.concat([X_train, y_train], axis=1)
test_df = pd.concat([X_test, y_test], axis=1)
```
#### PySpark
[Apache Spark](https://spark.apache.org/docs/3.1.3/api/python/index.html) is a popular large data handling platform. Over the years, they built Machine Learning capabilities in MLlib.
```{python,eval=FALSE, echo=TRUE}
import pyspark
from pyspark.sql import SparkSession
from pyspark.ml.regression import LinearRegression
from pyspark.ml.feature import VectorAssembler
```
```{python,eval=FALSE, echo=TRUE}
spark = SparkSession.builder.appName("AmesHousing").getOrCreate()
```
```{python,eval=FALSE, echo=TRUE}
ames_raw_sparkDF=spark.createDataFrame(ames_raw)
ames_raw_sparkDF.printSchema()
ames_raw_sparkDF.show()
```
```{python,eval=FALSE, echo=TRUE}
featureassembler = VectorAssembler(inputCols = ["Gr Liv Area","Lot Area","Year Built"], outputCol = "Independent Features")
output = featureassembler.transform(ames_raw_sparkDF)
output.select("Independent Features").show()
finalised_data = output.select("Independent Features", "SalePrice")
```
```{python,eval=FALSE, echo=TRUE}
train_data, test_data = finalised_data.randomSplit([0.75, 0.25])
```
```{python,eval=FALSE, echo=TRUE}
regressor = LinearRegression(featuresCol = "Independent Features", labelCol = 'SalePrice')
regressor = regressor.fit(train_data)
```
```{python,eval=FALSE, echo=TRUE}
pred_results = regressor.evaluate(test_data)
pred_results.predictions.show()
spark.stop()
```
#### Prediction using h2o
H2O is a cross platform library that is popular in the predictive modeling space. They work well out of box and can be called from any platform independent of the language used. Making it work on R could sometimes be a headache. So try using H2O but if you cannot make it work, I recommend you leave this section alone.
If you are on Mac you will need to install Java (http://www.java.com ).
https://docs.h2o.ai/h2o/latest-stable/h2o-py/docs/intro.html
```{python,eval=FALSE, echo=TRUE}
#pip install requests
#pip install tabulate
#pip uninstall h2o
#pip install -f http://h2o-release.s3.amazonaws.com/h2o/latest_stable_Py.html h2o
# load packages and data
import h2o
```
##### Starting H2O
To use H2O you need to instantiate it.
```{python,eval=FALSE, echo=TRUE}
# nthreads specifies number of threads. -1 means use all the CPU cores.
# max_mem_size specifies the maximum amount of RAM to use.
localH2O= h2o.init(nthreads = -1, max_mem_size="4g")
```
You can access H2O instance using the web UI FLOW by typing
http://localhost:54321
in your browser.
##### Serving the data to H2O
Since H2O is not in R, you need to tell it to use your data.
```{python,eval=FALSE, echo=TRUE}
train_hf = h2o.H2OFrame(train_df)
test_hf = h2o.H2OFrame(test_df)
```
##### Fitting GLM
```{python h2o_fit_glm,eval=FALSE, echo=TRUE}
from h2o.estimators.glm import H2OGeneralizedLinearEstimator
predictors=["SalePrice","Lot.Area","Gr.Liv.Area","Full.Bath"]
model = H2OGeneralizedLinearEstimator( #response variable
#predictor variables
training_frame = train_hf, #data
family = "gaussian") #specify the dist. of y and penalty parameter: lambda
model.train(y = "SalePrice",x = predictors)
prediction=model.predict(test_hf)
h2o.export_file(prediction, "/tmp/pred.csv") #export prediction result as a file
```
##### Saving and loading the model
```{python,eval=FALSE, echo=TRUE}
# save the model
model_path = h2o.save_model(model, path="/tmp/mymodel", force=True)
print(model_path)
# load the model
saved_model = h2o.load_model(model_path) #extract the saved model
saved_model
```
##### Shut down H2O
```{python,eval=FALSE, echo=TRUE}
h2o.cluster().shutdown(prompt =False)
```
#### PyCaret
PyCaret (https://pycaret.org) is like Caret in R, it's a wrapper around several machine learning libraries and frameworks such as scikit-learn, XGBoost, LightGBM, CatBoost, spaCy, Optuna, Hyperopt, Ray, and few more. Because of how it's done so well, it's starting to become the goto hub for many people who wants to do machine learning.
You can find the Regression Example here:
https://github.com/pycaret/pycaret/blob/master/tutorials/Tutorial%20-%20Regression.ipynb
## Advanced Content
### Best Linear Unbiased Estimator
#### Euler and motion of planets
The idea of regression started with Euler(1949) when he was studying the motion of planets. He wanted to predict the location of Jupiter. Euler had 75 observations for a linear model with seven unknown constants; equivalently, he had 75 equations and seven unknowns.
Let's translate this into a more familiar notation that we are used to. We will let
\begin{eqnarray*}
y_i=\varphi_i\verb|, |\boldsymbol{\beta}=\left(\begin{array}{c}
\beta_1\\
\beta_2\\
\vdots\\
\beta_p
\end{array}\right)