13 - Support Vector Machine Code Demo
1 R implementation
1.1 Linear kernel
Code
svm_fit <- e1071::svm(y ~ ., data = data.frame(x, y), type = 'C-classification',
kernel = 'linear', scale = FALSE, cost = 10000)
Code
svm_fit2 <- kernlab::ksvm(x, y, type = "C-svc", kernel = 'vanilladot', C = 10000)
Setting default kernel parameters
1.2 Radial basis (Gaussian) kernel
Code
load("../data/ESL.mixture.rda", verbose = TRUE)
Loading objects:
ESL.mixture
Code
x <- ESL.mixture$x
y <- ESL.mixture$y
dat <- data.frame(y = factor(y), x)
fit <- svm(y ~ ., data = dat, scale = FALSE, kernel = "radial", cost = 5)
Code
px1 <- ESL.mixture$px1
px2 <- ESL.mixture$px2
xgrid <- expand.grid(X1 = px1, X2 = px2)
func <- predict(fit, xgrid, decision.values = TRUE)
func <- attributes(func)$decision
2 Python implementation
Code
import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC
2.1 Linear kernel
Code
1)
np.random.seed(= 6
n = 2
p = np.random.normal(size=(n, p))
xneg = np.random.normal(loc=3, size=(n, p))
xpos = np.vstack((xpos, xneg))
x = np.array([1] * n + [-1] * n) y
Code
= SVC(kernel="linear", C=10000, probability=True)
svm_fit svm_fit.fit(x, y)
SVC(C=10000, kernel='linear', probability=True)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
SVC(C=10000, kernel='linear', probability=True)
2.2 Radial basis (Gaussian) kernel
Code
import rdata
= rdata.read_rda('../data/ESL.mixture.rda') mixture_example
/Users/chenghanyu/.virtualenvs/r-reticulate/lib/python3.12/site-packages/rdata/conversion/_conversion.py:856: UserWarning: Missing constructor for R class "matrix". The underlying R object is returned instead.
warnings.warn(
Code
= mixture_example['ESL.mixture']['x']
x = mixture_example['ESL.mixture']['y'] y
Code
= SVC(kernel = 'rbf', C = 5, probability = True)
svm_rbf svm_rbf.fit(x, y)
SVC(C=5, probability=True)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
SVC(C=5, probability=True)
Code
= mixture_example['ESL.mixture']['px1']
px1 = mixture_example['ESL.mixture']['px2']
px2 = np.meshgrid(px1, px2)
ppx1, ppx2 = np.c_[ppx1.ravel(), ppx2.ravel()]
x_grid = svm_rbf.decision_function(x_grid).reshape(ppx1.shape)
decision_function = svm_rbf.predict_proba(x_grid)[:, 1].reshape(ppx1.shape) probability
Code
plt.figure()=[0], colors="black", linewidths=2)
plt.contour(px1, px2, decision_function, levels0], x[:, 1], c=y, cmap="bwr", s=50, edgecolor="k")
plt.scatter(x[:, 0], x_grid[:, 1],
plt.scatter(x_grid[:, =np.where(probability.ravel() >= 0.5, "red", "blue"), s=10, alpha=0.1)
c"SVM with RBF Kernel")
plt.title("X1")
plt.xlabel("X2")
plt.ylabel( plt.show()