-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhands_on_chapter_5_svm.py
73 lines (56 loc) · 1.89 KB
/
hands_on_chapter_5_svm.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 7 19:19:04 2018
@author: Jake
"""
'''
Chapter 5: Support Vector Machines
Hands-On Machine Learning with Scikit-Learn & TensorFlow
'''
#############################
# Linear SVM Classification #
#############################
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)
print('-- Linear SVM Classification --')
print('Predicting Iris-Virginica [0: Negative, 1: Positive]:')
dimensions = [5.5, 1.7]
print('Dimensions: ' + str(dimensions))
print(svm_clf.predict([dimensions]))
################################
# Nonlinear SVM Classification #
################################
from sklearn.datasets import make_moons
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.svm import SVC
moons = make_moons()
X = moons[0]
y = moons[1]
polynomial_svm_clf = Pipeline([
('poly_features', PolynomialFeatures(degree = 3)),
('scaler', StandardScaler()),
('svm_clf', LinearSVC(C = 10, loss = 'hinge'))
])
polynomial_svm_clf.fit(X, y)
#####################
# Polynomial Kernel #
#####################
poly_kernel_svm_clf = Pipeline([
('scaler', StandardScaler()),
('svm_clf', SVC(kernel = 'poly', degree = 3,
coef0 = 1, C = 5))
])
poly_kernel_svm_clf.fit(X, y)