-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpractica1.tex
More file actions
executable file
·2431 lines (2119 loc) · 90.3 KB
/
practica1.tex
File metadata and controls
executable file
·2431 lines (2119 loc) · 90.3 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
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The Legrand Orange Book
% LaTeX Template
% Version 2.1.1 (14/2/16)
%
% This template has been downloaded from:
% http://www.LaTeXTemplates.com
%
% Original author:
% Mathias Legrand (legrand.mathias@gmail.com) with modifications by:
% Vel (vel@latextemplates.com)
%
% License:
% CC BY-NC-SA 3.0 (http://creativecommons.org/licenses/by-nc-sa/3.0/)
%
% Compiling this template:
% This template uses biber for its bibliography and makeindex for its index.
% When you first open the template, compile it from the command line with the
% commands below to make sure your LaTeX distribution is configured correctly:
%
% 1) pdflatex main
% 2) makeindex main.idx -s StyleInd.ist
% 3) biber main
% 4) pdflatex main x 2
%
% After this, when you wish to update the bibliography/index use the appropriate
% command above and make sure to compile with pdflatex several times
% afterwards to propagate your changes to the document.
%
% This template also uses a number of packages which may need to be
% updated to the newest versions for the template to compile. It is strongly
% recommended you update your LaTeX distribution if you have any
% compilation errors.
%
% Important note:
% Chapter heading images should have a 2:1 width:height ratio,
% e.g. 920px width and 460px height.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%----------------------------------------------------------------------------------------
% PACKAGES AND OTHER DOCUMENT CONFIGURATIONS
%----------------------------------------------------------------------------------------
\documentclass[11pt,fleqn]{book} % Default font size and left-justified equations
%----------------------------------------------------------------------------------------
\input{structure} % Insert the commands.tex file which contains the majority of the structure behind the template
%%% Códigos R ...
% Paquete listings para visualización de código más elegante
\usepackage{xcolor,listings}
\usepackage{textcomp}
\lstset{upquote=true}
\lstloadlanguages{R}
\usepackage{color}
\definecolor{mygreen}{rgb}{0,0.6,0}
\definecolor{mygray}{rgb}{0.5,0.5,0.5}
\definecolor{mymauve}{rgb}{0.58,0,0.82}
\lstset{ %
backgroundcolor=\color{white}, % choose the background color; you must add \usepackage{color} or \usepackage{xcolor}
basicstyle=\footnotesize, % the size of the fonts that are used for the code
breakatwhitespace=false, % sets if automatic breaks should only happen at whitespace
breaklines=true, % sets automatic line breaking
captionpos=b, % sets the caption-position to bottom
commentstyle=\color{mygreen}, % comment style
deletekeywords={...}, % if you want to delete keywords from the given language
escapeinside={\%*}{*)}, % if you want to add LaTeX within your code
extendedchars=true, % lets you use non-ASCII characters; for 8-bits encodings only, does not work with UTF-8
frame=single, % adds a frame around the code
keepspaces=true, % keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible)
keywordstyle=\color{blue}, % keyword style
language=R , % the language of the code
otherkeywords={*,...}, % if you want to add more keywords to the set
numbers=left, % where to put the line-numbers; possible values are (none, left, right)
numbersep=5pt, % how far the line-numbers are from the code
numberstyle=\tiny\color{mygray}, % the style that is used for the line-numbers
rulecolor=\color{black}, % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. comments (green here))
showspaces=false, % show spaces everywhere adding particular underscores; it overrides 'showstringspaces'
showstringspaces=false, % underline spaces within strings only
showtabs=false, % show tabs within strings adding particular underscores
stepnumber=2, % the step between two line-numbers. If it's 1, each line will be numbered
stringstyle=\color{mymauve}, % string literal style
tabsize=2, % sets default tabsize to 2 spaces
title=\lstname % show the filename of files included with \lstinputlisting; also try caption instead of title
}
%Para los comentarios multilinea
\usepackage{verbatim}
% Para la multicolumna
\usepackage{multicol}
% Para la animación en .gif
\usepackage{movie15}
\begin{document}
%----------------------------------------------------------------------------------------
% TITLE PAGE
%----------------------------------------------------------------------------------------
\begingroup
\thispagestyle{empty}
\begin{tikzpicture}[remember picture,overlay]
\coordinate [below=12cm] (midpoint) at (current page.north);
\node at (current page.north west)
{\begin{tikzpicture}[remember picture,overlay]
\node[anchor=north west,inner sep=0pt] at (0,0) {\includegraphics[width=\paperwidth]{background}}; % Background image
\draw[anchor=north] (midpoint) node [fill=ocre!30!white,fill opacity=0.6,text opacity=1,inner sep=1cm]{\Huge\centering
\bfseries\sffamily\parbox[c][][t]{\paperwidth}{\centering Análisis y Visualización de Datos con R\\[15pt] % Book title
{\Large Orientado al Aprendizaje Automático}\\[20pt] % Subtitle
{\huge Rafael Nogales}}}; % Author name
\end{tikzpicture}};
\end{tikzpicture}
\vfill
\endgroup
%----------------------------------------------------------------------------------------
% COPYRIGHT PAGE
%----------------------------------------------------------------------------------------
\newpage
~\vfill
\thispagestyle{empty}
\noindent Copyright \copyright\ 2016 Rafael Nogales\\ % Copyright notice
%\noindent \textsc{Published by Publisher}\\ % Publisher
%\noindent \textsc{book-website.com}\\ % URL
\noindent Licensed under the Creative Commons Attribution-NonCommercial 3.0 Unported License (the ``License''). You may not use this file except in compliance with the License. You may obtain a copy of the License at \url{http://creativecommons.org/licenses/by-nc/3.0}. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \textsc{``as is'' basis, without warranties or conditions of any kind}, either express or implied. See the License for the specific language governing permissions and limitations under the License.\\ % License information
\noindent \textit{First printing, February 2016} % Printing/edition date
%----------------------------------------------------------------------------------------
% TABLE OF CONTENTS
%----------------------------------------------------------------------------------------
%\usechapterimagefalse % If you don't want to include a chapter image, use this to toggle images off - it can be enabled later with \usechapterimagetrue
\chapterimage{chapter_head_1.pdf} % Table of contents heading image
\pagestyle{empty} % No headers
\tableofcontents % Print the table of contents itself
%\cleardoublepage % Forces the first chapter to start on an odd page so it's on the right
\pagestyle{fancy} % Print headers again
%----------------------------------------------------------------------------------------
% PART
%----------------------------------------------------------------------------------------
%\part{Part One}
%----------------------------------------------------------------------------------------
% CHAPTER 1
%----------------------------------------------------------------------------------------
\chapterimage{chapter_head_2.pdf} % Chapter heading image
\chapter{Práctica 1}
\section{Eliminar valores perdidos}\index{Paragraphs of Text}
En muchas ocasiones cuanto trabajamos con un vector, una lista o un data.frame nos encontramos con que hay valores NA \textit{not available} o NaN \textit{not a number}.\\
Para poder trabajar cómodamente lo ideal es eliminar esos valores, vamos a ver dos formas de hacer esto:\\
La primera es utilizar la función de R \textbf{is.na()}
\begin{sintaxis}[is.na()]
Devuelve un vector de TRUE/FALSE del mismo tamaño que el argumento, la posición $i$ es TRUE si x[i] es NA o NaN.
\end{sintaxis}
\textbf{Ejemplo:}
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> x <- c(2, NA, NaN, 123)
> x
[1] 2 NA NaN 123
> x <- x[!is.na(x)]
> x
[1] 2 123
\end{lstlisting}
La otra forma es utilizando la función \textbf{complete.cases()} que hace lo mismo pero puede aplicarse a data.frames\\
\textbf{Ejemplo:}
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> x <- c(2, NA, NaN, 123)
> x
[1] 2 NA NaN 123
> x <- x[complete.cases(x)]
> x
[1] 2 123
> x <- c(2, NA, NaN, 123)
> complete.cases(x)
[1] TRUE FALSE FALSE TRUE
> !is.na(x)
[1] TRUE FALSE FALSE TRUE
\end{lstlisting}
\section{Lanzar dos dados}\index{Paragraphs of Text}
\begin{exercise}
Crea una función denominada \textit{puntuación} que simule tirar dos dados, y devuelva la suma. Los lanzamientos deben ser independientes.\\
Nota: Utiliza la función \textbf{sample}. Deben de poder obteners valores como 2 o 12.
\end{exercise}
\textbf{Solución}\\
Código de la función puntuación para un dado:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> puntuacion <- function(){
return(sample(6,1) + sample(6,1));
}
\end{lstlisting}
Observemos la sintaxis de la función sample:\\
\begin{sintaxis}[sample(x, size, replace = FALSE, prob = NULL)]
Los parámetros que vamos a considerar importantes por el momento son los tres primeros:
\begin{itemize}
\item \textbf{x} indica el conjunto de donde se van a extraer las muestras un número $n$ indica 1...$n$
\item \textbf{size} indica cuantas muestras vamos a extrar, en nuestro caso solo queremos una de cada dado
\item \textbf{replace} indica si se pueden repetir muestras, en nuestro caso da igual porque solo vamos a sacar una muestra.
\end{itemize}
\end{sintaxis}
Aquí vemos unas cuantas ejecuciones de la función puntuación tal y como la llevamos:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> puntuacion()
[1] 3
> puntuacion()
[1] 12
> puntuacion()
[1] 7
> puntuacion()
[1] 9
\end{lstlisting}
\textbf{Nota:} Si escribimos "puntuacion" en RStudio podemos ver el código de la función puntuación.\\
Ahora vamos a redefinir la función para que haga $n$ lanzamientos y los guarde en un vector. Luego vamos a ejecutarla unas cuantas veces para ver como funciona:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> puntuacion <- function(n){
+ vect_punt<-0;
+ for(i in 1:n){
+ vect_punt[i]<-(sample(6,1) + sample(6,1));
+ }
+ return (vect_punt);
+ }
> puntuacion(12)
[1] 9 5 10 4 5 3 8 12 7 6 10 7
> x<-puntuacion(12)
> x
[1] 8 10 4 10 10 11 3 11 9 7 9 3
> sort(x)
[1] 3 3 4 7 8 9 9 10 10 10 11 11
\end{lstlisting}
Parece que funciona correctamente, pero nosotros sabemos que en este experimento la media es 7, veamoslo experimentalmente:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> mean(puntuacion(10000))
[1] 6.9958
> mean(puntuacion(10000))
[1] 7.0069
\end{lstlisting}
Podemos además hacer cosas más interesantes como un histograma:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> x<-puntuacion(2000)
> hist(x, col="blue",breaks = 1:12,main="Tirar 2000 dados dobles", xlab = "Score")
\end{lstlisting}
Que devuelve la siguiente figura:
\begin{figure}[htbp]
\includegraphics[scale=0.7]{Pictures/2000dados.png}
\end{figure}
%------------------------------------------------
\section{Baraja Española}
\begin{exercise}
Vamos a manipular la baraja española, a barajarla y a robar de la baraja. Para ello será necesario
crear la baraja: un dataframe y dos funciones \textit{barajar} y \textit{robar}.
\end{exercise}
\textbf{Solución}\\
Para crear la baraja vamos a utilizar la función \textbf{expand.grid()} que genera un data.frame con todas las combinaciones posibles de elementos de los vectores que se le meten como parámetros.
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
BarajaESP<-function(){
figuras <- c(1:7, "Sota", "Caballo", "Rey");
palos <- c("Espadas", "Oros", "Copas", "Bastos");
baraja <- expand.grid(Carta = figuras, Palo = palos);
return(baraja)
}
\end{lstlisting}
Devuelve el siguiente data.frame:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> baraja<-BarajaESP()
> baraja> baraja
Carta Palo
1 1 Espadas
2 2 Espadas
3 3 Espadas
4 4 Espadas
5 5 Espadas
6 6 Espadas
7 7 Espadas
8 Sota Espadas
9 Caballo Espadas
10 Rey Espadas
11 1 Oros
12 2 Oros
..................
37 7 Bastos
38 Sota Bastos
39 Caballo Bastos
40 Rey Bastos
}
\end{lstlisting}
Podemos incluso hacer un plot de baraja y veremos la baraja así:
\begin{figure}
\includegraphics[scale=0.5]{baraja.png}
\end{figure}
\pagebreak
Para la función de barajar volvemos a utilizar la función \textbf{sample}:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> barajar <- function(baraja){
tmp <- baraja;
orden <- sample(1:40,40,replace = FALSE);
for(i in orden){
tmp[i, 1:2] <- baraja[orden[i], 1:2]
}
return(tmp)
}
\end{lstlisting}
Tenemos en cuenta que tmp será un nuevo dataframe que al principio contendrá la baraja en el mismo orden.
Pero poco a poco vamos reemplazando las cartas, para ello hacemos una permutación de los primeros 40 naturales y la guardamos en \textit{orden} después aplicamos esa permutación a las cartas.\\
Es importante darse observar que \textit{baraja[i, 1:2]} es la forma de representar la carta i-esima de la baraja, utilizamos \textit{1:2} para indicar "número y palo".
La función \textbf{robar()} es más sencilla y no requiere explicación:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> robar <- function(baraja){
return(baraja[sample(1:40,1, replace = FALSE), 1:2])
}
> robar(baraja)
Carta Palo
11 1 Oros
> robar(baraja)
Carta Palo
14 4 Oros
\end{lstlisting}
Es importante apreciar que esta forma de robar va volviendo a colocar la carta en la baraja, por tanto es posible robar dos veces la misma carta.
\chapter{Práctica 2}
\section{Generación y Visualización de Datos}\index{Paragraphs of Text}
\begin{exercise}
Construir una función $lista = simula\_unif(N,dim,rango)$ que calcule una lista de longitud N de vectores de dimension dim conteniendo números aleatorios uniformes en el intervalo rango.
\end{exercise}
Parece que lo más natural es crear una función que utilice \textbf{runif()} que es una función de R que genera números siguiendo una distribución uniforme y a partir de ello devolver una matriz $N \times dim$
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
simula_unif<-function(N, dim, minimo, maximo){
unif<-matrix(nrow = dim, ncol = N);
for(i in 1:N){
unif[,i] <- runif(dim,minimo, maximo)
}
return(unif);
}
\end{lstlisting}
Pero como nos pide que sea una lista hacemos que la variable unif sea una lista (y por tanto accedemos a las componentes con \textbf{[[·]]})
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> simula_unif<-function(N, dim, minimo, maximo){
unif<-list();
for(i in 1:N){
unif[[i]] <- runif(dim,minimo, maximo)
}
return(unif);
}
> lista_uniforme <- simula_unif(N=3,dim=4,-1,1)
> lista_uniforme
[[1]]
[1] 0.0386862 -0.1860388 0.9824784 0.2079370
[[2]]
[1] 0.888472 -0.454218 -0.932526 -0.543044
[[3]]
[1] 0.79459142 0.60399254 -0.15797747 -0.06230832
\end{lstlisting}
Podemos ver si funciona correctamente mediante un histograma:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> lista_unif<-simula_unif(N=1,dim = 500,-1,1)
> hist(lista_unif[[1]], col = "yellow",main = "Distribucion Uniforme - 500 muestras",xlab = "Valor")
\end{lstlisting}
\begin{figure}[h]
\includegraphics[scale=0.7]{Pictures/DistUniforme.png}
\end{figure}
\begin{exercise}
Construir una función $lista = simula\_gaus(N,dim,sigma)$ que calcule una lista de longitud N de vectores de dimension dim conteniendo números aleatorios gaussianos de media 0 y varianzas dadas por el vector \textit{sigma}.
\end{exercise}
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> simula_gaus <- function(N, dim, sigma){
normal<-list();
for(i in 1:N){
normal[[i]] <- rnorm(n =dim, mean=0,sd = sigma[i]);
}
return(normal)
}
> x<-simula_gaus(4,400,c(1,3,5,7))
> plot(x[[4]], col="black", ylab = "Valor", xlab = "Indice", pch=4)
> points(x[[3]], col="red", pch=4)
> points(x[[2]], col="blue", pch=4)
> points(x[[1]], col="green", pch=4)
\end{lstlisting}
Podemos ver el resultado de las últimas ordenes del cuadro de código anterior en la siguiente figura.\\
Se aprecia claramente como los puntos más dispersos corresponden a las que tienen mayor desviación típica (sigma)
\begin{figure}[h]
\includegraphics[scale=0.6]{Pictures/dispNormal.png}
\end{figure}
\begin{exercise}
Suponer N = 50, dim=2, rango = [-50, 50] en cada dimensión. Dibujar una gráfica de la salida de la función correspondiente.
\end{exercise}
Creamos una función para que nos haga todo automáticamente:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
plotUnif<-function(N, minimo, maximo){
x <- c();
y <- c();
puntos <- list();
puntos <- simula_unif(N, 2, minimo, maximo);
for(i in 1:N){
x[i] <- puntos[[i]][[1]];
y[i] <- puntos[[i]][[2]];
}
plot(x, y);
}
\end{lstlisting}
En la siguiente figura aparece una ejecución de la orden \textit{>plotUnif(50, -50, 50)}:
\includegraphics[scale=0.6]{Pictures/uniforme50x-50to50.png}
Observación:\\
La forma de almacenar las coordenadas $x$ e $y$ de nuestra lista de puntos no es muy apropiada para trabajar en R tal y como lo estamos haciendo. Es decir como una lista con la siguiente estructura: $(x_1, y_1) ; (x_2, y_2) ; ... ; (x_n, y_n)$ \\
Una forma de almacenar los puntos que simplifica las implementaciones en R es la siguiente:\\
Lista de puntos = $(x_1, x_2, ..., x_n) ; (y_1, y_2, ..., y_n)$\\
En el siguiente ejercicio vamos a reescribir la función $simula\_gaus()$ para adaptarla a esta estructura y luego vamos a dibujar:
\begin{exercise}
Suponer N = 50, dim=2, sigma = [5, 7] en cada dimensión. Dibujar una gráfica de la salida de la función correspondiente.
\end{exercise}
Función simula\_gaus() \textit{(versión 2)}
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
simula_gaus <- function(N, dim, sigma){
puntos <- list();
for(i in 1:dim){
xi <- c();
xi <- rnorm(N, 0, sigma[i]);
puntos[[i]]<-xi;
}
return(puntos);
}
\end{lstlisting}
La forma en la que utilizamos la función es la misma que usabamos en la primera versión pero la estructura que devuelve es diferente:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> simula_gaus(20, 2, c(5,7))
[[1]]
[1] -2.4491073 -3.2584142 2.3869703 -9.8788259 0.1670119 6.2144173 4.5063578 3.1975652
[9] -2.0464434 1.0344226 -2.0405586 -8.9180882 -1.5210091 -1.4812887 -3.1102648 -2.3895402
[17] -6.4188965 1.5368615 1.7382187 -6.1144230
[[2]]
[1] -6.8042244 0.1074266 -3.0641119 4.0550469 -2.6651593 -1.2383127 1.5766815 -3.0189121
[9] 5.9075899 -12.1843298 0.9067658 -3.4628036 -6.5992591 -8.4734840 -3.9468448 -2.1081100
[17] 11.1544907 3.4082678 0.1045350 -5.2854292
\end{lstlisting}
Vamos a hacer una función para dibujar nubes de puntos en las que la coordenada $X$ sigue una distribución normal y la coordenada $Y$ sigue otra distribución normal diferente:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
plotGaus2D <- function(N, sigma1, sigma2){
puntos <- list();
puntos <- simula_gaus(N, 2, c(sigma1,sigma2))
plot(puntos[[1]], puntos[[2]],col="brown", pch=1, main = "Distribucion Gaussiana en R^2", ylab = "Coordenada Y", xlab = "Coordenada X")
}
\end{lstlisting}
Notamos que esta función solo dibuja en $R^2$ pero ampliarla a $R^n$ es bastante sencillo.//
La gráfica que pide el encunciado puede obtenerse ejecutando: plotGaus2D(50, 5, 7)
\begin{figure}[h]
\includegraphics[scale=0.6]{Pictures/gaussDist.png}
\end{figure}
\begin{exercise}
Construir la función $v = simula\_recta(intervalo)$ que calcula los parametros $ v = (a,b) $ de una recta aleatoria
$y = ax + b$, que corte al cuadrado $[-50,50]\times[-50,50]$\\
(Ayuda: Para calcular la recta simula las coordenadas de dos puntos y usalos para obtener $(a,b)$)
\end{exercise}
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
simula_recta <- function(min, max){
x <- c();
y <- c();
x <- runif(2, min, max);
y <- runif(2, min, max);
a <- (y[2] - y[1]) / (x[2] - x[1]);
b <- -a*x[1] + y[1];
v <- c(a, b);
return(v);
}
\end{lstlisting}
\subsection{Modelo lineal}
\begin{exercise}
Genera una muestra uniforme usando simula\_unif() y etiqueta la muestra usando el signo de la función $f(x,y) = y - ax - b$
de cada punto a una recta simulada con simula\_recta(). Mostrar una gráfica con el resultado junto con la recta usada para ello.
\end{exercise}
En primer lugar vamos a modificar la función simula\_unif() para que saque una lista con dos elementos (coordenadas $x$ y coordenadas $y$).
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> simula_unif <- function(N, dim, minimo, maximo){
puntos <- list();
for(i in 1:dim){
xi <- c();
xi <- runif(N, minimo, maximo);
puntos[[i]] <- xi;
}
return(puntos)
}
\end{lstlisting}
Hecho esto ya podemos hacer la función plotEtiquetas() con más facilidad:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> plotEtiquetas <- function(N, min, max){
v <- simula_recta(min, max);
a <- v[1];
b <- v[2];
puntos <- simula_unif(N, dim=2, min, max);
colores <- c();
forma <- c();
for(i in 1:N){
if(puntos[[2]][[i]] - a*puntos[[1]][[i]] - b > 0){
colores[i] <- "red";
forma[i] <- 1;
}
else{
colores[i] <- "blue";
forma[i] <- 3;
}
}
plot(puntos[[1]], puntos[[2]], col=colores, pch=forma, xlab="Coord X", ylab="Coord Y", main = "Clasificacion Basica");
curve(a*x + b, add=TRUE);
}
\end{lstlisting}
Podemos ejecutar \textbf{plotEtiquetas(100, -10, 10)} con un resultado como este:
\begin{figure}[h]
\includegraphics[scale=0.7]{Pictures/Clasificacion.png}
\end{figure}
Como ahora queremos clasificar nubes de puntos de diferentes formas vamos a crear una función más general a la cual se le va a pasar una lista de puntos en el formato en el que estamos acostumbrados y los parámetros $a$ y $b$ de la recta que usaremos para clasificar.\\
Esto es una solución más general del ejercicio:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
clasificaPuntosRecta <- function(puntos, a, b){
xtipo1 <- c();
ytipo1 <- c();
xtipo2 <- c();
ytipo2 <- c();
N <- length(puntos[[1]]);
for(i in 1:N){
if(puntos[[2]][[i]] - a*puntos[[1]][[i]] - b > 0){
xtipo1 <- c(xtipo1, puntos[[1]][[i]]);
ytipo1 <- c(ytipo1, puntos[[2]][[i]]);
}
else{
xtipo2 <- c(xtipo2, puntos[[1]][[i]]);
ytipo2 <- c(ytipo2, puntos[[2]][[i]]);
}
}
#Limites de los ejes para el plot:
miny = min(ytipo1, ytipo2);
maxy = max(ytipo1, ytipo2);
minx = min(xtipo1, xtipo2);
maxx = max(xtipo1, xtipo2);
plot(xtipo1, ytipo1, col="red", pch=1, xlab="Coord X", ylab="Coord Y", main = "Clasificacion Basica", xlim = c(minx, maxx), ylim = c(miny, maxy) );
points(xtipo2, ytipo2, col="blue", pch=4);
curve(a*x + b, add=TRUE);
return(list(xtipo1, ytipo1, xtipo2, ytipo2));
}
\end{lstlisting}
La función \textbf{clasificaPuntosRecta(Puntos, a, b)} clasifica los puntos que hay en la lista \textit{Puntos} con dos etiquetas en función del signo de su distancia a la recta $y = ax + b$\\
Podemos ver un ejemplo con la recta $y=x$ y otro con una recta aleatoria:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> misPuntos <- simula_unif(50, 2, -50, 50)
> clasificaPuntosRecta(misPuntos, 1, 0)
\end{lstlisting}
\begin{figure}[h]
\includegraphics[scale=0.7]{Pictures/clasificacion2.png}
\end{figure}
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> recta <- simula_recta(-50, 50)
> clasificaPuntosRecta(misPuntos, recta[1], recta[2])
\end{lstlisting}
\begin{figure}
\includegraphics[scale=0.7]{Pictures/clasificacion_recta_aleatoria.png}
\end{figure}
\begin{exercise}
Usar la muestra generada en el apartado anterior y etiquetarla con $+1, -1$ usando el signo de cada una de las siguientes funciones:\\
\begin{itemize}
\item $f_1(x,y) = (x-10)^2 + (y-20)^2 - 400$
\item $f_2(x,y) = 0.5(x+10)^2 +(y- 20)^2 - 400$
\item $f_3(x,y) = 0.5(x-10)^2 -(y + 20)^2 - 400$
\item $f_4(x,y) = y - 20x^2 - 5x+3$
\end{itemize}
\end{exercise}
\subsection{Modelo Circular}
Observemos en primer lugar que $f_1(x,y)=0$ representa una circunferencia, luego clasificar los puntos en función del signo de $f_1(x,y)$ es clasificar puntos dependiendo de que estén dentro o fuera de la circunferencia $\{(x,y) \in \mathbb{R}^2 : (x-10)^2 + (y-20)^2 - 400 = 0\}$.\\
Por eso vamos además a crear una subfuncion en R llamada \textbf{draw.circle} para que se vea más claro como está funcionando la clasificación.\\
El código en R de la clasificación atendiendo al signo de $f_1$ es el siguiente:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
clasificaPuntosFuncion1 <- function(puntos){
xtipo1 <- c();
ytipo1 <- c();
xtipo2 <- c();
ytipo2 <- c();
N <- length(puntos[[1]]);
### Editar Funcion para cambiar la forma de clasificar
mifuncion <- function(x,y){
return((x-10)^2 + (y-20)^2 - 400);
}
### Funcion para dibujar circulos
draw.circle <- function(x,y, radius){
theta <- seq(0, 2 * pi, length = 200);
# draw the circle
lines(x = radius * cos(theta) + x, y = radius * sin(theta) + y);
}
for(i in 1:N){
if(mifuncion(puntos[[1]][[i]],puntos[[2]][[i]]) > 0){
xtipo1 <- c(xtipo1, puntos[[1]][[i]]);
ytipo1 <- c(ytipo1, puntos[[2]][[i]]);
}
else{
xtipo2 <- c(xtipo2, puntos[[1]][[i]]);
ytipo2 <- c(ytipo2, puntos[[2]][[i]]);
}
}
#Limites de los ejes para el plot:
miny = min(ytipo1, ytipo2);
maxy = max(ytipo1, ytipo2);
minx = min(xtipo1, xtipo2);
maxx = max(xtipo1, xtipo2);
plot(xtipo1, ytipo1, col="red", pch=1, xlab="Coord X", ylab="Coord Y",
main = "Clasificacion por circulos", xlim = c(minx, maxx), ylim = c(miny, maxy) );
points(xtipo2, ytipo2, col="blue", pch=4);
draw.circle(10, 20, sqrt(400));
return(list(xtipo1, ytipo1, xtipo2, ytipo2));
}
\end{lstlisting}
Para aplicar esta clasificación a los datos que teníamos en el ejercicio anterior ejecutamos:\\
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> clasificaPuntosFuncion1(misPuntos)
\end{lstlisting}
y obtenemos el siguiente gráfico:
\includegraphics[scale=0.7]{Pictures/clasifica_circulos.png}
\subsection{Modelo Elíptico}
La clasificación en función de $f_2$ es bastante parecida a la primera, pero en este caso la figura es una elipse.\\
Podemos hacer una función draw.elipse(x,y, a,b) donde $(x,y)$ es el centro y $(a,b)$ son los semiejes $X$ e $Y$ de la elipse.
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
> clasificaPuntosFuncion2 <- function(puntos){
xtipo1 <- c();
ytipo1 <- c();
xtipo2 <- c();
ytipo2 <- c();
N <- length(puntos[[1]]);
### Editar Funcion para cambiar la forma de clasificar
mifuncion <- function(x,y){
return(0.5*(x+10)^2 + (y-20)^2 - 400);
}
### Funcion para dibujar elipses
draw.elipse <- function(x=0,y=0,a=1,b=1){
theta <- seq(0, 2 * pi, length = 200);
# draw the circle
lines(x = a*cos(theta) + x, y = b*sin(theta) + y);
}
for(i in 1:N){
if(mifuncion(puntos[[1]][[i]],puntos[[2]][[i]]) > 0){
xtipo1 <- c(xtipo1, puntos[[1]][[i]]);
ytipo1 <- c(ytipo1, puntos[[2]][[i]]);
}
else{
xtipo2 <- c(xtipo2, puntos[[1]][[i]]);
ytipo2 <- c(ytipo2, puntos[[2]][[i]]);
}
}
#Limites de los ejes para el plot:
miny = min(ytipo1, ytipo2);
maxy = max(ytipo1, ytipo2);
minx = min(xtipo1, xtipo2);
maxx = max(xtipo1, xtipo2);
plot(xtipo1, ytipo1, col="red", pch=1, xlab="Coord X", ylab="Coord Y",
main = "Clasificacion por elipses", xlim = c(minx, maxx), ylim = c(miny, maxy) );
points(xtipo2, ytipo2, col="blue", pch=4);
draw.elipse(-10, 20, sqrt(400)/sqrt(0.5), sqrt(400));
return(list(xtipo1, ytipo1, xtipo2, ytipo2));
}
\end{lstlisting}
\begin{figure}[h]
\includegraphics[scale=0.7]{Pictures/clasificacion_elipses.png}
\end{figure}
\subsection{Modelo Hiperbólico}
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
clasificaPuntosFuncion3 <- function(puntos){
xtipo1 <- c();
ytipo1 <- c();
xtipo2 <- c();
ytipo2 <- c();
N <- length(puntos[[1]]);
### Editar Funcion para cambiar la forma de clasificar
mifuncion <- function(x,y){
return(0.5*(x+10)^2 - (y+20)^2 - 400);
}
### Funcion para dibujar hiperbola
draw.hiperbola <- function(x=0,y=0,a=1,b=1){
theta <- seq(0, 2 * pi, length = 200);
# draw
lines(x = a*(1/cos(theta)) + x, y = b*tan(theta) + y);
}
for(i in 1:N){
if(mifuncion(puntos[[1]][[i]],puntos[[2]][[i]]) > 0){
xtipo1 <- c(xtipo1, puntos[[1]][[i]]);
ytipo1 <- c(ytipo1, puntos[[2]][[i]]);
}
else{
xtipo2 <- c(xtipo2, puntos[[1]][[i]]);
ytipo2 <- c(ytipo2, puntos[[2]][[i]]);
}
}
#Limites de los ejes para el plot:
miny = min(ytipo1, ytipo2);
maxy = max(ytipo1, ytipo2);
minx = min(xtipo1, xtipo2);
maxx = max(xtipo1, xtipo2);
plot(xtipo1, ytipo1, col="red", pch=1, xlab="Coord X", ylab="Coord Y",
main = "Clasificacion por hiperbolas", xlim = c(minx, maxx), ylim = c(miny, maxy) );
points(xtipo2, ytipo2, col="blue", pch=4);
draw.hiperbola(-10, -20, sqrt(400)/sqrt(0.5), sqrt(400));
return(list(xtipo1, ytipo1, xtipo2, ytipo2));
}
\end{lstlisting}
\includegraphics[scale=0.7]{Pictures/clasificacion_hiperbolas.png}
\subsection{Modelo Parabólico}
Por último vamos a hacer una clasificación mediante una parábola:
\begin{lstlisting}[
language=R,
breaklines=true,
showspaces=false,
basicstyle=\ttfamily,
commentstyle=\color{gray}
]
clasificaPuntosFuncion4 <- function(puntos){
xtipo1 <- c();
ytipo1 <- c();
xtipo2 <- c();
ytipo2 <- c();
N <- length(puntos[[1]]);
### Editar Funcion para cambiar la forma de clasificar
mifuncion <- function(x,y){
return(y - 20*x^2 - 5*x+3);
}
for(i in 1:N){
if(mifuncion(puntos[[1]][[i]],puntos[[2]][[i]]) > 0){
xtipo1 <- c(xtipo1, puntos[[1]][[i]]);
ytipo1 <- c(ytipo1, puntos[[2]][[i]]);
}
else{
xtipo2 <- c(xtipo2, puntos[[1]][[i]]);
ytipo2 <- c(ytipo2, puntos[[2]][[i]]);
}
}
#Limites de los ejes para el plot:
miny = min(ytipo1, ytipo2);
maxy = max(ytipo1, ytipo2);
minx = min(xtipo1, xtipo2);
maxx = max(xtipo1, xtipo2);
plot(xtipo1, ytipo1, col="red", pch=1, xlab="Coord X", ylab="Coord Y",
main = "Clasificacion por Parabolas", xlim = c(minx, maxx), ylim = c(miny, maxy) );
points(xtipo2, ytipo2, col="blue", pch=4);
curve(expr = (y = 20*x^2 + 5*x -3),add = TRUE);
return(list(xtipo1, ytipo1, xtipo2, ytipo2));
}