生成径向可分的数据集

R 中的支持向量机

Kailash Awati

Instructor

生成二维均匀分布点集

  • 生成包含 200 个点的数据集
    • 2 个自变量 x1 和 x2,在 -1 到 1 之间均匀分布。
# Set required number of datapoints
n <- 200
# Set seed to ensure reproducibility
set.seed(42)

# Generate dataframe with 2 predictors x1 and x2 in (-1, 1)
df <- data.frame(x1 = runif(n, min = -1, max = 1),
                 x2 = runif(n, min = -1, max = 1))
R 中的支持向量机

创建圆形边界

  • 创建半径为 0.7 的圆形决策边界。
  • 分类变量 y:点在边界内为 -1,外为 +1。
radius <- 0.7
radius_squared <- radius ^ 2

#categorize data points depending on location wrt boundary
df$y <- factor(ifelse(df$x1 ^ 2 + df$x2 ^ 2 < radius_squared, -1, 1),
               levels = c(-1, 1))
R 中的支持向量机

绘制数据集

  • 使用 ggplot 可视化。
library(ggplot2)
  • 两个自变量为坐标轴;类别用颜色区分。
# Build plot
p <- ggplot(data = df, aes(x = x1, y = x2, color = y)) + 
     geom_point() + 
     scale_color_manual(values = c("-1" = "red", "1" = "blue")) 
# Display plot 
p
R 中的支持向量机

第 3.1 章 - 径向可分数据集

R 中的支持向量机

添加圆形边界 - 第 1 部分

  • 我们将创建一个生成圆的函数
# Function generates dataframe with points
# lying on a circle of radius r
circle <- 
  function(x1_center, x2_center, r, npoint = 100) {

  # Angular spacing of 2*pi/npoint between points
  theta <- seq(0, 2 * pi, length.out = npoint)
  x1_circ <- x1_center + r * cos(theta)
  x2_circ <- x2_center + r * sin(theta)

  data.frame(x1c = x1_circ, x2c = x2_circ)
}
R 中的支持向量机

添加圆形边界 - 第 2 部分

  • 向图中添加边界:
    • 使用 circle() 函数生成边界。
    • 使用 geom_path() 将边界加入图中。
# Generate boundary
boundary <- circle(x1_center = 0,
                   x2_center = 0,
                   r = radius)
# Add boundary to previous plot
p <- p + 
     geom_path(data = boundary,
               aes(x = x1c, y = x2c),
               inherit.aes = FALSE)
# Display plot
p
R 中的支持向量机

第 3.1 章 - 带决策边界的径向可分数据集

R 中的支持向量机

该练习由你来完成!

R 中的支持向量机

Preparing Video For Download...