-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path12_Regresion.html
More file actions
1150 lines (1095 loc) · 98.2 KB
/
12_Regresion.html
File metadata and controls
1150 lines (1095 loc) · 98.2 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
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
<!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.3.450">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<meta name="author" content="Andrés Quintero-Zea">
<meta name="dcterms.date" content="2024-09-09">
<title>Modelos de regresión</title>
<style>
code {
white-space: pre-wrap;
}
span.smallcaps {
font-variant: small-caps;
}
div.columns {
display: flex;
gap: min(4vw, 1.5em);
}
div.column {
flex: auto;
overflow-x: auto;
}
div.hanging-indent {
margin-left: 1.5em;
text-indent: -1.5em;
}
ul.task-list {
list-style: none;
}
ul.task-list li input[type="checkbox"] {
width: 0.8em;
margin: 0 0.8em 0.2em -1em;
/* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */
vertical-align: middle;
}
/* CSS for syntax highlighting */
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;
}
pre.numberSource {
margin-left: 3em;
padding-left: 4px;
}
@media screen {
pre>code.sourceCode>span>a:first-child::before {
text-decoration: underline;
}
}
</style>
<script src="assets/quarto-nav/quarto-nav.js"></script>
<script src="assets/quarto-nav/headroom.min.js"></script>
<script src="assets/clipboard/clipboard.min.js"></script>
<script src="assets/quarto-search/autocomplete.umd.js"></script>
<script src="assets/quarto-search/fuse.min.js"></script>
<script src="assets/quarto-search/quarto-search.js"></script>
<meta name="quarto:offset" content="./">
<link href="./08_Matplotlib.html" rel="next">
<link href="./10_Intro_DS.html" rel="prev">
<script src="assets/quarto-html/quarto.js"></script>
<script src="assets/quarto-html/popper.min.js"></script>
<script src="assets/quarto-html/tippy.umd.min.js"></script>
<script src="assets/quarto-html/anchor.min.js"></script>
<link href="assets/quarto-html/tippy.css" rel="stylesheet">
<link href="assets/quarto-html/quarto-syntax-highlighting.css" rel="stylesheet"
id="quarto-text-highlighting-styles">
<script src="assets/bootstrap/bootstrap.min.js"></script>
<link href="assets/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="assets/bootstrap/bootstrap.min.css" rel="stylesheet" id="quarto-bootstrap" data-mode="light">
<script id="quarto-search-options" type="application/json">{
"location": "sidebar",
"copy-button": false,
"collapse-after": 3,
"panel-placement": "start",
"type": "textbox",
"limit": 20,
"language": {
"search-no-results-text": "No results",
"search-matching-documents-text": "matching documents",
"search-copy-link-title": "Copy link to search",
"search-hide-matches-text": "Hide additional matches",
"search-more-match-text": "more match in this document",
"search-more-matches-text": "more matches in this document",
"search-clear-button-title": "Clear",
"search-detached-cancel-button-title": "Cancel",
"search-submit-button-title": "Submit",
"search-label": "Search"
}
}</script>
<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://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=default'></script>
</head>
<body class="nav-sidebar floating">
<!-- content -->
<div id="quarto-content" class="quarto-container page-columns page-rows-contents page-layout-article">
<!-- sidebar -->
<nav id="quarto-sidebar" class="sidebar collapse collapse-horizontal sidebar-navigation floating overflow-auto">
<div class="pt-lg-2 mt-2 text-left sidebar-header sidebar-header-stacked">
<img src="./LogoNuevo.png" alt="" class="sidebar-logo py-0 d-lg-inline d-none">
<div class="sidebar-title mb-0 py-0">
<a href="./index.html">Programación PRE2013A45</a>
</div>
</div>
<div class="sidebar-menu-container">
<ul class="list-unstyled mt-1">
<li class="sidebar-item sidebar-item-section">
<div class="sidebar-item-container">
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse"
data-bs-target="#quarto-sidebar-section-1" aria-expanded="true">
<span class="menu-text">Python</span></a>
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse"
data-bs-target="#quarto-sidebar-section-1" aria-expanded="true"
aria-label="Toggle section">
<i class="bi bi-chevron-right ms-2"></i>
</a>
</div>
<ul id="quarto-sidebar-section-1" class="collapse list-unstyled sidebar-section depth1 show">
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./01_Intro_Python.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">1</span> <span
class="chapter-title">Introducción a Python</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./02_Estructuras_control.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">2</span> <span
class="chapter-title">Estructuras de control</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./03_Funciones.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">3</span> <span
class="chapter-title">Funciones</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./04_Estructura_datos.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">4</span> <span
class="chapter-title">Estructuras de datos avanzadas</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./05_Archivos_excepciones.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">5</span> <span
class="chapter-title">Manejo de archivos y excepciones</span></span></a>
</div>
</li>
</ul>
</li>
<li class="sidebar-item sidebar-item-section">
<div class="sidebar-item-container">
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse"
data-bs-target="#quarto-sidebar-section-2" aria-expanded="true">
<span class="menu-text">Análisis de Datos</span></a>
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse"
data-bs-target="#quarto-sidebar-section-2" aria-expanded="true"
aria-label="Toggle section">
<i class="bi bi-chevron-right ms-2"></i>
</a>
</div>
<ul id="quarto-sidebar-section-2" class="collapse list-unstyled sidebar-section depth1 show">
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./06_Numpy.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">6</span> <span
class="chapter-title">Introducción a Numpy</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./07_Pandas.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">7</span> <span
class="chapter-title">Manipulación de datos con Pandas</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./08_Matplotlib.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">8</span> <span
class="chapter-title">Visualización de datos con
Matplotlib y Seaborn</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./09_EDA.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">9</span> <span
class="chapter-title">Análisis exploratorio de datos</span></span></a>
</div>
</li>
</ul>
</li>
<li class="sidebar-item sidebar-item-section">
<div class="sidebar-item-container">
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse"
data-bs-target="#quarto-sidebar-section-3" aria-expanded="true">
<span class="menu-text">Ciencia de Datos</span></a>
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse"
data-bs-target="#quarto-sidebar-section-3" aria-expanded="true"
aria-label="Toggle section">
<i class="bi bi-chevron-right ms-2"></i>
</a>
</div>
<ul id="quarto-sidebar-section-3" class="collapse list-unstyled sidebar-section depth1 show">
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./10_Intro_DS.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">10</span> <span
class="chapter-title">Introducción a la ciencia de
datos</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./11_Clasificacion.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">11</span> <span
class="chapter-title">Modelos de clasificación</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./12_Regresion.html" class="sidebar-item-text sidebar-link active">
<span class="menu-text"><span class="chapter-number">12</span> <span
class="chapter-title">Modelos de regresión</span></span></a>
</div>
</li>
</ul>
</li>
</ul>
</div>
</nav>
<div id="quarto-sidebar-glass" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar,#quarto-sidebar-glass">
</div>
<!-- margin-sidebar -->
<div id="quarto-margin-sidebar" class="sidebar margin-sidebar">
<nav id="TOC" role="doc-toc" class="toc-active">
<h2 id="toc-title">Tabla de contenidos</h2>
<ul>
<li><a href="#objetivo" id="toc-objetivo" class="nav-link active"
data-scroll-target="#objetivo">Objetivo</a></li>
<li><a href="#consejos-generales-sobre-matplotlib" id="toc-consejos-generales-sobre-matplotlib" class="nav-link"
data-scroll-target="#consejos-generales-sobre-matplotlib"><span class="header-section-number"> 8.1 </span> Consejos generales sobre Matplotlib </a></li>
<li><a href="#dos-interfaces-por-el-precio-de-una" id="toc-dos-interfaces-por-el-precio-de-una" class="nav-link"
data-scroll-target="#dos-interfaces-por-el-precio-de-una"><span class="header-section-number"> 8.2 </span> Dos interfaces por el precio de una </a>
</li>
<li><a href="#gráficos-de-líneas-simples" id="toc-gráficos-de-líneas-simples" class="nav-link"
data-scroll-target="#gráficos-de-líneas-simples"><span class="header-section-number"> 8.3 </span> Gráficos de líneas simples </a>
</li>
<li><a href="#diagramas-de-dispersión-simples" id="toc-diagramas-de-dispersión-simples" class="nav-link"
data-scroll-target="#diagramas-de-dispersión-simples"><span class="header-section-number"> 8.4 </span> Diagramas de dispersión simples </a>
</li>
<li><a href="#visualizando-errores" id="toc-visualizando-errores" class="nav-link"
data-scroll-target="#visualizando-errores"><span class="header-section-number"> 8.5 </span> Visualizando errores</a>
</li>
<li><a href="#gráficas-de-densidad-y-contorno" id="toc-gráficas-de-densidad-y-contorno" class="nav-link"
data-scroll-target="#gráficas-de-densidad-y-contorno"><span class="header-section-number"> 8.6 </span> Gráficas de densidad y contorno </a>
</li>
<li><a href="#histogramas-binnings-y-densidad" id="toc-histogramas-binnings-y-densidad" class="nav-link"
data-scroll-target="#histogramas-binnings-y-densidad"><span class="header-section-number"> 8.7 </span> Histogramas, binnings y densidad </a>
</li>
<li><a href="#personalización-de-leyendas" id="toc-personalización-de-leyendas" class="nav-link"
data-scroll-target="#personalización-de-leyendas"><span class="header-section-number"> 8.8 </span> Personalización de leyendas </a>
</li>
<li><a href="#varias-subgráficas" id="toc-varias-subgráficas" class="nav-link"
data-scroll-target="#varias-subgráficas"><span class="header-section-number"> 8.9 </span> Varias subgráficas </a>
</li>
<li><a href="#texto-y-anotaciones" id="toc-texto-y-anotaciones" class="nav-link"
data-scroll-target="#texto-y-anotaciones"><span class="header-section-number"> 8.10 </span> Texto y anotaciones </a>
</li>
<li><a href="#personalización-de-ticks" id="toc-personalización-de-ticks" class="nav-link"
data-scroll-target="#personalización-de-ticks"><span class="header-section-number"> 8.11 </span> Personalización de ticks </a>
</li>
<li><a href="#personalización-de-matplotlib" id="toc-personalización-de-matplotlib" class="nav-link"
data-scroll-target="#personalización-de-matplotlib"><span class="header-section-number"> 8.12 </span> Personalización de Matplotlib </a>
</li>
<li><a href="#visualización-con-seaborn" id="toc-visualización-con-seaborn" class="nav-link"
data-scroll-target="#visualización-con-seaborn"><span class="header-section-number"> 8.13 </span> Visualización con Seaborn </a>
</li>
<li><a href="#practice-exercises" id="toc-practice-exercises" class="nav-link"
data-scroll-target="#practice-exercises"><span class="header-section-number">8.14</span>
Ejercicios prácticos</a></li>
</ul>
</nav>
</div>
<!-- main -->
<main class="content" id="quarto-document-content">
<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title">
<h1 class="title"><span class="chapter-number">12</span> <span
class="chapter-title">Modelos de regresión</span></h1>
</div>
<div class="quarto-title-meta"> </div>
</header>
<section id="objetivo" class="level1">
<h1 class="anchored" data-anchor-id="objetivo">Objetivo</h1>
<p>
El objetivo de esta clase es que los estudiantes aprendan a implementar en Python varios modelos de regresión.</p>
</section>
<p>La regresión lineal es el algoritmo más sencillo del aprendizaje automático y se puede entrenar de distintas formas. En este cuaderno, cubriremos los siguientes algoritmos lineales:</p>
<ol type="1">
<li>Linear Regression</li>
<li>Robust Regression</li>
<li>Ridge Regression</li>
<li>LASSO Regression</li>
<li>Elastic Net</li>
<li>Polynomial Regression</li>
<li>Stochastic Gradient Descent</li>
<li>Artificial Neural Networks</li>
<li>Random Forest Regressor</li>
<li>Support Vector Machine</li>
</ol>
<p>Usaremos la base de datos <code>USA_Housing</code>, que contiene la siguiente información:</p>
<ul>
<li><code>Avg. Area Income</code>: Avg. The income of residents of the city house is located in.</li>
<li><code>Avg. Area House Age</code>: Avg Age of Houses in the same city</li>
<li><code>Avg. Area Number of Rooms</code>: Avg Number of Rooms for Houses in the same city</li>
<li><code>Avg. Area Number of Bedrooms</code>: Avg Number of Bedrooms for Houses in the same city</li>
<li><code>Area Population</code>: The population of city house is located in</li>
<li><code>Price</code>: Price that the house sold at</li>
<li><code>Address</code>: Address for the house</li>
</ul>
<div id="cell-3" class="cell">
<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> matplotlib.pyplot <span class="im">as</span> plt</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>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a>pd.set_option(<span class="st">'display.float'</span>, <span class="st">'</span><span class="sc">{:.2f}</span><span class="st">'</span>.<span class="bu">format</span>)</span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> decimal <span class="im">import</span> Decimal, getcontext</span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a>getcontext().prec <span class="op">=</span> <span class="dv">2</span></span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a><span class="op">%</span>matplotlib inline</span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a>sns.set_style(<span class="st">"whitegrid"</span>)</span>
<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a>plt.style.use(<span class="st">"fivethirtyeight"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<section id="análisis-exploratorio-de-datos" class="level2">
<h2 class="anchored" data-anchor-id="análisis-exploratorio-de-datos">12.1 Análisis exploratorio de datos</h2>
<div id="cell-5" class="cell">
<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>USAhousing <span class="op">=</span> pd.read_csv(<span class="st">'USA_Housing.csv'</span>)</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>USAhousing.head()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="cell-6" class="cell">
<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>USAhousing.info()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="cell-7" class="cell">
<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>USAhousing.describe()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="cell-8" class="cell">
<div class="sourceCode cell-code" id="cb5"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a>USAhousing.columns</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="cell-9" class="cell">
<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>sns.pairplot(USAhousing)</span>
<span id="cb6-2"><a href="#cb6-2" 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>
<div id="cell-10" class="cell">
<div class="sourceCode cell-code" id="cb7"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a>sns.heatmap(USAhousing.corr(numeric_only<span class="op">=</span><span class="va">True</span>), annot<span class="op">=</span><span class="va">True</span>, fmt<span class="op">=</span><span class="st">'0.2f'</span>)</span>
<span id="cb7-2"><a href="#cb7-2" 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>
</section>
<section id="preparación-de-los-datos" class="level2">
<h2 class="anchored" data-anchor-id="preparación-de-los-datos">12.2 Preparación de los datos</h2>
<div id="cell-12" class="cell">
<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>X <span class="op">=</span> USAhousing[[<span class="st">'Avg. Area Income'</span>, <span class="st">'Avg. Area House Age'</span>, <span class="st">'Avg. Area Number of Rooms'</span>,</span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a> <span class="st">'Avg. Area Number of Bedrooms'</span>, <span class="st">'Area Population'</span>]]</span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a>y <span class="op">=</span> USAhousing[<span class="st">'Price'</span>]</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="cell-13" class="cell">
<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><span class="im">from</span> sklearn.model_selection <span class="im">import</span> train_test_split</span>
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a>X_train, X_test, y_train, y_test <span class="op">=</span> train_test_split(X, y, test_size<span class="op">=</span><span class="fl">0.3</span>, random_state<span class="op">=</span><span class="dv">42</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="cell-14" class="cell">
<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="im">from</span> sklearn <span class="im">import</span> metrics</span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.model_selection <span class="im">import</span> cross_val_score</span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> cross_val(model):</span>
<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a> pred <span class="op">=</span> cross_val_score(model, X, y, cv<span class="op">=</span><span class="dv">10</span>)</span>
<span id="cb10-6"><a href="#cb10-6" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> pred.mean()</span>
<span id="cb10-7"><a href="#cb10-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-8"><a href="#cb10-8" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> print_evaluate(true, predicted): </span>
<span id="cb10-9"><a href="#cb10-9" aria-hidden="true" tabindex="-1"></a> mae <span class="op">=</span> metrics.mean_absolute_error(true, predicted)</span>
<span id="cb10-10"><a href="#cb10-10" aria-hidden="true" tabindex="-1"></a> mse <span class="op">=</span> metrics.mean_squared_error(true, predicted)</span>
<span id="cb10-11"><a href="#cb10-11" aria-hidden="true" tabindex="-1"></a> rmse <span class="op">=</span> np.sqrt(metrics.mean_squared_error(true, predicted))</span>
<span id="cb10-12"><a href="#cb10-12" aria-hidden="true" tabindex="-1"></a> r2_square <span class="op">=</span> metrics.r2_score(true, predicted)</span>
<span id="cb10-13"><a href="#cb10-13" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="ss">f'MAE: </span><span class="sc">{</span>mae<span class="sc">:0.2f}</span><span class="ss">'</span>)</span>
<span id="cb10-14"><a href="#cb10-14" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="ss">f'MSE: </span><span class="sc">{</span>mse<span class="sc">:0.2f}</span><span class="ss">'</span>)</span>
<span id="cb10-15"><a href="#cb10-15" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="ss">f'RMSE:: </span><span class="sc">{</span>rmse<span class="sc">:0.2f}</span><span class="ss">'</span>)</span>
<span id="cb10-16"><a href="#cb10-16" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="ss">f'R2 Square: </span><span class="sc">{</span>r2_square<span class="sc">:0.2f}</span><span class="ss">'</span>)</span>
<span id="cb10-17"><a href="#cb10-17" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="st">'__________________________________'</span>)</span>
<span id="cb10-18"><a href="#cb10-18" aria-hidden="true" tabindex="-1"></a> </span>
<span id="cb10-19"><a href="#cb10-19" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> evaluate(true, predicted):</span>
<span id="cb10-20"><a href="#cb10-20" aria-hidden="true" tabindex="-1"></a> mae <span class="op">=</span> metrics.mean_absolute_error(true, predicted)</span>
<span id="cb10-21"><a href="#cb10-21" aria-hidden="true" tabindex="-1"></a> mse <span class="op">=</span> metrics.mean_squared_error(true, predicted)</span>
<span id="cb10-22"><a href="#cb10-22" aria-hidden="true" tabindex="-1"></a> rmse <span class="op">=</span> np.sqrt(metrics.mean_squared_error(true, predicted))</span>
<span id="cb10-23"><a href="#cb10-23" aria-hidden="true" tabindex="-1"></a> r2_square <span class="op">=</span> metrics.r2_score(true, predicted)</span>
<span id="cb10-24"><a href="#cb10-24" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> mae, mse, rmse, r2_square</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>La regresión lineal se ha estudiado en profundidad y existe mucha literatura sobre cómo se deben estructurar los datos para aprovechar al máximo el modelo.</p>
<p>Por ello, hay mucha sofisticación al hablar de estos requisitos y expectativas, lo que puede resultar intimidante. En la práctica, puede utilizar estas reglas más como reglas generales al utilizar la regresión de mínimos cuadrados ordinarios, la implementación más común de la regresión lineal.</p>
<p>Pruebe diferentes preparaciones de sus datos utilizando estas heurísticas y vea qué funciona mejor para su problema.</p>
<ul>
<li><strong>Suposición lineal.</strong> La regresión lineal supone que la relación entre su entrada y salida es lineal. No admite nada más. Esto puede ser obvio, pero es bueno recordarlo cuando tiene muchos atributos. Es posible que deba transformar los datos para que la relación sea lineal (por ejemplo, transformación logarítmica para una relación exponencial).</li>
<li><strong>Eliminar ruido.</strong> La regresión lineal supone que sus variables de entrada y salida no son ruidosas. Considere utilizar operaciones de limpieza de datos que le permitan exponer y aclarar mejor la señal en sus datos. Esto es más importante para la variable de salida y desea eliminar los valores atípicos en la variable de salida (y) si es posible.</li>
<li><strong>Eliminar colinealidad.</strong> La regresión lineal sobreajustará sus datos cuando tenga variables de entrada altamente correlacionadas. Considere calcular correlaciones por pares para sus datos de entrada y eliminar los más correlacionados.</li>
<li><strong>Distribuciones gaussianas.</strong> La regresión lineal hará predicciones más confiables si sus variables de entrada y salida tienen una distribución gaussiana. Puede obtener algún beneficio al usar transformaciones (por ejemplo, log o BoxCox) en sus variables para hacer que su distribución se vea más gaussiana.</li>
<li><strong>Reescalar entradas:</strong> La regresión lineal a menudo hará predicciones más confiables si reescalar las variables de entrada usando estandarización o normalización.</li>
</ul>
<div id="cell-16" class="cell">
<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="im">from</span> sklearn.preprocessing <span class="im">import</span> StandardScaler</span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.pipeline <span class="im">import</span> Pipeline</span>
<span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a>pipeline <span class="op">=</span> Pipeline([</span>
<span id="cb11-5"><a href="#cb11-5" aria-hidden="true" tabindex="-1"></a> (<span class="st">'std_scalar'</span>, StandardScaler())</span>
<span id="cb11-6"><a href="#cb11-6" aria-hidden="true" tabindex="-1"></a>])</span>
<span id="cb11-7"><a href="#cb11-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb11-8"><a href="#cb11-8" aria-hidden="true" tabindex="-1"></a>X_train <span class="op">=</span> pipeline.fit_transform(X_train)</span>
<span id="cb11-9"><a href="#cb11-9" aria-hidden="true" tabindex="-1"></a>X_test <span class="op">=</span> pipeline.transform(X_test)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="modelos-de-regresión" class="level2">
<h2 class="anchored" data-anchor-id="modelos-de-regresión">12.3 Modelos de regresión</h2>
<section id="linear-regression" class="level3">
<h3 class="anchored" data-anchor-id="linear-regression">12.3.1 Linear Regression</h3>
<div id="cell-19" class="cell">
<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="im">from</span> sklearn.linear_model <span class="im">import</span> LinearRegression</span>
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a>lin_reg <span class="op">=</span> LinearRegression()</span>
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a>lin_reg.fit(X_train,y_train)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="cell-20" class="cell">
<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><span class="bu">print</span>(lin_reg.intercept_)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="cell-21" class="cell">
<div class="sourceCode cell-code" id="cb14"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"><a href="#cb14-1" aria-hidden="true" tabindex="-1"></a>coeff_df <span class="op">=</span> pd.DataFrame(lin_reg.coef_, X.columns, columns<span class="op">=</span>[<span class="st">'Coefficient'</span>])</span>
<span id="cb14-2"><a href="#cb14-2" aria-hidden="true" tabindex="-1"></a>coeff_df</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="cell-22" class="cell">
<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>pred <span class="op">=</span> lin_reg.predict(X_test)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="cell-23" class="cell">
<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>sns.scatterplot(x<span class="op">=</span>y_test, y<span class="op">=</span>pred)</span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a>plt.xlabel(<span class="st">'Valores reales'</span>)</span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a>plt.ylabel(<span class="st">'Valores predichos'</span>)</span>
<span id="cb16-4"><a href="#cb16-4" 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>
<div id="cell-24" class="cell">
<div class="sourceCode cell-code" id="cb17"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a>sns.kdeplot(x<span class="op">=</span>y_test<span class="op">-</span>pred)</span>
<span id="cb17-2"><a href="#cb17-2" 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>
<p>A continuación se presentan tres métricas de evaluación comunes para problemas de regresión:</p>
<ul>
<li><strong>Mean Absolute Error</strong> (MAE) es la media del valor absoluto de los errores:</li>
</ul>
<p><span class="math display">\[\frac 1n\sum_{i=1}^n|y_i-\hat{y}_i|\]</span></p>
<ul>
<li><strong>Mean Squared Error</strong> (MSE) es la media de los errores al cuadrado:</li>
</ul>
<p><span class="math display">\[\frac 1n\sum_{i=1}^n(y_i-\hat{y}_i)^2\]</span></p>
<ul>
<li><strong>Root Mean Squared Error</strong> (RMSE) es la raíz cuadrada de la media de los errores al cuadrado:</li>
</ul>
<p><span class="math display">\[\sqrt{\frac 1n\sum_{i=1}^n(y_i-\hat{y}_i)^2}\]</span></p>
<ul>
<li><strong>MAE</strong> es la más fácil de entender, porque es el error promedio.</li>
<li><strong>MSE</strong> es más popular que MAE, porque MSE “castiga” los errores mayores, lo que tiende a ser útil en el mundo real.</li>
<li><strong>RMSE</strong> es incluso más popular que MSE, porque RMSE es interpretable en las unidades de <span class="math inline">\(y\)</span>.</li>
</ul>
<p>Todas estas son <strong>funciones de pérdida</strong>, porque queremos minimizarlas.</p>
<div id="cell-26" class="cell">
<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>test_pred <span class="op">=</span> lin_reg.predict(X_test)</span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a>train_pred <span class="op">=</span> lin_reg.predict(X_train)</span>
<span id="cb18-3"><a href="#cb18-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb18-4"><a href="#cb18-4" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Test set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb18-5"><a href="#cb18-5" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_test, test_pred)</span>
<span id="cb18-6"><a href="#cb18-6" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Train set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb18-7"><a href="#cb18-7" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_train, train_pred)</span>
<span id="cb18-8"><a href="#cb18-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb18-9"><a href="#cb18-9" aria-hidden="true" tabindex="-1"></a>results_df <span class="op">=</span> pd.DataFrame(data<span class="op">=</span>[[<span class="st">"Linear Regression"</span>, <span class="op">*</span>evaluate(y_test, test_pred) , cross_val(LinearRegression())]], </span>
<span id="cb18-10"><a href="#cb18-10" aria-hidden="true" tabindex="-1"></a> columns<span class="op">=</span>[<span class="st">'Model'</span>, <span class="st">'MAE'</span>, <span class="st">'MSE'</span>, <span class="st">'RMSE'</span>, <span class="st">'R2 Square'</span>, <span class="st">"Cross Validation"</span>])</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="robust-regression" class="level3">
<h3 class="anchored" data-anchor-id="robust-regression">12.3.2 Robust Regression</h3>
<p>La regresión robusta es una forma de análisis de regresión diseñada para superar algunas limitaciones de los métodos paramétricos y no paramétricos tradicionales. Los métodos de regresión robusta están diseñados para no verse excesivamente afectados por las violaciones de los supuestos del proceso subyacente de generación de datos.</p>
<p>Un caso en el que se debe considerar la estimación robusta es cuando existe una fuerte sospecha de “heteroscedasticidad”.</p>
<p>Una situación común en la que se utiliza la estimación robusta se produce cuando los datos contienen valores atípicos. En presencia de valores atípicos que no provienen del mismo proceso de generación de datos que el resto de los datos, la estimación de mínimos cuadrados es ineficiente y puede estar sesgada. Debido a que las predicciones de mínimos cuadrados se arrastran hacia los valores atípicos, y debido a que la varianza de las estimaciones se infla artificialmente, el resultado es que los valores atípicos pueden quedar enmascarados. (En muchas situaciones, incluidas algunas áreas de geoestadística y estadística médica, son precisamente los valores atípicos los que interesan).</p>
<div id="cell-28" class="cell">
<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="im">from</span> sklearn.linear_model <span class="im">import</span> RANSACRegressor</span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> RANSACRegressor(max_trials<span class="op">=</span><span class="dv">100</span>)</span>
<span id="cb19-4"><a href="#cb19-4" aria-hidden="true" tabindex="-1"></a>model.fit(X_train, y_train)</span>
<span id="cb19-5"><a href="#cb19-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb19-6"><a href="#cb19-6" aria-hidden="true" tabindex="-1"></a>test_pred <span class="op">=</span> model.predict(X_test)</span>
<span id="cb19-7"><a href="#cb19-7" aria-hidden="true" tabindex="-1"></a>train_pred <span class="op">=</span> model.predict(X_train)</span>
<span id="cb19-8"><a href="#cb19-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb19-9"><a href="#cb19-9" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Test set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb19-10"><a href="#cb19-10" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_test, test_pred)</span>
<span id="cb19-11"><a href="#cb19-11" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'===================================='</span>)</span>
<span id="cb19-12"><a href="#cb19-12" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Train set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb19-13"><a href="#cb19-13" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_train, train_pred)</span>
<span id="cb19-14"><a href="#cb19-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb19-15"><a href="#cb19-15" aria-hidden="true" tabindex="-1"></a>results_df_2 <span class="op">=</span> pd.DataFrame(data<span class="op">=</span>[[<span class="st">"Robust Regression"</span>, <span class="op">*</span>evaluate(y_test, test_pred) , cross_val(RANSACRegressor())]], </span>
<span id="cb19-16"><a href="#cb19-16" aria-hidden="true" tabindex="-1"></a> columns<span class="op">=</span>[<span class="st">'Model'</span>, <span class="st">'MAE'</span>, <span class="st">'MSE'</span>, <span class="st">'RMSE'</span>, <span class="st">'R2 Square'</span>, <span class="st">"Cross Validation"</span>])</span>
<span id="cb19-17"><a href="#cb19-17" aria-hidden="true" tabindex="-1"></a>results_df <span class="op">=</span> pd.concat([results_df,results_df_2])</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="ridge-regression" class="level3">
<h3 class="anchored" data-anchor-id="ridge-regression">12.3.3 Ridge Regression</h3>
<p>La regresión <em>ridge</em> aborda algunos de los problemas de los <strong>mínimos cuadrados ordinarios</strong> al imponer una penalización en el tamaño de los coeficientes (Regularizacion de Tikhonov). Los coeficientes ridge minimizan una suma residual penalizada de cuadrados,</p>
<p><span class="math display">\[\min_{w}\big|\big|Xw-y\big|\big|^2_2+\alpha\big|\big|w\big|\big|^2_2\]</span></p>
<p><span class="math inline">\(\alpha\geq0\)</span> es un parámetro de complejidad que controla la cantidad de contracción: cuanto mayor sea el valor de <span class="math inline">\(\alpha\)</span>, mayor será la cantidad de contracción y, por lo tanto, los coeficientes se vuelven más robustos a la colinealidad.</p>
<p>La regresión <em>ridge</em> es un modelo penalizado L2.</p>
<div id="cell-30" class="cell">
<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="im">from</span> sklearn.linear_model <span class="im">import</span> Ridge</span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> Ridge(alpha<span class="op">=</span><span class="dv">100</span>, solver<span class="op">=</span><span class="st">'cholesky'</span>, tol<span class="op">=</span><span class="fl">0.0001</span>, random_state<span class="op">=</span><span class="dv">42</span>)</span>
<span id="cb20-4"><a href="#cb20-4" aria-hidden="true" tabindex="-1"></a>model.fit(X_train, y_train)</span>
<span id="cb20-5"><a href="#cb20-5" aria-hidden="true" tabindex="-1"></a>pred <span class="op">=</span> model.predict(X_test)</span>
<span id="cb20-6"><a href="#cb20-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb20-7"><a href="#cb20-7" aria-hidden="true" tabindex="-1"></a>test_pred <span class="op">=</span> model.predict(X_test)</span>
<span id="cb20-8"><a href="#cb20-8" aria-hidden="true" tabindex="-1"></a>train_pred <span class="op">=</span> model.predict(X_train)</span>
<span id="cb20-9"><a href="#cb20-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb20-10"><a href="#cb20-10" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Test set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb20-11"><a href="#cb20-11" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_test, test_pred)</span>
<span id="cb20-12"><a href="#cb20-12" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'===================================='</span>)</span>
<span id="cb20-13"><a href="#cb20-13" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Train set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb20-14"><a href="#cb20-14" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_train, train_pred)</span>
<span id="cb20-15"><a href="#cb20-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb20-16"><a href="#cb20-16" aria-hidden="true" tabindex="-1"></a>results_df_2 <span class="op">=</span> pd.DataFrame(data<span class="op">=</span>[[<span class="st">"Ridge Regression"</span>, <span class="op">*</span>evaluate(y_test, test_pred) , cross_val(Ridge())]], </span>
<span id="cb20-17"><a href="#cb20-17" aria-hidden="true" tabindex="-1"></a> columns<span class="op">=</span>[<span class="st">'Model'</span>, <span class="st">'MAE'</span>, <span class="st">'MSE'</span>, <span class="st">'RMSE'</span>, <span class="st">'R2 Square'</span>, <span class="st">"Cross Validation"</span>])</span>
<span id="cb20-18"><a href="#cb20-18" aria-hidden="true" tabindex="-1"></a>results_df <span class="op">=</span> pd.concat([results_df,results_df_2])</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="lasso-regression" class="level3">
<h3 class="anchored" data-anchor-id="lasso-regression">13.3.4 LASSO Regression</h3>
<p>Un modelo lineal que estima coeficientes dispersos.</p>
<p>Matemáticamente, consiste en un modelo lineal entrenado con L1 a priori como regularizador. La función objetivo a minimizar es:</p>
<p><span class="math display">\[\min_{w}\frac{1}{2n_{samples}} \big|\big|Xw - y\big|\big|_2^2 + \alpha \big|\big|w\big|\big|_1\]</span></p>
<p>La estimación del lazo resuelve así la minimización de la penalización de mínimos cuadrados con <span class="math inline">\(\alpha \big|\big|w\big|\big|_1\)</span> añadido, donde <span class="math inline">\(\alpha\)</span> es una constante y <span class="math inline">\(\big|\big|w\big|\big|_1\)</span> es la normal L1 del vector de parámetros.</p>
<div id="cell-32" class="cell">
<div class="sourceCode cell-code" id="cb21"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.linear_model <span class="im">import</span> Lasso</span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> Lasso(alpha<span class="op">=</span><span class="fl">0.1</span>, </span>
<span id="cb21-4"><a href="#cb21-4" aria-hidden="true" tabindex="-1"></a> precompute<span class="op">=</span><span class="va">True</span>, </span>
<span id="cb21-5"><a href="#cb21-5" aria-hidden="true" tabindex="-1"></a><span class="co"># warm_start=True, </span></span>
<span id="cb21-6"><a href="#cb21-6" aria-hidden="true" tabindex="-1"></a> positive<span class="op">=</span><span class="va">True</span>, </span>
<span id="cb21-7"><a href="#cb21-7" aria-hidden="true" tabindex="-1"></a> selection<span class="op">=</span><span class="st">'random'</span>,</span>
<span id="cb21-8"><a href="#cb21-8" aria-hidden="true" tabindex="-1"></a> random_state<span class="op">=</span><span class="dv">42</span>)</span>
<span id="cb21-9"><a href="#cb21-9" aria-hidden="true" tabindex="-1"></a>model.fit(X_train, y_train)</span>
<span id="cb21-10"><a href="#cb21-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-11"><a href="#cb21-11" aria-hidden="true" tabindex="-1"></a>test_pred <span class="op">=</span> model.predict(X_test)</span>
<span id="cb21-12"><a href="#cb21-12" aria-hidden="true" tabindex="-1"></a>train_pred <span class="op">=</span> model.predict(X_train)</span>
<span id="cb21-13"><a href="#cb21-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-14"><a href="#cb21-14" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Test set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb21-15"><a href="#cb21-15" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_test, test_pred)</span>
<span id="cb21-16"><a href="#cb21-16" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'===================================='</span>)</span>
<span id="cb21-17"><a href="#cb21-17" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Train set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb21-18"><a href="#cb21-18" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_train, train_pred)</span>
<span id="cb21-19"><a href="#cb21-19" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-20"><a href="#cb21-20" aria-hidden="true" tabindex="-1"></a>results_df_2 <span class="op">=</span> pd.DataFrame(data<span class="op">=</span>[[<span class="st">"Lasso Regression"</span>, <span class="op">*</span>evaluate(y_test, test_pred) , cross_val(Lasso())]], </span>
<span id="cb21-21"><a href="#cb21-21" aria-hidden="true" tabindex="-1"></a> columns<span class="op">=</span>[<span class="st">'Model'</span>, <span class="st">'MAE'</span>, <span class="st">'MSE'</span>, <span class="st">'RMSE'</span>, <span class="st">'R2 Square'</span>, <span class="st">"Cross Validation"</span>])</span>
<span id="cb21-22"><a href="#cb21-22" aria-hidden="true" tabindex="-1"></a>results_df <span class="op">=</span> pd.concat([results_df,results_df_2])</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="elastic-net" class="level3">
<h3 class="anchored" data-anchor-id="elastic-net">13.3.5 Elastic Net</h3>
<p>Un modelo de regresión lineal entrenado con L1 y L2 a priori como regularizador. Esta combinación permite aprender un modelo disperso donde pocos de los pesos son distintos de cero como Lasso, manteniendo al mismo tiempo las propiedades de regularización de Ridge. Elastic-net es útil cuando hay múltiples características que están correlacionadas entre sí. Es probable que Lasso elija una de ellas al azar, mientras que elastic-net probablemente elija ambas. Una ventaja práctica de la compensación entre Lasso y Ridge es que permite a Elastic-Net heredar parte de la estabilidad de Ridge bajo rotación. La función objetivo a minimizar es en este caso</p>
<p><span class="math display">\[\min_{w}{\frac{1}{2n_{samples}} \big|\big|X w - y\big|\big|_2 ^ 2 + \alpha \rho \big|\big|w\big|\big|_1 +
\frac{\alpha(1-\rho)}{2} \big|\big|w\big|\big|_2^2}\]</span></p>
<div id="cell-34" class="cell">
<div class="sourceCode cell-code" id="cb22"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.linear_model <span class="im">import</span> ElasticNet</span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb22-3"><a href="#cb22-3" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> ElasticNet(alpha<span class="op">=</span><span class="fl">0.1</span>, l1_ratio<span class="op">=</span><span class="fl">0.9</span>, selection<span class="op">=</span><span class="st">'random'</span>, random_state<span class="op">=</span><span class="dv">42</span>)</span>
<span id="cb22-4"><a href="#cb22-4" aria-hidden="true" tabindex="-1"></a>model.fit(X_train, y_train)</span>
<span id="cb22-5"><a href="#cb22-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb22-6"><a href="#cb22-6" aria-hidden="true" tabindex="-1"></a>test_pred <span class="op">=</span> model.predict(X_test)</span>
<span id="cb22-7"><a href="#cb22-7" aria-hidden="true" tabindex="-1"></a>train_pred <span class="op">=</span> model.predict(X_train)</span>
<span id="cb22-8"><a href="#cb22-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb22-9"><a href="#cb22-9" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Test set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb22-10"><a href="#cb22-10" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_test, test_pred)</span>
<span id="cb22-11"><a href="#cb22-11" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'===================================='</span>)</span>
<span id="cb22-12"><a href="#cb22-12" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Train set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb22-13"><a href="#cb22-13" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_train, train_pred)</span>
<span id="cb22-14"><a href="#cb22-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb22-15"><a href="#cb22-15" aria-hidden="true" tabindex="-1"></a>results_df_2 <span class="op">=</span> pd.DataFrame(data<span class="op">=</span>[[<span class="st">"Elastic Net Regression"</span>, <span class="op">*</span>evaluate(y_test, test_pred) , cross_val(ElasticNet())]], </span>
<span id="cb22-16"><a href="#cb22-16" aria-hidden="true" tabindex="-1"></a> columns<span class="op">=</span>[<span class="st">'Model'</span>, <span class="st">'MAE'</span>, <span class="st">'MSE'</span>, <span class="st">'RMSE'</span>, <span class="st">'R2 Square'</span>, <span class="st">"Cross Validation"</span>])</span>
<span id="cb22-17"><a href="#cb22-17" aria-hidden="true" tabindex="-1"></a>results_df <span class="op">=</span> pd.concat([results_df,results_df_2])</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="polynomial-regression" class="level3">
<h3 class="anchored" data-anchor-id="polynomial-regression">12.3.6 Polynomial Regression</h3>
<p>Un patrón común en el aprendizaje automático es el uso de modelos lineales entrenados con funciones no lineales de los datos. Este enfoque mantiene el rendimiento generalmente rápido de los métodos lineales, al tiempo que les permite adaptarse a una gama mucho más amplia de datos.</p>
<p>Por ejemplo, una regresión lineal simple se puede ampliar mediante la construcción de características polinómicas a partir de los coeficientes. En el caso de la regresión lineal estándar, es posible que tenga un modelo que se parezca a esto para datos bidimensionales:</p>
<p><span class="math display">\[\hat{y}(w, x) = w_0 + w_1 x_1 + w_2 x_2\]</span></p>
<p>Si queremos ajustar un paraboloide a los datos en lugar de un plano, podemos combinar las características en polinomios de segundo orden, de modo que el modelo se vea así:</p>
<p><span class="math display">\[\hat{y}(w, x) = w_0 + w_1 x_1 + w_2 x_2 + w_3 x_1 x_2 + w_4 x_1^2 + w_5 x_2^2\]</span></p>
<p>La observación (a veces sorprendente) es que este sigue siendo un modelo lineal: para ver esto, imagine crear una nueva variable</p>
<p><span class="math display">\[z = [x_1, x_2, x_1 x_2, x_1^2, x_2^2]\]</span></p>
<p>Con este reetiquetado de los datos, nuestro problema se puede escribir</p>
<p><span class="math display">\[\hat{y}(w, z) = w_0 + w_1 z_1 + w_2 z_2 + w_3 z_3 + w_4 z_4 + w_5 z_5\]</span></p>
<p>Vemos que la regresión polinómica resultante pertenece a la misma clase de modelos lineales que hemos considerado anteriormente (es decir, el modelo es lineal en w) y se puede resolver con las mismas técnicas. Al considerar ajustes lineales dentro de un espacio de mayor dimensión construido con estas funciones base, el modelo tiene la flexibilidad de ajustarse a un rango mucho más amplio de datos.</p>
<div id="cell-36" class="cell">
<div class="sourceCode cell-code" id="cb23"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.preprocessing <span class="im">import</span> PolynomialFeatures</span>
<span id="cb23-2"><a href="#cb23-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb23-3"><a href="#cb23-3" aria-hidden="true" tabindex="-1"></a>poly_reg <span class="op">=</span> PolynomialFeatures(degree<span class="op">=</span><span class="dv">2</span>)</span>
<span id="cb23-4"><a href="#cb23-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb23-5"><a href="#cb23-5" aria-hidden="true" tabindex="-1"></a>X_train_2_d <span class="op">=</span> poly_reg.fit_transform(X_train)</span>
<span id="cb23-6"><a href="#cb23-6" aria-hidden="true" tabindex="-1"></a>X_test_2_d <span class="op">=</span> poly_reg.transform(X_test)</span>
<span id="cb23-7"><a href="#cb23-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb23-8"><a href="#cb23-8" aria-hidden="true" tabindex="-1"></a>lin_reg <span class="op">=</span> LinearRegression()</span>
<span id="cb23-9"><a href="#cb23-9" aria-hidden="true" tabindex="-1"></a>lin_reg.fit(X_train_2_d,y_train)</span>
<span id="cb23-10"><a href="#cb23-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb23-11"><a href="#cb23-11" aria-hidden="true" tabindex="-1"></a>test_pred <span class="op">=</span> lin_reg.predict(X_test_2_d)</span>
<span id="cb23-12"><a href="#cb23-12" aria-hidden="true" tabindex="-1"></a>train_pred <span class="op">=</span> lin_reg.predict(X_train_2_d)</span>
<span id="cb23-13"><a href="#cb23-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb23-14"><a href="#cb23-14" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Test set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb23-15"><a href="#cb23-15" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_test, test_pred)</span>
<span id="cb23-16"><a href="#cb23-16" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'===================================='</span>)</span>
<span id="cb23-17"><a href="#cb23-17" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Train set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb23-18"><a href="#cb23-18" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_train, train_pred)</span>
<span id="cb23-19"><a href="#cb23-19" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb23-20"><a href="#cb23-20" aria-hidden="true" tabindex="-1"></a>results_df_2 <span class="op">=</span> pd.DataFrame(data<span class="op">=</span>[[<span class="st">"Polynomail Regression"</span>, <span class="op">*</span>evaluate(y_test, test_pred), <span class="dv">0</span>]], </span>
<span id="cb23-21"><a href="#cb23-21" aria-hidden="true" tabindex="-1"></a> columns<span class="op">=</span>[<span class="st">'Model'</span>, <span class="st">'MAE'</span>, <span class="st">'MSE'</span>, <span class="st">'RMSE'</span>, <span class="st">'R2 Square'</span>, <span class="st">'Cross Validation'</span>])</span>
<span id="cb23-22"><a href="#cb23-22" aria-hidden="true" tabindex="-1"></a>results_df <span class="op">=</span> pd.concat([results_df,results_df_2])</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="stochastic-gradient-descent" class="level3">
<h3 class="anchored" data-anchor-id="stochastic-gradient-descent">12.3.7 Stochastic Gradient Descent</h3>
<p>El descenso de gradiente es un algoritmo de optimización muy genérico capaz de encontrar soluciones óptimas para una amplia gama de problemas. La idea general del descenso de gradiente es ajustar los parámetros de forma iterativa para minimizar una función de costo. El descenso de gradiente mide el gradiente local de la función de error con respecto al vector de parámetros y va en la dirección del gradiente descendente. Una vez que el gradiente es cero, se ha alcanzado un mínimo.</p>
<div id="cell-38" class="cell">
<div class="sourceCode cell-code" id="cb24"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.linear_model <span class="im">import</span> SGDRegressor</span>
<span id="cb24-2"><a href="#cb24-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-3"><a href="#cb24-3" aria-hidden="true" tabindex="-1"></a>sgd_reg <span class="op">=</span> SGDRegressor(n_iter_no_change<span class="op">=</span><span class="dv">250</span>, penalty<span class="op">=</span><span class="va">None</span>, eta0<span class="op">=</span><span class="fl">0.0001</span>, max_iter<span class="op">=</span><span class="dv">100000</span>)</span>
<span id="cb24-4"><a href="#cb24-4" aria-hidden="true" tabindex="-1"></a>sgd_reg.fit(X_train, y_train)</span>
<span id="cb24-5"><a href="#cb24-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-6"><a href="#cb24-6" aria-hidden="true" tabindex="-1"></a>test_pred <span class="op">=</span> sgd_reg.predict(X_test)</span>
<span id="cb24-7"><a href="#cb24-7" aria-hidden="true" tabindex="-1"></a>train_pred <span class="op">=</span> sgd_reg.predict(X_train)</span>
<span id="cb24-8"><a href="#cb24-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-9"><a href="#cb24-9" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Test set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb24-10"><a href="#cb24-10" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_test, test_pred)</span>
<span id="cb24-11"><a href="#cb24-11" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'===================================='</span>)</span>
<span id="cb24-12"><a href="#cb24-12" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Train set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb24-13"><a href="#cb24-13" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_train, train_pred)</span>
<span id="cb24-14"><a href="#cb24-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-15"><a href="#cb24-15" aria-hidden="true" tabindex="-1"></a>results_df_2 <span class="op">=</span> pd.DataFrame(data<span class="op">=</span>[[<span class="st">"Stochastic Gradient Descent"</span>, <span class="op">*</span>evaluate(y_test, test_pred), <span class="dv">0</span>]], </span>
<span id="cb24-16"><a href="#cb24-16" aria-hidden="true" tabindex="-1"></a> columns<span class="op">=</span>[<span class="st">'Model'</span>, <span class="st">'MAE'</span>, <span class="st">'MSE'</span>, <span class="st">'RMSE'</span>, <span class="st">'R2 Square'</span>, <span class="st">'Cross Validation'</span>])</span>
<span id="cb24-17"><a href="#cb24-17" aria-hidden="true" tabindex="-1"></a>results_df <span class="op">=</span> pd.concat([results_df,results_df_2])</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="artficial-neural-network" class="level3">
<h3 class="anchored" data-anchor-id="artficial-neural-network">12.3.8 Artficial Neural Network</h3>
<div class="sourceCode cell-code" id="cb25"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> tensorflow.keras.models <span class="im">import</span> Sequential</span>
<span id="cb25-2"><a href="#cb25-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> tensorflow.keras.layers <span class="im">import</span> Input, Dense, Activation, Dropout</span>
<span id="cb25-3"><a href="#cb25-3" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> tensorflow.keras.optimizers <span class="im">import</span> Adam</span>
<span id="cb25-4"><a href="#cb25-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb25-5"><a href="#cb25-5" aria-hidden="true" tabindex="-1"></a>X_train <span class="op">=</span> np.array(X_train)</span>
<span id="cb25-6"><a href="#cb25-6" aria-hidden="true" tabindex="-1"></a>X_test <span class="op">=</span> np.array(X_test)</span>
<span id="cb25-7"><a href="#cb25-7" aria-hidden="true" tabindex="-1"></a>y_train <span class="op">=</span> np.array(y_train)</span>
<span id="cb25-8"><a href="#cb25-8" aria-hidden="true" tabindex="-1"></a>y_test <span class="op">=</span> np.array(y_test)</span>
<span id="cb25-9"><a href="#cb25-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb25-10"><a href="#cb25-10" aria-hidden="true" tabindex="-1"></a>model <span class="op">=</span> Sequential()</span>
<span id="cb25-11"><a href="#cb25-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb25-12"><a href="#cb25-12" aria-hidden="true" tabindex="-1"></a>model.add(Dense(X_train.shape[<span class="dv">1</span>], activation<span class="op">=</span><span class="st">'relu'</span>))</span>
<span id="cb25-13"><a href="#cb25-13" aria-hidden="true" tabindex="-1"></a>model.add(Dense(<span class="dv">32</span>, activation<span class="op">=</span><span class="st">'relu'</span>))</span>
<span id="cb25-14"><a href="#cb25-14" aria-hidden="true" tabindex="-1"></a><span class="co"># model.add(Dropout(0.2))</span></span>
<span id="cb25-15"><a href="#cb25-15" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb25-16"><a href="#cb25-16" aria-hidden="true" tabindex="-1"></a>model.add(Dense(<span class="dv">64</span>, activation<span class="op">=</span><span class="st">'relu'</span>))</span>
<span id="cb25-17"><a href="#cb25-17" aria-hidden="true" tabindex="-1"></a><span class="co"># model.add(Dropout(0.2))</span></span>
<span id="cb25-18"><a href="#cb25-18" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb25-19"><a href="#cb25-19" aria-hidden="true" tabindex="-1"></a>model.add(Dense(<span class="dv">128</span>, activation<span class="op">=</span><span class="st">'relu'</span>))</span>
<span id="cb25-20"><a href="#cb25-20" aria-hidden="true" tabindex="-1"></a><span class="co"># model.add(Dropout(0.2))</span></span>
<span id="cb25-21"><a href="#cb25-21" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb25-22"><a href="#cb25-22" aria-hidden="true" tabindex="-1"></a>model.add(Dense(<span class="dv">512</span>, activation<span class="op">=</span><span class="st">'relu'</span>))</span>
<span id="cb25-23"><a href="#cb25-23" aria-hidden="true" tabindex="-1"></a>model.add(Dropout(<span class="fl">0.1</span>))</span>
<span id="cb25-24"><a href="#cb25-24" aria-hidden="true" tabindex="-1"></a>model.add(Dense(<span class="dv">1</span>))</span>
<span id="cb25-25"><a href="#cb25-25" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb25-26"><a href="#cb25-26" aria-hidden="true" tabindex="-1"></a>model.<span class="bu">compile</span>(optimizer<span class="op">=</span>Adam(<span class="fl">0.00001</span>), loss<span class="op">=</span><span class="st">'mse'</span>)</span>
<span id="cb25-27"><a href="#cb25-27" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb25-28"><a href="#cb25-28" aria-hidden="true" tabindex="-1"></a>r <span class="op">=</span> model.fit(X_train, y_train,</span>
<span id="cb25-29"><a href="#cb25-29" aria-hidden="true" tabindex="-1"></a> validation_data<span class="op">=</span>(X_test,y_test),</span>
<span id="cb25-30"><a href="#cb25-30" aria-hidden="true" tabindex="-1"></a> batch_size<span class="op">=</span><span class="dv">1</span>,</span>
<span id="cb25-31"><a href="#cb25-31" aria-hidden="true" tabindex="-1"></a> epochs<span class="op">=</span><span class="dv">100</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div id="cell-41" class="cell">
<div class="sourceCode cell-code" id="cb26"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb26-1"><a href="#cb26-1" aria-hidden="true" tabindex="-1"></a>test_pred <span class="op">=</span> model.predict(X_test)</span>
<span id="cb26-2"><a href="#cb26-2" aria-hidden="true" tabindex="-1"></a>train_pred <span class="op">=</span> model.predict(X_train)</span>
<span id="cb26-3"><a href="#cb26-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb26-4"><a href="#cb26-4" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Test set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb26-5"><a href="#cb26-5" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_test, test_pred)</span>
<span id="cb26-6"><a href="#cb26-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb26-7"><a href="#cb26-7" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Train set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb26-8"><a href="#cb26-8" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_train, train_pred)</span>
<span id="cb26-9"><a href="#cb26-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb26-10"><a href="#cb26-10" aria-hidden="true" tabindex="-1"></a>results_df_2 <span class="op">=</span> pd.DataFrame(data<span class="op">=</span>[[<span class="st">"Artficial Neural Network"</span>, <span class="op">*</span>evaluate(y_test, test_pred), <span class="dv">0</span>]], </span>
<span id="cb26-11"><a href="#cb26-11" aria-hidden="true" tabindex="-1"></a> columns<span class="op">=</span>[<span class="st">'Model'</span>, <span class="st">'MAE'</span>, <span class="st">'MSE'</span>, <span class="st">'RMSE'</span>, <span class="st">'R2 Square'</span>, <span class="st">'Cross Validation'</span>])</span>
<span id="cb26-12"><a href="#cb26-12" aria-hidden="true" tabindex="-1"></a>results_df <span class="op">=</span> pd.concat([results_df,results_df_2])</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="random-forest-regressor" class="level3">
<h3 class="anchored" data-anchor-id="random-forest-regressor">12.3.9 Random Forest Regressor</h3>
<div id="cell-43" class="cell">
<div class="sourceCode cell-code" id="cb27"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb27-1"><a href="#cb27-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.ensemble <span class="im">import</span> RandomForestRegressor</span>
<span id="cb27-2"><a href="#cb27-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb27-3"><a href="#cb27-3" aria-hidden="true" tabindex="-1"></a>rf_reg <span class="op">=</span> RandomForestRegressor(n_estimators<span class="op">=</span><span class="dv">1000</span>)</span>
<span id="cb27-4"><a href="#cb27-4" aria-hidden="true" tabindex="-1"></a>rf_reg.fit(X_train, y_train)</span>
<span id="cb27-5"><a href="#cb27-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb27-6"><a href="#cb27-6" aria-hidden="true" tabindex="-1"></a>test_pred <span class="op">=</span> rf_reg.predict(X_test)</span>
<span id="cb27-7"><a href="#cb27-7" aria-hidden="true" tabindex="-1"></a>train_pred <span class="op">=</span> rf_reg.predict(X_train)</span>
<span id="cb27-8"><a href="#cb27-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb27-9"><a href="#cb27-9" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Test set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb27-10"><a href="#cb27-10" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_test, test_pred)</span>
<span id="cb27-11"><a href="#cb27-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb27-12"><a href="#cb27-12" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Train set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb27-13"><a href="#cb27-13" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_train, train_pred)</span>
<span id="cb27-14"><a href="#cb27-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb27-15"><a href="#cb27-15" aria-hidden="true" tabindex="-1"></a>results_df_2 <span class="op">=</span> pd.DataFrame(data<span class="op">=</span>[[<span class="st">"Random Forest Regressor"</span>, <span class="op">*</span>evaluate(y_test, test_pred), <span class="dv">0</span>]], </span>
<span id="cb27-16"><a href="#cb27-16" aria-hidden="true" tabindex="-1"></a> columns<span class="op">=</span>[<span class="st">'Model'</span>, <span class="st">'MAE'</span>, <span class="st">'MSE'</span>, <span class="st">'RMSE'</span>, <span class="st">'R2 Square'</span>, <span class="st">'Cross Validation'</span>])</span>
<span id="cb27-17"><a href="#cb27-17" aria-hidden="true" tabindex="-1"></a>results_df <span class="op">=</span> pd.concat([results_df,results_df_2])</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
<section id="support-vector-machine" class="level3">
<h3 class="anchored" data-anchor-id="support-vector-machine">12.3.10 Support Vector Machine</h3>
<div id="cell-45" class="cell">
<div class="sourceCode cell-code" id="cb28"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb28-1"><a href="#cb28-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> sklearn.svm <span class="im">import</span> SVR</span>
<span id="cb28-2"><a href="#cb28-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb28-3"><a href="#cb28-3" aria-hidden="true" tabindex="-1"></a>svm_reg <span class="op">=</span> SVR(kernel<span class="op">=</span><span class="st">'rbf'</span>, C<span class="op">=</span><span class="dv">1000000</span>, epsilon<span class="op">=</span><span class="fl">0.001</span>)</span>
<span id="cb28-4"><a href="#cb28-4" aria-hidden="true" tabindex="-1"></a>svm_reg.fit(X_train, y_train)</span>
<span id="cb28-5"><a href="#cb28-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb28-6"><a href="#cb28-6" aria-hidden="true" tabindex="-1"></a>test_pred <span class="op">=</span> svm_reg.predict(X_test)</span>
<span id="cb28-7"><a href="#cb28-7" aria-hidden="true" tabindex="-1"></a>train_pred <span class="op">=</span> svm_reg.predict(X_train)</span>
<span id="cb28-8"><a href="#cb28-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb28-9"><a href="#cb28-9" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Test set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb28-10"><a href="#cb28-10" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_test, test_pred)</span>
<span id="cb28-11"><a href="#cb28-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb28-12"><a href="#cb28-12" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="st">'Train set evaluation:</span><span class="ch">\n</span><span class="st">_____________________________________'</span>)</span>
<span id="cb28-13"><a href="#cb28-13" aria-hidden="true" tabindex="-1"></a>print_evaluate(y_train, train_pred)</span>
<span id="cb28-14"><a href="#cb28-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb28-15"><a href="#cb28-15" aria-hidden="true" tabindex="-1"></a>results_df_2 <span class="op">=</span> pd.DataFrame(data<span class="op">=</span>[[<span class="st">"SVM Regressor"</span>, <span class="op">*</span>evaluate(y_test, test_pred), <span class="dv">0</span>]], </span>
<span id="cb28-16"><a href="#cb28-16" aria-hidden="true" tabindex="-1"></a> columns<span class="op">=</span>[<span class="st">'Model'</span>, <span class="st">'MAE'</span>, <span class="st">'MSE'</span>, <span class="st">'RMSE'</span>, <span class="st">'R2 Square'</span>, <span class="st">'Cross Validation'</span>])</span>
<span id="cb28-17"><a href="#cb28-17" aria-hidden="true" tabindex="-1"></a>results_df <span class="op">=</span> pd.concat([results_df,results_df_2])</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<div id="cell-46" class="cell">
<div class="sourceCode cell-code" id="cb29"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb29-1"><a href="#cb29-1" aria-hidden="true" tabindex="-1"></a>results_df</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
</section>
</section>
<section id="comparación-de-los-modelos" class="level2">
<h2 class="anchored" data-anchor-id="comparación-de-los-modelos">12.4 Comparación de los modelos</h2>
<div id="cell-48" class="cell">
<div class="sourceCode cell-code" id="cb30"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb30-1"><a href="#cb30-1" aria-hidden="true" tabindex="-1"></a>results_df.set_index(<span class="st">'Model'</span>, inplace<span class="op">=</span><span class="va">True</span>)</span>
<span id="cb30-2"><a href="#cb30-2" aria-hidden="true" tabindex="-1"></a>results_df[<span class="st">'R2 Square'</span>].plot(kind<span class="op">=</span><span class="st">'barh'</span>, figsize<span class="op">=</span>(<span class="dv">12</span>, <span class="dv">8</span>))</span>
<span id="cb30-3"><a href="#cb30-3" 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>
</section>
<section id="practice-exercises" class="level2" data-number="12.5">
<h2 data-number="12.5" class="anchored" data-anchor-id="practice-exercises"><span
class="header-section-number">12.5</span> Ejercicios prácticos </h2>
<ol type="1">
<li>Cree un nuevo Notebook.</li>
<li>Guarde el archivo como <strong>Ejercicios_practicos_clase_11.ipynb</strong>.</li>
<li>Asigne un título <strong>H1</strong> con su nombre.</li>
</ol>
<section id="practice-exercise-1" class="level3" data-number="11.6.1">
<h3 data-number="11.6.1" class="anchored" data-anchor-id="practice-exercise-1"><span
class="header-section-number">12.5.1 </span> Ejercicio práctico 1 </h3>
<p>Implemente dos modelos de regresión usando la base de datos <a href="https://archive.ics.uci.edu/dataset/360/air+quality"><i>Air Quality</i></a>.</p>
</section>
</main> <!-- /main -->
<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 isCodeAnnotation = (el) => {
for (const clz of el.classList) {
if (clz.startsWith('code-annotation-')) {
return true;
}
}
return false;
}
const clipboard = new window.ClipboardJS('.code-copy-button', {
text: function (trigger) {
const codeEl = trigger.previousElementSibling.cloneNode(true);
for (const childEl of codeEl.children) {
if (isCodeAnnotation(childEl)) {
childEl.remove();
}
}
return codeEl.innerText;
}
});
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!");
let tooltip;
if (window.bootstrap) {
button.setAttribute("data-bs-toggle", "tooltip");
button.setAttribute("data-bs-placement", "left");
button.setAttribute("data-bs-title", "Copied!");
tooltip = new bootstrap.Tooltip(button,
{
trigger: "manual",
customClass: "code-copy-button-tooltip",
offset: [0, -8]
});
tooltip.show();
}
setTimeout(function () {
if (tooltip) {
tooltip.hide();
button.removeAttribute("data-bs-title");
button.removeAttribute("data-bs-toggle");
button.removeAttribute("data-bs-placement");
}
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 () {
// use id or data attribute instead here
let href = ref.getAttribute('data-footnote-href') || ref.getAttribute('href');
try { href = new URL(href).hash; } catch { }
const id = href.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
return note.innerHTML;