support vector machine - gráficas, estadística y minería de datos
TRANSCRIPT
![Page 1: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/1.jpg)
Support Vector MachineGraficas, estadıstica y minerıa de datos con Python
Miguel Cardenas Montes
Centro de Investigaciones Energeticas Medioambientales y Tecnologicas,Madrid, Spain
2-6 de Noviembre de 2015
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 1 / 31
![Page 2: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/2.jpg)
Tabla de Contenidos
1 Objetivos
2 Support Vector Machine
3 Ejemplo Python
4 Regresion con SVM
5 Ejemplo R
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 2 / 31
![Page 3: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/3.jpg)
Objetivos
Conocer las diferencias entre los metodos de aprendizaje supervisadoy no supervisados.
Conocer metodos SVM lineales, polinomicos y radiales
Aspectos Tecnicos
scikit-learn API
Support Vector Machine
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 3 / 31
![Page 4: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/4.jpg)
Support Vector Machine
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 4 / 31
![Page 5: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/5.jpg)
SVM I
Support Vector Machine (SVM)es un metodo supervisado declasificacion, aunque tambienpuede utilizarse en regresion.
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 5 / 31
![Page 6: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/6.jpg)
SVM II
H1 no separa las clases.
H2 y H3 sı separan las clases.
H3 maximiza el margen deseparacion de las clases.
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 6 / 31
![Page 7: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/7.jpg)
SVM III
Objetivo maximizar la anchura del margen que separa ambas clasesde datos.
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 7 / 31
![Page 8: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/8.jpg)
SVM IV
Existen conjutos de datos no linealmente separables.
SVM tambien puede tratarlos.
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 8 / 31
![Page 9: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/9.jpg)
Elementos de SVM I
Un Support VectorMachine (SVM) ejecutauna clasificacion.
Para ello tiene queencontrar el hiperplanoque maximiza el margenentre las dos clases.
Los vectores (casos) quedefinen el hiperplano sedenominan support
vectors.
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 9 / 31
![Page 10: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/10.jpg)
SVM
SVM usa un mapeo no lineal transformando los datos originales enotros de dimensionalidad superior.
En estas nuevas dimensionalidades, SVM busca el hiperplano optimoque separa las clases.
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 10 / 31
![Page 11: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/11.jpg)
Ejemplo: Python
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 11 / 31
![Page 12: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/12.jpg)
Ejemplo I
SVM linealmente separable.
import numpy as np
import pylab as pl
from sklearn import svm
# first training set
X = np.r_[’1,2,0’, \
[500, 1000, 2000, 1000, 4000, 4000, 8000], \
[500, 1000, 2000, 4000, 1000, 4000, 2000] ]
Y = [0, 0, 0, 0, 0, \
1, 1]
pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired)
pl.xlabel(’Label A’)
pl.ylabel(’Label B’)
pl.axis(’tight’)
pl.ylim( (0, 8110) )
pl.xlim( (0, 8110) )
pl.show()
0 1000 2000 3000 4000 5000 6000 7000 8000Label A
0
1000
2000
3000
4000
5000
6000
7000
8000
Labe
l B
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 12 / 31
![Page 13: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/13.jpg)
Ejemplo II
SVM linealmente separable.
# fit the model and get the separating hyperplane
clf = svm.SVC(kernel=’linear’, C=2.0)
clf.fit(X, Y)
# get the separating hyperplane
w = clf.coef_[0]
a = -w[0] / w[1]
xx = np.linspace(0, 20001)
yy = a * xx - (clf.intercept_[0]) / w[1]
# plot the parallels to the separating hyperplane that pass through the
# support vectors
b = clf.support_vectors_[0]
yy_down = a * xx + (b[1] - a * b[0])
b = clf.support_vectors_[-1]
yy_up = a * xx + (b[1] - a * b[0])
# plot the line, the points, and the nearest vectors to the plane
pl.plot(xx, yy, ’k-’)
pl.plot(xx, yy_down, ’k--’)
pl.plot(xx, yy_up, ’k--’)
pl.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80, facecolors=’none’)
pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired)
0 1000 2000 3000 4000 5000 6000 7000 8000Label A
0
1000
2000
3000
4000
5000
6000
7000
8000
Labe
l B
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 13 / 31
![Page 14: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/14.jpg)
Ejemplo III
Al anadir un nuevo punto se reoganiza el esquema.
Se mantiene que los puntos son linealmente separables (3500, 3500,etiqueta 1).
# Modified training set
X = np.r_[’1,2,0’, \
[500, 1000, 2000, 1000, 4000, 4000, 8000, 3500], \
[500, 1000, 2000, 4000, 1000, 4000, 2000, 3500] ]
Y = [0, 0, 0, 0, 0, \
1, 1, 1]
0 1000 2000 3000 4000 5000 6000 7000 8000Label A
0
1000
2000
3000
4000
5000
6000
7000
8000
Labe
l B
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 14 / 31
![Page 15: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/15.jpg)
Ejemplo IV
0 1000 2000 3000 4000 5000 6000 7000 8000Label A
0
1000
2000
3000
4000
5000
6000
7000
8000
Labe
l B
0 1000 2000 3000 4000 5000 6000 7000 8000Label A
0
1000
2000
3000
4000
5000
6000
7000
8000
Labe
l B
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 15 / 31
![Page 16: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/16.jpg)
Ejemplo V
Prediccion de nuevos puntos.
from sklearn import svm
X = [[0, 0], [0.4, 0.5], [1, 1], [2, 2]]
y = [0, 0, 1, 1]
clf = svm.SVC()
clf.fit(X, y)
print clf.predict([[0.5, 1.]])
print clf.predict([[2., 2.]])
print clf.predict([[2., 3.]])
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 16 / 31
![Page 17: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/17.jpg)
Ejemplo VI
Datos no linealmente separable.Se cambia un punto de etiqueta (2000, 2000, etiqueta 1).El resultado grafico es anomalo si se trata de mantener unaseparabilidad lineal.
# Modified training set
X = np.r_[’1,2,0’, \
[500, 1000, 2000, 1000, 4000, 4000, 8000], \
[500, 1000, 2000, 4000, 1000, 4000, 2000] ]
Y = [0, 0, 1, 0, 0, \
1, 1]
0 1000 2000 3000 4000 5000 6000 7000 8000 90000
500
1000
1500
2000
2500
3000
3500
4000
4500
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 17 / 31
![Page 18: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/18.jpg)
Ejemplo VII
Sin embargo, con ecuacion no lineal (polinomica) se podrıan separarlos datos.
clf = svm.SVC(kernel=’poly’, gamma=4)
clf.fit(X, Y)
pl.figure()
pl.clf()
pl.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=pl.cm.Paired)
pl.axis(’tight’)
x_min = X[:, 0].min()
x_max = X[:, 0].max()
y_min = X[:, 1].min()
y_max = X[:, 1].max()
XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()])
# Put the result into a color plot
Z = Z.reshape(XX.shape)
pl.pcolormesh(XX, YY, Z > 0, cmap=pl.cm.Paired)
pl.contour(XX, YY, Z, colors=[’k’, ’k’, ’k’], linestyles=[’--’, ’-’, ’--’], levels=[-.5, 0, .5])
pl.show()
1000 2000 3000 4000 5000 6000 7000 8000500
1000
1500
2000
2500
3000
3500
4000
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 18 / 31
![Page 19: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/19.jpg)
Tipos de kernel en SVM
Lineal
Polinomico
rbf, radial basis function
sigmoide, tangente hiperbolica
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 19 / 31
![Page 20: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/20.jpg)
Parametros de SVM
C Penalizacion del termino de error. Este parametro, comun entodos los kernels, es un compromiso entre las clasificacioneserroneas de las tuplas de entrenamiento contra la simplicidadde la superficie de decision. Un valor bajo de ”c” hace lasuperficie de decision suave, mientras que un valor alto tratade clasificar absolutamente todas las tuplas de entrenamientocorrectamente.
kernel Tipo de kernel usado en el algoritmo.
degree Grado de la funcion kernel cuando de tipo polinomico.
gamma Coeficiente del kernel cuando es de tipo rbf.
coef0 Parametro del kernel cuando es de tipo sigmoide.
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 20 / 31
![Page 21: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/21.jpg)
Multiclases
Para datos no linealmente separable y masde dos clases es posible hacer mapas(mediante prediccion) de las zonas deinfluencia de cada clase.
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 21 / 31
![Page 22: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/22.jpg)
Complejidad Computacional de SVM
SVM incrementa los requerimientos computacionales con rapidez conel numero de tuplas de entrenamiento.
El nucleo de la librerıa escala como O(nfeatures × n2samples) o como
O(nfeatures × n3samples) dependiendo de la eficiencia del uso y de lasparticularidades de los datos.
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 22 / 31
![Page 23: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/23.jpg)
Regresion con SVM
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 23 / 31
![Page 24: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/24.jpg)
Regresion con SVM I
El metodo de SVM puede ser extendida a la resolucion de problemasde regresion.
En SVR la etiqueta categorica tiene que ser cambiada por valorescontinuos.
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 24 / 31
![Page 25: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/25.jpg)
Regresion con SVM II
import numpy as np
X = np.sort(5 * np.random.rand(40, 1), axis=0)
y = np.sin(X).ravel()
# Add noise to targets
y[::4] += 3 * (0.5 - np.random.rand(10))
# Fit regression model
from sklearn.svm import SVR
svr_rbf = SVR(kernel=’rbf’, C=1e3, gamma=0.1)
svr_lin = SVR(kernel=’linear’, C=1e3)
svr_poly = SVR(kernel=’poly’, C=1e3, degree=2)
y_rbf = svr_rbf.fit(X, y).predict(X)
y_lin = svr_lin.fit(X, y).predict(X)
y_poly = svr_poly.fit(X, y).predict(X)
# look at the results
import pylab as pl
pl.scatter(X, y, c=’k’, label=’data’)
pl.hold(’on’)
pl.plot(X, y_rbf, c=’g’, label=’RBF model’)
pl.plot(X, y_lin, c=’r’, label=’Linear model’)
pl.plot(X, y_poly, c=’b’, label=’Polynomial model’)
pl.legend()
pl.show()
−1 0 1 2 3 4 5 6data
−2.0
−1.5
−1.0
−0.5
0.0
0.5
1.0
1.5
2.0
targ
et
Support Vector Regression
Linear modelPolynomial modeldata
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 25 / 31
![Page 26: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/26.jpg)
Ejemplo: R
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 26 / 31
![Page 27: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/27.jpg)
Ejemplo (SVM Lineal) I
Ejemplo en R de SVM linealmente separable.
# numero de valores
nn<-100
dim<-2
# valores eje x,y para el primer conjunto
data1<-matrix(c(rnorm(nn,mean=2,sd=0.7),rnorm(nn,mean=1,sd=0.7)),nn,dim)
data1
# valores eje x,y para el segundo conjunto
data2<-matrix(c(rnorm(nn,mean=5,sd=0.6),rnorm(nn,mean=4,sd=0.4)),nn,dim)
data2
# construir tabla datos
datos<-rbind(data1,data2)
datos
# generar las etiquetas
y <- matrix(c(rep(1,nn),rep(-1,nn)))
# mostrar los datos
plot(datos,col=ifelse(y>0,1,2))
1 2 3 4 5 6
01
23
45
datos[,1]
dato
s[,2
]
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 27 / 31
![Page 28: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/28.jpg)
Ejemplo (SVM Lineal) II
# leer el paquete kernlab
library(kernlab)
# entrenar el modelo SVM
svp <- ksvm(datos,y,type="C-svc",kernel=’vanilladot’,C=100,scaled=c())
# Sumario de datos
svp
# Atributos disponibles
attributes(svp)
# algunos ejemplos de atributos disponibles
alpha(svp)
alphaindex(svp)
b(svp)
# Usar el modelo para pintar el clasificador
plot(svp,data=datos)
−4
−2
0
2
4
6
0 1 2 3 4 5
1
2
3
4
5
6
SVM classification plot
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 28 / 31
![Page 29: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/29.jpg)
Ejemplo (SVM No Lineal: RBF) III
# numero de valores
nn<-100
dim<-2
# valores eje x,y para el primer conjunto
data1<-matrix(c(rnorm(nn,mean=2,sd=0.7),rnorm(nn,mean=1,sd=0.7)),nn,dim)
# valores eje x,y para el segundo conjunto
data2<-matrix(c(rnorm(nn,mean=5,sd=0.6),rnorm(nn,mean=4,sd=0.4)),nn,dim)
# valores eje x,y para el terce conjunto
data3<-matrix(c(rnorm(nn,mean=-2,sd=0.3),rnorm(nn,mean=-2,sd=0.3)),nn,dim)
# construir tabla datos
datos<-rbind(data1,data2,data3)
# generar las etiquetas
y <- matrix(c(rep(1,nn),rep(-1,nn), rep(-1,nn)))
# mostrar los datos
plot(datos,col=ifelse(y>0,1,2))
# leer el paquete kernlab
library(kernlab)
# entrenar el modelo SVM
svp <- ksvm(datos,y,type="C-svc",kernel=’rbf’,kpar=list(sigma=1),C=1 )
# Usar el modelo para pintar el clasificador
plot(svp,data=datos)
−1.5
−1.0
−0.5
0.0
0.5
1.0
1.5
2.0
−2 −1 0 1 2 3 4 5
−2
0
2
4
6
SVM classification plot
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 29 / 31
![Page 30: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/30.jpg)
Ejemplo (SVM Lineal) IV
Ejemplo de SVM Lineal con margenes y vectores de soporte:
nn<-40
dim<-2
data1<-matrix(c(rnorm(nn,mean=1,sd=0.7),rnorm(nn,mean=2,sd=0.7)),nn,dim)
data2<-matrix(c(rnorm(nn,mean=4,sd=0.6),rnorm(nn,mean=5,sd=0.4)),nn,dim)
datos<-rbind(data1,data2)
# generar las etiquetas
y <- matrix(c(rep(1,nn),rep(-1,nn)))
# mostrar los datos
#plot(datos,col=ifelse(y>0,1,2), type=’n’)
# leer el paquete kernlab
library(kernlab)
# entrenar el modelo SVM
svp <- ksvm(datos,y,type="C-svc",kernel=’vanilladot’,C=100,scaled=c())
ymat<-ymatrix(svp)
plot(c(min(datos[,1]), max(datos[,1])),c(min(datos[,2]), max(datos[,2])),type=’n’,xlab=’x1’,ylab=’x2’)
points(datos[-SVindex(svp),1], datos[-SVindex(svp),2], pch = ifelse(ymat[-SVindex(svp)] < 0, 2, 1))
points(datos[SVindex(svp),1], datos[SVindex(svp),2], pch = ifelse(ymat[SVindex(svp)] < 0, 17, 16))
# Extraer w y b del modelo
w <- colSums(coef(svp)[[1]] * datos[SVindex(svp),])
b <- b(svp)
# Dibujar lineas
abline(b/w[2],-w[1]/w[2])
abline((b+1)/w[2],-w[1]/w[2],lty=2)
abline((b-1)/w[2],-w[1]/w[2],lty=2)
0 1 2 3 4 5
12
34
5
x1
x2
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 30 / 31
![Page 31: Support Vector Machine - Gráficas, estadística y minería de datos](https://reader034.vdocuments.site/reader034/viewer/2022052607/589af6601a28ab28468bce0b/html5/thumbnails/31.jpg)
Gracias
Gracias
¿Preguntas?
¿Mas preguntas?
M. Cardenas (CIEMAT) SVM 2-6 de Noviembre de 2015 31 / 31