In [3]:
# Linear SVM
import numpy as np
from sklearn import datasets
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC
iris = datasets.load_iris()
X = iris['data'][:,(2,3)]
y = (iris['target'] == 2).astype(np.float64)
svm_clf = Pipeline([
('scaler', StandardScaler()),
('linear_svc', LinearSVC(C=1,loss='hinge')),
])
svm_clf.fit(X, y)
svm_clf.predict([[5.5, 1.7]])
Out[3]:
In [5]:
# Nonlinear SVM
from sklearn.datasets import make_moons
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.svm import LinearSVC
polynomial_svm_clf = Pipeline([
('poly_features', PolynomialFeatures(degree=3)),
('scaler', StandardScaler()),
('linear_svc', LinearSVC(C=10,loss='hinge')),
])
polynomial_svm_clf.fit(X,y)
Out[5]:
In [7]:
# Polynomial Kernel
from sklearn.svm import SVC
poly_kernel_clf = Pipeline([
('scaler', StandardScaler()),
('svc', SVC(kernel='poly', degree=3,coef0=1, C=5)),
])
poly_kernel_clf.fit(X,y)
Out[7]:
In [9]:
rbf_kernel_clf = Pipeline([
('scaler', StandardScaler()),
('svc', SVC(kernel='rbf', gamma=5, C=0.001)),
])
rbf_kernel_clf.fit(X,y)
Out[9]:
In [15]:
# SVM Regression
from sklearn.svm import LinearSVR
svm_reg = LinearSVR(epsilon=1.5)
svm_reg.fit(X,y)
from sklearn.svm import SVR
svm_reg = SVR(kernel='poly', gamma ='scale', degree=2, C=100, epsilon=0.1)
svm_reg.fit(X,y)
Out[15]:
In [ ]: