Support Vector Machines (SVM)

  • fjklds
  • jlfioe

In [10]:
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC

In [22]:
X = np.random.random(50)
Y = np.random.random(50)

X1 = np.where((Y > 0.6) & (X > 0.6))
X2 = np.where((Y <= 0.4) & (X < 0.6))

plt.scatter(X[X1],Y[X1], c='red')
plt.scatter(X[X2],Y[X2], c='blue')
plt.show()



In [24]:
svm_clf = Pipeline((
 ("scaler", StandardScaler()),
 ("linear_svc", LinearSVC(C=1, loss="hinge")),
 ))
svm_clf.fit(X1, y)


Out[24]:
array([0.78998508, 0.91537352, 0.87701355, 0.61896387, 0.71136212,
       0.62622068, 0.82039243, 0.76644889, 0.62941531, 0.9419023 ,
       0.80138809])

In [11]:
iris = datasets.load_iris()
X = iris["data"][:, (2, 3)] # petal length, petal width
y = (iris["target"] == 2).astype(np.float64) # Iris-Virginica

In [26]:
X


Out[26]:
array([7.59484309e-02, 8.20179552e-01, 7.65509658e-01, 9.25927375e-01,
       1.03904152e-01, 6.05989261e-02, 8.62859376e-01, 4.07529395e-01,
       6.94486344e-01, 6.58011407e-01, 1.92194882e-01, 9.02575682e-01,
       1.27332732e-01, 2.91483063e-01, 5.43045725e-01, 5.40020640e-01,
       9.24484584e-01, 9.08849318e-01, 1.28903363e-01, 7.08017108e-01,
       4.04431209e-01, 1.83045090e-01, 5.32129835e-01, 3.29960653e-02,
       5.06782072e-01, 2.76549869e-01, 7.64320248e-01, 4.01145864e-01,
       5.86075874e-01, 9.05546621e-01, 8.14144568e-03, 2.25837014e-01,
       2.28096504e-01, 7.47166592e-01, 2.93685799e-01, 7.72893887e-01,
       1.12589795e-01, 1.90655391e-01, 7.01387455e-01, 1.87649933e-01,
       5.25142363e-01, 6.56190262e-01, 4.96248390e-01, 4.35633451e-01,
       8.31857595e-01, 1.21277990e-04, 5.64299456e-01, 1.06728281e-01,
       8.05003509e-01, 7.61453982e-01])

In [8]:
svm_clf = Pipeline((
 ("scaler", StandardScaler()),
 ("linear_svc", LinearSVC(C=1, loss="hinge")),
 ))
svm_clf.fit(X, y)


Out[8]:
Pipeline(memory=None,
     steps=[('scaler', StandardScaler(copy=True, with_mean=True, with_std=True)), ('linear_svc', LinearSVC(C=1, class_weight=None, dual=True, fit_intercept=True,
     intercept_scaling=1, loss='hinge', max_iter=1000, multi_class='ovr',
     penalty='l2', random_state=None, tol=0.0001, verbose=0))])

In [9]:
svm_clf.predict([[5.5, 1.7]])


Out[9]:
array([1.])

In [ ]: