-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSection_3312_Variable_Interactions_&_Transformations-Copy1.html
More file actions
912 lines (879 loc) · 53.6 KB
/
Section_3312_Variable_Interactions_&_Transformations-Copy1.html
File metadata and controls
912 lines (879 loc) · 53.6 KB
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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<meta name="generator" content="quarto-1.0.37">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>Variable interactions and transformations</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
color: #aaaaaa;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span.al { color: #ff0000; font-weight: bold; } /* Alert */
code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #7d9029; } /* Attribute */
code span.bn { color: #40a070; } /* BaseN */
code span.bu { } /* BuiltIn */
code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4070a0; } /* Char */
code span.cn { color: #880000; } /* Constant */
code span.co { color: #60a0b0; font-style: italic; } /* Comment */
code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #ba2121; font-style: italic; } /* Documentation */
code span.dt { color: #902000; } /* DataType */
code span.dv { color: #40a070; } /* DecVal */
code span.er { color: #ff0000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #40a070; } /* Float */
code span.fu { color: #06287e; } /* Function */
code span.im { } /* Import */
code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #007020; font-weight: bold; } /* Keyword */
code span.op { color: #666666; } /* Operator */
code span.ot { color: #007020; } /* Other */
code span.pp { color: #bc7a00; } /* Preprocessor */
code span.sc { color: #4070a0; } /* SpecialChar */
code span.ss { color: #bb6688; } /* SpecialString */
code span.st { color: #4070a0; } /* String */
code span.va { color: #19177c; } /* Variable */
code span.vs { color: #4070a0; } /* VerbatimString */
code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
</style>
<script src="Section_3312_Variable_Interactions_&_Transformations-Copy1_files/libs/clipboard/clipboard.min.js"></script>
<script src="Section_3312_Variable_Interactions_&_Transformations-Copy1_files/libs/quarto-html/quarto.js"></script>
<script src="Section_3312_Variable_Interactions_&_Transformations-Copy1_files/libs/quarto-html/popper.min.js"></script>
<script src="Section_3312_Variable_Interactions_&_Transformations-Copy1_files/libs/quarto-html/tippy.umd.min.js"></script>
<script src="Section_3312_Variable_Interactions_&_Transformations-Copy1_files/libs/quarto-html/anchor.min.js"></script>
<link href="Section_3312_Variable_Interactions_&_Transformations-Copy1_files/libs/quarto-html/tippy.css" rel="stylesheet">
<link href="Section_3312_Variable_Interactions_&_Transformations-Copy1_files/libs/quarto-html/quarto-syntax-highlighting.css" rel="stylesheet" id="quarto-text-highlighting-styles">
<script src="Section_3312_Variable_Interactions_&_Transformations-Copy1_files/libs/bootstrap/bootstrap.min.js"></script>
<link href="Section_3312_Variable_Interactions_&_Transformations-Copy1_files/libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="Section_3312_Variable_Interactions_&_Transformations-Copy1_files/libs/bootstrap/bootstrap.min.css" rel="stylesheet" id="quarto-bootstrap" data-mode="light">
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" integrity="sha512-c3Nl8+7g4LMSTdrm621y7kf9v3SDPnhxLNhcjFJbKECVnmZHTdo+IRO05sNLTH/D3vA6u1X32ehoLC7WFVdheg==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
<script type="application/javascript">define('jquery', [],function() {return window.jQuery;})</script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml-full.js" type="text/javascript"></script>
</head>
<body class="fullcontent">
<div id="quarto-content" class="page-columns page-rows-contents page-layout-article">
<main class="content" id="quarto-document-content">
<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title">
<h1 class="title">Variable interactions and transformations</h1>
</div>
<div class="quarto-title-meta">
</div>
</header>
<section id="variable-interactions" class="level2">
<h2 class="anchored" data-anchor-id="variable-interactions">Variable interactions</h2>
<div class="cell" data-execution_count="2">
<div class="sourceCode cell-code" id="cb1"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> pandas <span class="im">as</span> pd</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> numpy <span class="im">as</span> np</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> statsmodels.formula.api <span class="im">as</span> smf</span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> seaborn <span class="im">as</span> sns</span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> matplotlib.pyplot <span class="im">as</span> plt</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div class="cell" data-execution_count="3">
<div class="sourceCode cell-code" id="cb2"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>trainf <span class="op">=</span> pd.read_csv(<span class="st">'./Datasets/Car_features_train.csv'</span>)</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>trainp <span class="op">=</span> pd.read_csv(<span class="st">'./Datasets/Car_prices_train.csv'</span>)</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>testf <span class="op">=</span> pd.read_csv(<span class="st">'./Datasets/Car_features_test.csv'</span>)</span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>testp <span class="op">=</span> pd.read_csv(<span class="st">'./Datasets/Car_prices_test.csv'</span>)</span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>train <span class="op">=</span> pd.merge(trainf,trainp)</span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>train.head()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="3">
<div>
<table class="dataframe table table-sm table-striped">
<thead>
<tr>
<th></th>
<th>carID</th>
<th>brand</th>
<th>model</th>
<th>year</th>
<th>transmission</th>
<th>mileage</th>
<th>fuelType</th>
<th>tax</th>
<th>mpg</th>
<th>engineSize</th>
<th>price</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>18473</td>
<td>bmw</td>
<td>6 Series</td>
<td>2020</td>
<td>Semi-Auto</td>
<td>11</td>
<td>Diesel</td>
<td>145</td>
<td>53.3282</td>
<td>3.0</td>
<td>37980</td>
</tr>
<tr>
<th>1</th>
<td>15064</td>
<td>bmw</td>
<td>6 Series</td>
<td>2019</td>
<td>Semi-Auto</td>
<td>10813</td>
<td>Diesel</td>
<td>145</td>
<td>53.0430</td>
<td>3.0</td>
<td>33980</td>
</tr>
<tr>
<th>2</th>
<td>18268</td>
<td>bmw</td>
<td>6 Series</td>
<td>2020</td>
<td>Semi-Auto</td>
<td>6</td>
<td>Diesel</td>
<td>145</td>
<td>53.4379</td>
<td>3.0</td>
<td>36850</td>
</tr>
<tr>
<th>3</th>
<td>18480</td>
<td>bmw</td>
<td>6 Series</td>
<td>2017</td>
<td>Semi-Auto</td>
<td>18895</td>
<td>Diesel</td>
<td>145</td>
<td>51.5140</td>
<td>3.0</td>
<td>25998</td>
</tr>
<tr>
<th>4</th>
<td>18492</td>
<td>bmw</td>
<td>6 Series</td>
<td>2015</td>
<td>Automatic</td>
<td>62953</td>
<td>Diesel</td>
<td>160</td>
<td>51.4903</td>
<td>3.0</td>
<td>18990</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>Until now, we have have assumed that the association between a predictor <span class="math inline">\(X_j\)</span> and response <span class="math inline">\(Y\)</span> does not depend on the value of other predictors. For example, the muliple linear regression model that we developed in Chapter <a href="https://nustat.github.io/STAT303-2-class-notes/Lec2_MultipleLinearRegression.html">2</a> assumes that the average increase in price associated with a unit increase in engineSize is always $12,180, regardless of the value of other predictors. However, this assumption may be incorrect.</p>
<section id="variable-interaction-between-continuous-predictors" class="level3">
<h3 class="anchored" data-anchor-id="variable-interaction-between-continuous-predictors">Variable interaction between continuous predictors</h3>
<p>We can relax this assumption by considering another predictor, called an interaction term. Let us assume that the average increase in <code>price</code> associated with a one-unit increase in <code>engineSize</code> depends on the model <code>year</code> of the car. In other words, there is an interaction between <code>engineSize</code> and <code>year</code>. This interaction can be included as a predictor, which is the product of <code>engineSize</code> and <code>year</code>. <em>Note that there are several possible interactions that we can consider. Here the interaction between <code>engineSize</code> and <code>year</code> is just an example.</em></p>
<div class="cell" data-execution_count="4">
<div class="sourceCode cell-code" id="cb3"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="co">#Considering interaction between engineSize and year</span></span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>ols_object <span class="op">=</span> smf.ols(formula <span class="op">=</span> <span class="st">'price~year*engineSize+mileage+mpg'</span>, data <span class="op">=</span> train)</span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> ols_object.fit()</span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a>model.summary()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="4">
<table class="simpletable">
<caption>OLS Regression Results</caption>
<tbody><tr>
<th>Dep. Variable:</th> <td>price</td> <th> R-squared: </th> <td> 0.682</td>
</tr>
<tr>
<th>Model:</th> <td>OLS</td> <th> Adj. R-squared: </th> <td> 0.681</td>
</tr>
<tr>
<th>Method:</th> <td>Least Squares</td> <th> F-statistic: </th> <td> 2121.</td>
</tr>
<tr>
<th>Date:</th> <td>Tue, 17 Jan 2023</td> <th> Prob (F-statistic):</th> <td> 0.00</td>
</tr>
<tr>
<th>Time:</th> <td>02:19:05</td> <th> Log-Likelihood: </th> <td> -52338.</td>
</tr>
<tr>
<th>No. Observations:</th> <td> 4960</td> <th> AIC: </th> <td>1.047e+05</td>
</tr>
<tr>
<th>Df Residuals:</th> <td> 4954</td> <th> BIC: </th> <td>1.047e+05</td>
</tr>
<tr>
<th>Df Model:</th> <td> 5</td> <th> </th> <td> </td>
</tr>
<tr>
<th>Covariance Type:</th> <td>nonrobust</td> <th> </th> <td> </td>
</tr>
</tbody></table>
<table class="simpletable">
<tbody><tr>
<td></td> <th>coef</th> <th>std err</th> <th>t</th> <th>P>|t|</th> <th>[0.025</th> <th>0.975]</th>
</tr>
<tr>
<th>Intercept</th> <td> 5.606e+05</td> <td> 2.74e+05</td> <td> 2.048</td> <td> 0.041</td> <td> 2.4e+04</td> <td> 1.1e+06</td>
</tr>
<tr>
<th>year</th> <td> -275.3833</td> <td> 135.695</td> <td> -2.029</td> <td> 0.042</td> <td> -541.405</td> <td> -9.361</td>
</tr>
<tr>
<th>engineSize</th> <td>-1.796e+06</td> <td> 9.97e+04</td> <td> -18.019</td> <td> 0.000</td> <td>-1.99e+06</td> <td> -1.6e+06</td>
</tr>
<tr>
<th>year:engineSize</th> <td> 896.7687</td> <td> 49.431</td> <td> 18.142</td> <td> 0.000</td> <td> 799.861</td> <td> 993.676</td>
</tr>
<tr>
<th>mileage</th> <td> -0.1525</td> <td> 0.008</td> <td> -17.954</td> <td> 0.000</td> <td> -0.169</td> <td> -0.136</td>
</tr>
<tr>
<th>mpg</th> <td> -84.3417</td> <td> 9.048</td> <td> -9.322</td> <td> 0.000</td> <td> -102.079</td> <td> -66.604</td>
</tr>
</tbody></table>
<table class="simpletable">
<tbody><tr>
<th>Omnibus:</th> <td>2330.413</td> <th> Durbin-Watson: </th> <td> 0.524</td>
</tr>
<tr>
<th>Prob(Omnibus):</th> <td> 0.000</td> <th> Jarque-Bera (JB): </th> <td>29977.437</td>
</tr>
<tr>
<th>Skew:</th> <td> 1.908</td> <th> Prob(JB): </th> <td> 0.00</td>
</tr>
<tr>
<th>Kurtosis:</th> <td>14.423</td> <th> Cond. No. </th> <td>7.66e+07</td>
</tr>
</tbody></table><br><br>Notes:<br>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br>[2] The condition number is large, 7.66e+07. This might indicate that there are<br>strong multicollinearity or other numerical problems.
</div>
</div>
<p>Note that the R-squared has increased as compared to the model in Chapter <a href="https://nustat.github.io/STAT303-2-class-notes/Lec2_MultipleLinearRegression.html">2</a> since we added a predictor.</p>
<p>The model equation is:</p>
<p><span class="math display">\[\begin{equation}
price = \beta_0 + \beta_1*year + \beta_2*engineSize + \beta_3*(year * engineSize) + \beta4*mileage + \beta_5*mpg,
\end{equation}\]</span>or</p>
<p><span class="math display">\[\begin{equation}
price = \beta_0 + \beta_1*year + (\beta_2+\beta_3*year)*engineSize + \beta4*mileage + \beta_5*mpg,
\end{equation}\]</span>or</p>
<p><span class="math display">\[\begin{equation}
price = \beta_0 + \beta_1*year + \tilde \beta*engineSize + \beta4*mileage + \beta_5*mpg,
\end{equation}\]</span></p>
<p>Since <span class="math inline">\(\tilde \beta\)</span> is a function of <code>year</code>, the association between <code>engineSize</code> and <code>price</code> is no longer a constant. A change in the value of <code>year</code> will change the association between <code>price</code> and <code>engineSize</code>.</p>
<p>Substituting the values of the coefficients: <span class="math display">\[\begin{equation}
price = 5.606e5 - 275.3833*year + (-1.796e6+896.7687*year)*engineSize -0.1525*mileage -84.3417*mpg
\end{equation}\]</span></p>
<p>Thus, for cars launched in the year 2010, the average increase in price for one liter increase in engine size is -1.796e6 + 896.7687 * 2010 <span class="math inline">\(\approx\)</span> \$6,500, assuming all the other predictors are constant. However, for cars launched in the year 2020, the average increase in price for one liter increase in engine size is -1.796e6 + 896.7687*2020 <span class="math inline">\(\approx\)</span> \$15,500 , assuming all the other predictors are constant.</p>
<p>Similarly, the equation can be re-arranged as: <span class="math display">\[\begin{equation}
price = 5.606e5 +(-275.3833+896.7687*engineSize)*year -1.796e6*engineSize -0.1525*mileage -84.3417*mpg
\end{equation}\]</span></p>
<p>Thus, for cars with an engine size of 2 litres, the average increase in price for a one year newer model is -275.3833+896.7687 * 2 <span class="math inline">\(\approx\)</span> \$1500, assuming all the other predictors are constant. However, for cars with an engine size of 3 litres, the average increase in price for a one year newer model is -275.3833+896.7687 * 3 <span class="math inline">\(\approx\)</span> \$2400, assuming all the other predictors are constant.</p>
<div class="cell" data-execution_count="5">
<div class="sourceCode cell-code" id="cb4"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="co">#Computing the RMSE of the model with the interaction term</span></span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>pred_price <span class="op">=</span> model.predict(testf)</span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a>np.sqrt(((testp.price <span class="op">-</span> pred_price)<span class="op">**</span><span class="dv">2</span>).mean())</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="5">
<pre><code>9423.598872501092</code></pre>
</div>
</div>
<p>Note that the RMSE reduced as compared to that of the model in Chapter <a href="https://nustat.github.io/STAT303-2-class-notes/Lec2_MultipleLinearRegression.html">2</a>. This is because the interaction term between <code>engineSize</code> and <code>year</code> is significant and relaxes the assumption of constant association between price and engine size, and between price and year. This added flexibility makes the model better fit the data. Caution: Too much flexibility may lead to overfitting!</p>
<p>Note that interaction terms corresponding to other variable pairs, and higher order interaction terms (such as those containing 3 or 4 variables) may also be significant and improve the model fit & thereby the prediction accuracy of the model.</p>
</section>
<section id="including-qualitative-predictors-in-the-model" class="level3">
<h3 class="anchored" data-anchor-id="including-qualitative-predictors-in-the-model">Including qualitative predictors in the model</h3>
<p>Let us develop a model for predicting <code>price</code> based on <code>engineSize</code> and the qualitative predictor <code>transmission</code>.</p>
<div class="cell" data-execution_count="23">
<div class="sourceCode cell-code" id="cb6"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="co">#checking the distribution of values of transmission</span></span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a>train.transmission.value_counts()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="23">
<pre><code>Manual 1948
Automatic 1660
Semi-Auto 1351
Other 1
Name: transmission, dtype: int64</code></pre>
</div>
</div>
<p>Note that the <em>Other</em> category of the variable <em>transmission</em> contains only a single observation, which is likely to be insufficient to train the model. We’ll remove that observation from the training data. Another option may be to combine the observation in the <em>Other</em> category with the nearest category, and keep it in the data.</p>
<div class="cell" data-execution_count="24">
<div class="sourceCode cell-code" id="cb8"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>train_updated <span class="op">=</span> train[train.transmission<span class="op">!=</span><span class="st">'Other'</span>]</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div class="cell" data-execution_count="25">
<div class="sourceCode cell-code" id="cb9"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a>ols_object <span class="op">=</span> smf.ols(formula <span class="op">=</span> <span class="st">'price~engineSize+transmission'</span>, data <span class="op">=</span> train_updated)</span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> ols_object.fit()</span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a>model.summary()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="25">
<table class="simpletable">
<caption>OLS Regression Results</caption>
<tbody><tr>
<th>Dep. Variable:</th> <td>price</td> <th> R-squared: </th> <td> 0.459</td>
</tr>
<tr>
<th>Model:</th> <td>OLS</td> <th> Adj. R-squared: </th> <td> 0.458</td>
</tr>
<tr>
<th>Method:</th> <td>Least Squares</td> <th> F-statistic: </th> <td> 1400.</td>
</tr>
<tr>
<th>Date:</th> <td>Tue, 17 Jan 2023</td> <th> Prob (F-statistic):</th> <td> 0.00</td>
</tr>
<tr>
<th>Time:</th> <td>03:22:02</td> <th> Log-Likelihood: </th> <td> -53644.</td>
</tr>
<tr>
<th>No. Observations:</th> <td> 4959</td> <th> AIC: </th> <td>1.073e+05</td>
</tr>
<tr>
<th>Df Residuals:</th> <td> 4955</td> <th> BIC: </th> <td>1.073e+05</td>
</tr>
<tr>
<th>Df Model:</th> <td> 3</td> <th> </th> <td> </td>
</tr>
<tr>
<th>Covariance Type:</th> <td>nonrobust</td> <th> </th> <td> </td>
</tr>
</tbody></table>
<table class="simpletable">
<tbody><tr>
<td></td> <th>coef</th> <th>std err</th> <th>t</th> <th>P>|t|</th> <th>[0.025</th> <th>0.975]</th>
</tr>
<tr>
<th>Intercept</th> <td> 3042.6765</td> <td> 661.190</td> <td> 4.602</td> <td> 0.000</td> <td> 1746.451</td> <td> 4338.902</td>
</tr>
<tr>
<th>transmission[T.Manual]</th> <td>-6770.6165</td> <td> 442.116</td> <td> -15.314</td> <td> 0.000</td> <td>-7637.360</td> <td>-5903.873</td>
</tr>
<tr>
<th>transmission[T.Semi-Auto]</th> <td> 4994.3112</td> <td> 442.989</td> <td> 11.274</td> <td> 0.000</td> <td> 4125.857</td> <td> 5862.765</td>
</tr>
<tr>
<th>engineSize</th> <td> 1.023e+04</td> <td> 247.485</td> <td> 41.323</td> <td> 0.000</td> <td> 9741.581</td> <td> 1.07e+04</td>
</tr>
</tbody></table>
<table class="simpletable">
<tbody><tr>
<th>Omnibus:</th> <td>1575.518</td> <th> Durbin-Watson: </th> <td> 0.579</td>
</tr>
<tr>
<th>Prob(Omnibus):</th> <td> 0.000</td> <th> Jarque-Bera (JB): </th> <td>11006.609</td>
</tr>
<tr>
<th>Skew:</th> <td> 1.334</td> <th> Prob(JB): </th> <td> 0.00</td>
</tr>
<tr>
<th>Kurtosis:</th> <td> 9.793</td> <th> Cond. No. </th> <td> 11.4</td>
</tr>
</tbody></table><br><br>Notes:<br>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
</div>
</div>
<p>The model equation is:</p>
<p>Automatic transmission: <code>price</code> = 3042.6765 + 1.023e4<code>engineSize</code>,</p>
<p>Semi-Automatic transmission: <code>price</code> = 3042.6765 + 1.023e4<code>engineSize</code> + 4994.3112,</p>
<p>Manual transmission: <code>price</code> = 3042.6765 + 1.023e4<code>engineSize</code> -6770.6165</p>
<div class="cell" data-execution_count="49">
<div class="sourceCode cell-code" id="cb10"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="co">#Visualizing the developed model with interaction terms</span></span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a><span class="co">#sns.lineplot(x = x, y = model.params['engineSize']*x+model.params['Intercept'], color = 'red')</span></span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a><span class="co">#sns.lineplot(x = x, y = model.params['engineSize']*x+model.params['Intercept']+model.params['transmission[T.Semi-Auto]'], color = 'blue')</span></span>
<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a><span class="co">#sns.lineplot(x = x, y = model.params['engineSize']*x+model.params['Intercept']+model.params['transmission[T.Manual]'], color = 'green')</span></span>
<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a><span class="co">#plt.legend(labels=["Automatic","Semi-Automatic", "Manual"])</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="including-qualitative-predictors-and-its-interaction-with-continuous-predictor-in-the-model" class="level3">
<h3 class="anchored" data-anchor-id="including-qualitative-predictors-and-its-interaction-with-continuous-predictor-in-the-model">Including qualitative predictors and its interaction with continuous predictor in the model</h3>
<p>Note that the qualitative predictor leads to fitting 3 parallel lines to the data, as there are 3 categories.</p>
<p>However, note that we have made the constant association assumption. The fact that the lines are parallel means that the average increase in car price for one litre increase in engine size does not depend on the type of transmission. This represents a potentially serious limitation of the model, since in fact a change in engine size may have a very different association on the price of an automatic car versus a semi-automatic or manual car.</p>
<p>This limitation can be addressed by adding an interaction variable by multiplying <code>engineSize</code> with the dummy variables for semi-automatic and manual transmissions.</p>
<div class="cell" data-execution_count="11">
<div class="sourceCode cell-code" id="cb11"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="co">#Using the ols function to create an ols object. 'ols' stands for 'Ordinary least squares'</span></span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a>ols_object <span class="op">=</span> smf.ols(formula <span class="op">=</span> <span class="st">'price~engineSize*transmission'</span>, data <span class="op">=</span> train2)</span>
<span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> ols_object.fit()</span>
<span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a>model.summary()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="11">
<table class="simpletable">
<caption>OLS Regression Results</caption>
<tbody><tr>
<th>Dep. Variable:</th> <td>price</td> <th> R-squared: </th> <td> 0.479</td>
</tr>
<tr>
<th>Model:</th> <td>OLS</td> <th> Adj. R-squared: </th> <td> 0.478</td>
</tr>
<tr>
<th>Method:</th> <td>Least Squares</td> <th> F-statistic: </th> <td> 909.9</td>
</tr>
<tr>
<th>Date:</th> <td>Tue, 17 Jan 2023</td> <th> Prob (F-statistic):</th> <td> 0.00</td>
</tr>
<tr>
<th>Time:</th> <td>01:32:37</td> <th> Log-Likelihood: </th> <td> -53550.</td>
</tr>
<tr>
<th>No. Observations:</th> <td> 4959</td> <th> AIC: </th> <td>1.071e+05</td>
</tr>
<tr>
<th>Df Residuals:</th> <td> 4953</td> <th> BIC: </th> <td>1.072e+05</td>
</tr>
<tr>
<th>Df Model:</th> <td> 5</td> <th> </th> <td> </td>
</tr>
<tr>
<th>Covariance Type:</th> <td>nonrobust</td> <th> </th> <td> </td>
</tr>
</tbody></table>
<table class="simpletable">
<tbody><tr>
<td></td> <th>coef</th> <th>std err</th> <th>t</th> <th>P>|t|</th> <th>[0.025</th> <th>0.975]</th>
</tr>
<tr>
<th>Intercept</th> <td> 3754.7238</td> <td> 895.221</td> <td> 4.194</td> <td> 0.000</td> <td> 1999.695</td> <td> 5509.753</td>
</tr>
<tr>
<th>transmission[T.Manual]</th> <td> 1768.5856</td> <td> 1294.071</td> <td> 1.367</td> <td> 0.172</td> <td> -768.366</td> <td> 4305.538</td>
</tr>
<tr>
<th>transmission[T.Semi-Auto]</th> <td>-5282.7164</td> <td> 1416.472</td> <td> -3.729</td> <td> 0.000</td> <td>-8059.628</td> <td>-2505.805</td>
</tr>
<tr>
<th>engineSize</th> <td> 9928.6082</td> <td> 354.511</td> <td> 28.006</td> <td> 0.000</td> <td> 9233.610</td> <td> 1.06e+04</td>
</tr>
<tr>
<th>engineSize:transmission[T.Manual]</th> <td>-5285.9059</td> <td> 646.175</td> <td> -8.180</td> <td> 0.000</td> <td>-6552.695</td> <td>-4019.117</td>
</tr>
<tr>
<th>engineSize:transmission[T.Semi-Auto]</th> <td> 4162.2428</td> <td> 552.597</td> <td> 7.532</td> <td> 0.000</td> <td> 3078.908</td> <td> 5245.578</td>
</tr>
</tbody></table>
<table class="simpletable">
<tbody><tr>
<th>Omnibus:</th> <td>1379.846</td> <th> Durbin-Watson: </th> <td> 0.622</td>
</tr>
<tr>
<th>Prob(Omnibus):</th> <td> 0.000</td> <th> Jarque-Bera (JB): </th> <td>9799.471</td>
</tr>
<tr>
<th>Skew:</th> <td> 1.139</td> <th> Prob(JB): </th> <td> 0.00</td>
</tr>
<tr>
<th>Kurtosis:</th> <td> 9.499</td> <th> Cond. No. </th> <td> 30.8</td>
</tr>
</tbody></table><br><br>Notes:<br>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
</div>
</div>
<p>The model equation for the model with interactions is:</p>
<p>Automatic transmission: <span class="math inline">\(price = 3754.7238 + 9928.6082 * engineSize\)</span>,<br>
Semi-Automatic transmission: <span class="math inline">\(price = 3754.7238 + 9928.6082 * engineSize + (-5282.7164+4162.2428*engineSize)\)</span>,<br>
Manual transmission: <span class="math inline">\(price = 3754.7238 + 9928.6082 * engineSize +(1768.5856-5285.9059*engineSize)\)</span>, or</p>
<p>Automatic transmission: <span class="math inline">\(price = 3754.7238 + 9928.6082 * engineSize\)</span>,<br>
Semi-Automatic transmission: <span class="math inline">\(price = -1527 + 7046 * engineSize\)</span>,<br>
Manual transmission: <span class="math inline">\(price = 5523 + 4642 * engineSize\)</span>,</p>
<div class="cell" data-execution_count="12">
<div class="sourceCode cell-code" id="cb12"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="co">#Visualizing the developed model with interaction terms</span></span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a>x <span class="op">=</span> np.linspace(<span class="op">-</span>train.engineSize.<span class="bu">min</span>(),train.engineSize.<span class="bu">max</span>(),<span class="dv">100</span>)</span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a>plt.plot(x, model.params[<span class="st">'engineSize'</span>]<span class="op">*</span>x<span class="op">+</span>model.params[<span class="st">'Intercept'</span>], <span class="st">'-r'</span>, label<span class="op">=</span><span class="st">'Automatic'</span>)</span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a>plt.plot(x, (model.params[<span class="st">'engineSize'</span>]<span class="op">+</span>model.params[<span class="st">'engineSize:transmission[T.Semi-Auto]'</span>])<span class="op">*</span>x<span class="op">+</span>model.params[<span class="st">'Intercept'</span>]<span class="op">+</span>model.params[<span class="st">'transmission[T.Semi-Auto]'</span>], <span class="st">'-b'</span>, label<span class="op">=</span><span class="st">'Semi-Automatic'</span>)</span>
<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a>plt.plot(x, (model.params[<span class="st">'engineSize'</span>]<span class="op">+</span>model.params[<span class="st">'engineSize:transmission[T.Manual]'</span>])<span class="op">*</span>x<span class="op">+</span>model.params[<span class="st">'Intercept'</span>]<span class="op">+</span>model.params[<span class="st">'transmission[T.Manual]'</span>], <span class="st">'-g'</span>, label<span class="op">=</span><span class="st">'Manual'</span>)</span>
<span id="cb12-6"><a href="#cb12-6" aria-hidden="true" tabindex="-1"></a>plt.legend(loc<span class="op">=</span><span class="st">'upper left'</span>)</span>
<span id="cb12-7"><a href="#cb12-7" aria-hidden="true" tabindex="-1"></a>plt.xlabel(<span class="st">'engine size'</span>)</span>
<span id="cb12-8"><a href="#cb12-8" aria-hidden="true" tabindex="-1"></a>plt.ylabel(<span class="st">'price'</span>)</span>
<span id="cb12-9"><a href="#cb12-9" aria-hidden="true" tabindex="-1"></a>plt.show()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display">
<p><img src="Section_3312_Variable_Interactions_&_Transformations-Copy1_files/figure-html/cell-11-output-1.png" class="img-fluid"></p>
</div>
</div>
<p>Note the interaction term adds flexibility to the model.</p>
<p>The slope of the regression line for semi-automatic cars is the largest. This suggests that increase in engine size is associated with a higher increase in car price for semi-automatic cars, as compared to other cars.</p>
</section>
</section>
<section id="variable-transformations" class="level2">
<h2 class="anchored" data-anchor-id="variable-transformations">Variable transformations</h2>
<p>So far we have considered only a linear relationship between the predictors and the response. However, the relationship may be non-linear.</p>
<p>Consider the regression plot of <em>price</em> on <em>mileage</em></p>
<div class="cell" data-execution_count="13">
<div class="sourceCode cell-code" id="cb13"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a>sns.regplot(x <span class="op">=</span> train2.mileage, y <span class="op">=</span>train2.price,color <span class="op">=</span> <span class="st">'orange'</span>, line_kws <span class="op">=</span> {<span class="st">'color'</span>:<span class="st">'blue'</span>})</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="13">
<pre><code><AxesSubplot:xlabel='mileage', ylabel='price'></code></pre>
</div>
<div class="cell-output cell-output-display">
<p><img src="Section_3312_Variable_Interactions_&_Transformations-Copy1_files/figure-html/cell-12-output-2.png" class="img-fluid"></p>
</div>
</div>
<p>It seems like a quadratic curve may better fit the points.</p>
<div class="cell" data-execution_count="14">
<div class="sourceCode cell-code" id="cb15"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="co">#Including mileage squared as a predictor and developing the model</span></span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a>ols_object <span class="op">=</span> smf.ols(formula <span class="op">=</span> <span class="st">'price~mileage+I(mileage**2)'</span>, data <span class="op">=</span> train2)</span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> ols_object.fit()</span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a>model.summary()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="14">
<table class="simpletable">
<caption>OLS Regression Results</caption>
<tbody><tr>
<th>Dep. Variable:</th> <td>price</td> <th> R-squared: </th> <td> 0.271</td>
</tr>
<tr>
<th>Model:</th> <td>OLS</td> <th> Adj. R-squared: </th> <td> 0.271</td>
</tr>
<tr>
<th>Method:</th> <td>Least Squares</td> <th> F-statistic: </th> <td> 920.6</td>
</tr>
<tr>
<th>Date:</th> <td>Tue, 17 Jan 2023</td> <th> Prob (F-statistic):</th> <td> 0.00</td>
</tr>
<tr>
<th>Time:</th> <td>01:32:40</td> <th> Log-Likelihood: </th> <td> -54382.</td>
</tr>
<tr>
<th>No. Observations:</th> <td> 4959</td> <th> AIC: </th> <td>1.088e+05</td>
</tr>
<tr>
<th>Df Residuals:</th> <td> 4956</td> <th> BIC: </th> <td>1.088e+05</td>
</tr>
<tr>
<th>Df Model:</th> <td> 2</td> <th> </th> <td> </td>
</tr>
<tr>
<th>Covariance Type:</th> <td>nonrobust</td> <th> </th> <td> </td>
</tr>
</tbody></table>
<table class="simpletable">
<tbody><tr>
<td></td> <th>coef</th> <th>std err</th> <th>t</th> <th>P>|t|</th> <th>[0.025</th> <th>0.975]</th>
</tr>
<tr>
<th>Intercept</th> <td> 3.44e+04</td> <td> 332.710</td> <td> 103.382</td> <td> 0.000</td> <td> 3.37e+04</td> <td> 3.5e+04</td>
</tr>
<tr>
<th>mileage</th> <td> -0.5662</td> <td> 0.017</td> <td> -33.940</td> <td> 0.000</td> <td> -0.599</td> <td> -0.534</td>
</tr>
<tr>
<th>I(mileage ** 2)</th> <td> 2.629e-06</td> <td> 1.56e-07</td> <td> 16.813</td> <td> 0.000</td> <td> 2.32e-06</td> <td> 2.94e-06</td>
</tr>
</tbody></table>
<table class="simpletable">
<tbody><tr>
<th>Omnibus:</th> <td>2362.973</td> <th> Durbin-Watson: </th> <td> 0.325</td>
</tr>
<tr>
<th>Prob(Omnibus):</th> <td> 0.000</td> <th> Jarque-Bera (JB): </th> <td>22427.952</td>
</tr>
<tr>
<th>Skew:</th> <td> 2.052</td> <th> Prob(JB): </th> <td> 0.00</td>
</tr>
<tr>
<th>Kurtosis:</th> <td>12.576</td> <th> Cond. No. </th> <td>4.81e+09</td>
</tr>
</tbody></table><br><br>Notes:<br>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br>[2] The condition number is large, 4.81e+09. This might indicate that there are<br>strong multicollinearity or other numerical problems.
</div>
</div>
<div class="cell" data-execution_count="15">
<div class="sourceCode cell-code" id="cb16"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a><span class="co">#Visualizing the regression line</span></span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a>pred_price <span class="op">=</span> model.predict(train2)</span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a>sns.scatterplot(x <span class="op">=</span> <span class="st">'mileage'</span>, y <span class="op">=</span> <span class="st">'price'</span>, data <span class="op">=</span> train2, color <span class="op">=</span> <span class="st">'orange'</span>)</span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a>sns.lineplot(x <span class="op">=</span> train2.mileage, y <span class="op">=</span> pred_price, color <span class="op">=</span> <span class="st">'blue'</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="15">
<pre><code><AxesSubplot:xlabel='mileage', ylabel='price'></code></pre>
</div>
<div class="cell-output cell-output-display">
<p><img src="Section_3312_Variable_Interactions_&_Transformations-Copy1_files/figure-html/cell-14-output-2.png" class="img-fluid"></p>
</div>
</div>
<div class="cell" data-execution_count="16">
<div class="sourceCode cell-code" id="cb18"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="co">#Including mileage squared as a predictor and developing the model</span></span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a>ols_object <span class="op">=</span> smf.ols(formula <span class="op">=</span> <span class="st">'price~mileage+I(mileage**2)+I(mileage**3)'</span>, data <span class="op">=</span> train2)</span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> ols_object.fit()</span>
<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a>model.summary()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="16">
<table class="simpletable">
<caption>OLS Regression Results</caption>
<tbody><tr>
<th>Dep. Variable:</th> <td>price</td> <th> R-squared: </th> <td> 0.283</td>
</tr>
<tr>
<th>Model:</th> <td>OLS</td> <th> Adj. R-squared: </th> <td> 0.283</td>
</tr>
<tr>
<th>Method:</th> <td>Least Squares</td> <th> F-statistic: </th> <td> 652.3</td>
</tr>
<tr>
<th>Date:</th> <td>Tue, 17 Jan 2023</td> <th> Prob (F-statistic):</th> <td> 0.00</td>
</tr>
<tr>
<th>Time:</th> <td>01:32:50</td> <th> Log-Likelihood: </th> <td> -54340.</td>
</tr>
<tr>
<th>No. Observations:</th> <td> 4959</td> <th> AIC: </th> <td>1.087e+05</td>
</tr>
<tr>
<th>Df Residuals:</th> <td> 4955</td> <th> BIC: </th> <td>1.087e+05</td>
</tr>
<tr>
<th>Df Model:</th> <td> 3</td> <th> </th> <td> </td>
</tr>
<tr>
<th>Covariance Type:</th> <td>nonrobust</td> <th> </th> <td> </td>
</tr>
</tbody></table>
<table class="simpletable">
<tbody><tr>
<td></td> <th>coef</th> <th>std err</th> <th>t</th> <th>P>|t|</th> <th>[0.025</th> <th>0.975]</th>
</tr>
<tr>
<th>Intercept</th> <td> 3.598e+04</td> <td> 371.926</td> <td> 96.727</td> <td> 0.000</td> <td> 3.52e+04</td> <td> 3.67e+04</td>
</tr>
<tr>
<th>mileage</th> <td> -0.7742</td> <td> 0.028</td> <td> -27.634</td> <td> 0.000</td> <td> -0.829</td> <td> -0.719</td>
</tr>
<tr>
<th>I(mileage ** 2)</th> <td> 6.875e-06</td> <td> 4.87e-07</td> <td> 14.119</td> <td> 0.000</td> <td> 5.92e-06</td> <td> 7.83e-06</td>
</tr>
<tr>
<th>I(mileage ** 3)</th> <td>-1.823e-11</td> <td> 1.98e-12</td> <td> -9.199</td> <td> 0.000</td> <td>-2.21e-11</td> <td>-1.43e-11</td>
</tr>
</tbody></table>
<table class="simpletable">
<tbody><tr>
<th>Omnibus:</th> <td>2380.788</td> <th> Durbin-Watson: </th> <td> 0.321</td>
</tr>
<tr>
<th>Prob(Omnibus):</th> <td> 0.000</td> <th> Jarque-Bera (JB): </th> <td>23039.307</td>
</tr>
<tr>
<th>Skew:</th> <td> 2.065</td> <th> Prob(JB): </th> <td> 0.00</td>
</tr>
<tr>
<th>Kurtosis:</th> <td>12.719</td> <th> Cond. No. </th> <td>7.73e+14</td>
</tr>
</tbody></table><br><br>Notes:<br>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br>[2] The condition number is large, 7.73e+14. This might indicate that there are<br>strong multicollinearity or other numerical problems.
</div>
</div>
<p>Note that the fit seems slighty better for mileage less than 150k. The model should not be used to predict car prices of cars with a mileage higher than 150k.</p>
<p>Let’s update the model created earlier (in the beginning of this chapter) to include the transformed predictor.</p>
<div class="cell" data-execution_count="17">
<div class="sourceCode cell-code" id="cb19"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="co">#Model with an interaction term and a variable transformation term</span></span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a>ols_object <span class="op">=</span> smf.ols(formula <span class="op">=</span> <span class="st">'price~year*engineSize+mileage+mpg+I(mileage**2)'</span>, data <span class="op">=</span> train)</span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> ols_object.fit()</span>
<span id="cb19-4"><a href="#cb19-4" aria-hidden="true" tabindex="-1"></a>model.summary()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="17">
<table class="simpletable">
<caption>OLS Regression Results</caption>
<tbody><tr>
<th>Dep. Variable:</th> <td>price</td> <th> R-squared: </th> <td> 0.702</td>
</tr>
<tr>
<th>Model:</th> <td>OLS</td> <th> Adj. R-squared: </th> <td> 0.702</td>
</tr>
<tr>
<th>Method:</th> <td>Least Squares</td> <th> F-statistic: </th> <td> 1947.</td>
</tr>
<tr>
<th>Date:</th> <td>Tue, 17 Jan 2023</td> <th> Prob (F-statistic):</th> <td> 0.00</td>
</tr>
<tr>
<th>Time:</th> <td>01:32:51</td> <th> Log-Likelihood: </th> <td> -52172.</td>
</tr>
<tr>
<th>No. Observations:</th> <td> 4960</td> <th> AIC: </th> <td>1.044e+05</td>
</tr>
<tr>
<th>Df Residuals:</th> <td> 4953</td> <th> BIC: </th> <td>1.044e+05</td>
</tr>
<tr>
<th>Df Model:</th> <td> 6</td> <th> </th> <td> </td>
</tr>
<tr>
<th>Covariance Type:</th> <td>nonrobust</td> <th> </th> <td> </td>
</tr>
</tbody></table>
<table class="simpletable">
<tbody><tr>
<td></td> <th>coef</th> <th>std err</th> <th>t</th> <th>P>|t|</th> <th>[0.025</th> <th>0.975]</th>
</tr>
<tr>
<th>Intercept</th> <td> 1.53e+06</td> <td> 2.7e+05</td> <td> 5.671</td> <td> 0.000</td> <td> 1e+06</td> <td> 2.06e+06</td>
</tr>
<tr>
<th>year</th> <td> -755.6269</td> <td> 133.764</td> <td> -5.649</td> <td> 0.000</td> <td>-1017.864</td> <td> -493.390</td>
</tr>
<tr>
<th>engineSize</th> <td>-2.022e+06</td> <td> 9.72e+04</td> <td> -20.807</td> <td> 0.000</td> <td>-2.21e+06</td> <td>-1.83e+06</td>
</tr>
<tr>
<th>year:engineSize</th> <td> 1008.6542</td> <td> 48.185</td> <td> 20.933</td> <td> 0.000</td> <td> 914.190</td> <td> 1103.118</td>
</tr>
<tr>
<th>mileage</th> <td> -0.3548</td> <td> 0.014</td> <td> -25.977</td> <td> 0.000</td> <td> -0.382</td> <td> -0.328</td>
</tr>
<tr>
<th>mpg</th> <td> -54.7489</td> <td> 8.895</td> <td> -6.155</td> <td> 0.000</td> <td> -72.186</td> <td> -37.311</td>
</tr>
<tr>
<th>I(mileage ** 2)</th> <td> 1.926e-06</td> <td> 1.04e-07</td> <td> 18.539</td> <td> 0.000</td> <td> 1.72e-06</td> <td> 2.13e-06</td>
</tr>
</tbody></table>
<table class="simpletable">
<tbody><tr>
<th>Omnibus:</th> <td>2356.205</td> <th> Durbin-Watson: </th> <td> 0.562</td>
</tr>
<tr>
<th>Prob(Omnibus):</th> <td> 0.000</td> <th> Jarque-Bera (JB): </th> <td>38343.274</td>
</tr>
<tr>
<th>Skew:</th> <td> 1.858</td> <th> Prob(JB): </th> <td> 0.00</td>
</tr>
<tr>
<th>Kurtosis:</th> <td>16.105</td> <th> Cond. No. </th> <td>6.40e+12</td>
</tr>
</tbody></table><br><br>Notes:<br>[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.<br>[2] The condition number is large, 6.4e+12. This might indicate that there are<br>strong multicollinearity or other numerical problems.
</div>
</div>
<p>Note that the R-squared has increased as compared to the model with just the interaction term.</p>
<div class="cell" data-execution_count="18">
<div class="sourceCode cell-code" id="cb20"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="co">#Computing RMSE on test data</span></span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a>pred_price <span class="op">=</span> model.predict(testf)</span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a>np.sqrt(((testp.price <span class="op">-</span> pred_price)<span class="op">**</span><span class="dv">2</span>).mean())</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-display" data-execution_count="18">
<pre><code>9074.485626191494</code></pre>
</div>
</div>
<p>Note that the prediction accuracy of the model has further increased, as the RMSE has reduced. The transformed predictor is statisically significant and provides additional flexibility to better capture the trend in the data, leading to an increase in prediction accuracy.</p>
</section>
</main>
<!-- /main column -->
<script id="quarto-html-after-body" type="application/javascript">
window.document.addEventListener("DOMContentLoaded", function (event) {
const toggleBodyColorMode = (bsSheetEl) => {
const mode = bsSheetEl.getAttribute("data-mode");
const bodyEl = window.document.querySelector("body");
if (mode === "dark") {
bodyEl.classList.add("quarto-dark");
bodyEl.classList.remove("quarto-light");
} else {
bodyEl.classList.add("quarto-light");
bodyEl.classList.remove("quarto-dark");
}
}
const toggleBodyColorPrimary = () => {
const bsSheetEl = window.document.querySelector("link#quarto-bootstrap");
if (bsSheetEl) {
toggleBodyColorMode(bsSheetEl);
}
}
toggleBodyColorPrimary();
const icon = "";
const anchorJS = new window.AnchorJS();
anchorJS.options = {
placement: 'right',
icon: icon
};
anchorJS.add('.anchored');
const clipboard = new window.ClipboardJS('.code-copy-button', {
target: function(trigger) {
return trigger.previousElementSibling;
}
});
clipboard.on('success', function(e) {
// button target
const button = e.trigger;
// don't keep focus
button.blur();
// flash "checked"
button.classList.add('code-copy-button-checked');
var currentTitle = button.getAttribute("title");
button.setAttribute("title", "Copied!");
setTimeout(function() {
button.setAttribute("title", currentTitle);
button.classList.remove('code-copy-button-checked');
}, 1000);
// clear code selection
e.clearSelection();
});
function tippyHover(el, contentFn) {
const config = {
allowHTML: true,
content: contentFn,
maxWidth: 500,
delay: 100,
arrow: false,
appendTo: function(el) {
return el.parentElement;
},
interactive: true,
interactiveBorder: 10,
theme: 'quarto',
placement: 'bottom-start'
};
window.tippy(el, config);
}
const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]');
for (var i=0; i<noterefs.length; i++) {
const ref = noterefs[i];
tippyHover(ref, function() {
let href = ref.getAttribute('href');
try { href = new URL(href).hash; } catch {}
const id = href.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
return note.innerHTML;
});
}
var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]');
for (var i=0; i<bibliorefs.length; i++) {
const ref = bibliorefs[i];
const cites = ref.parentNode.getAttribute('data-cites').split(' ');
tippyHover(ref, function() {
var popup = window.document.createElement('div');
cites.forEach(function(cite) {
var citeDiv = window.document.createElement('div');
citeDiv.classList.add('hanging-indent');
citeDiv.classList.add('csl-entry');
var biblioDiv = window.document.getElementById('ref-' + cite);
if (biblioDiv) {
citeDiv.innerHTML = biblioDiv.innerHTML;
}
popup.appendChild(citeDiv);
});
return popup.innerHTML;
});
}
});
</script>
</div> <!-- /content -->
</body></html>