-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsvm.py
30 lines (27 loc) · 1020 Bytes
/
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
from sklearn import svm
import pandas as pd
import os
# Load the iris dataset
assert os.getcwd().endswith('svm') # NOTE: Need to run file from the svm directory
df = pd.read_csv('../data/iris.csv')
X = df[['sepal length', 'sepal width']]
Y = df['class']
Y = Y.map({'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2})
clf = svm.SVC()
clf.fit(X, Y)
# Pretty plot
import matplotlib.pyplot as plt
import numpy as np
plt.scatter(X['sepal length'], X['sepal width'], c=Y, cmap=plt.cm.coolwarm)
plt.xlabel('Sepal Length')
plt.ylabel('Sepal Width')
plt.title("SVM Classifier on Iris Dataset")
# Plot the decision boundary
x_min, x_max = X['sepal length'].min() - 1, X['sepal length'].max() + 1
y_min, y_max = X['sepal width'].min() - 1, X['sepal width'].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01), np.arange(y_min, y_max, 0.01))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.8)
plt.savefig('plots/svm.pdf')
plt.show()