Rで学ぶSupport Vector Machines
Kailash Awati
Instructor
ggplot() を使って訓練データをプロットする。# Visualize training data, distinguish classes using color
p <- ggplot(data = trainset, aes(x = x1, y = x2, color = y)) +
geom_point() +
scale_color_manual(values = c("red", "blue"))
# Render plot
p
svm_model の index を使ってサポートベクターを特定する。# Identify support vectors
df_sv <- trainset[svm_model$index, ]
# Mark out support vectors in plot
p <- p + geom_point(data = df_sv,
aes(x = x1, y = x2),
color = "purple",
size = 4, alpha = 0.5)
# Display plot
p

境界の傾きと切片を求める:
svm_model の coefs と SV から重みベクトル w を構築する。# Build weight vector
w <- t(svm_model$coefs) %*% svm_model$SV
-w[1] / w[2]# Calculate slope and save it to a variable
slope_1 <- -w[1] / w[2]
svm_model$rho / w[2]# Calculate intercept and save it to a variable
intercept_1 <- svm_model$rho / w[2]
geom_abline() を使って決定境界をプロットに追加する。# Plot decision boundary based on calculated slope and intercept
p <- p + geom_abline(slope = slope_1,
intercept = intercept_1)
1 / w[2] だけオフセットされる。# Add margins to plot
p <- p +
geom_abline(slope = slope_1,
intercept = intercept_1 - 1 / w[2],
linetype = "dashed") +
geom_abline(slope = slope_1,
intercept = intercept_1 + 1 / w[2],
linetype = "dashed")
# Display plot
p

e1071 の plot() 関数を使うと、決定境界を簡単にプロットできます。# Visualize decision boundary using built in plot function
plot(x = svm_model,
data = trainset)

Rで学ぶSupport Vector Machines