You are on page 1of 2

SVM

August 25, 2021

1 Support Vector Machine (SVM)


SVM là một thuật toán classify được sử dụng rất phổ biến.
• Lý thuyết:
Khoảng cách từ một điểm (vector) có toạ độ X0 tới siêu mặt phẳng (hyperplane) có phương trình
wTx + b=0 được xác định bởi: Bài toán tối ưu trong SVM là bài toán tìm Boundary (w,b) sao
khoảng cách gần nhất từ một điểm trong dữ liệu tới boundary đó là nhỏ nhất: min(margin). Minh
họa như hình dưới. Hypothesis: yn = sign(wTx + b) => yn=[1;-1]
Optimizer: Vì biến đổi toán học của SVM khá phức tạp và có nhiều thư viện hỗ trợ làm việc đó
nên mình không biểu diễn ở đây. * Khi nào nên sử dụng SVM/Logistic regression
Gọi m là số lượng examples, n là số lượng feature của mỗi examples.
Nếu n lớn hơn m: sử dụng logistic regression hoặc SVM with linear kernel
Nếu n nhỏ, m trung bình: sử dụng SVM with Gaussian kernel
Nếu n nhỏ, m lớn: tạo thêm nhiều feature để sử dụng logistic regression hoặc SVM with linear
kernel
Neural network có thể làm tốt ở các trường hợp, nhưng chi phí tính toán sẽ lớn hơn nên phù hợp
với những bài phức tạp hơn.

[1]: from sklearn.svm import SVC


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.metrics import accuracy_score

[2]: data = pd.read_csv('Iris.csv')


data.head()

[2]: Id SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm Species


0 1 5.1 3.5 1.4 0.2 Iris-setosa
1 2 4.9 3.0 1.4 0.2 Iris-setosa
2 3 4.7 3.2 1.3 0.2 Iris-setosa

1
3 4 4.6 3.1 1.5 0.2 Iris-setosa
4 5 5.0 3.6 1.4 0.2 Iris-setosa

[4]: # Split data


X = data.iloc[:, 1:-1]
y = data.iloc[:, -1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,␣
,→random_state=0)

[5]: # Define & train model


svclassifier = SVC(kernel='rbf') # 'rbf' is gaussian kernel
svclassifier.fit(X_train, y_train)

[5]: SVC()

[6]: # Evaluate model f1 score


y_pred = svclassifier.predict(X_test)
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
print(accuracy_score(y_test, y_pred))

[[11 0 0]
[ 0 13 0]
[ 0 0 6]]
precision recall f1-score support

Iris-setosa 1.00 1.00 1.00 11


Iris-versicolor 1.00 1.00 1.00 13
Iris-virginica 1.00 1.00 1.00 6

accuracy 1.00 30
macro avg 1.00 1.00 1.00 30
weighted avg 1.00 1.00 1.00 30

1.0

[ ]:

You might also like