Support Vector Machines in R
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
index
from svm_model
.# 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
Find slope and intercept of the boundary:
w
, from coefs
and SV
elements of svm_model
.# 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()
to add the decision boundary to the plot.# Plot decision boundary based on calculated slope and intercept
p <- p + geom_abline(slope = slope_1,
intercept = intercept_1)
1 / w[2]
on either side of it.# 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
plot()
function in e1071
offers an easy way to plot the decision boundary.# Visualize decision boundary using built in plot function
plot(x = svm_model,
data = trainset)
Support Vector Machines in R