核技巧

R 中的支持向量机

Kailash Awati

Instructor

基本思路

  • 设计一种变换,使问题线性可分。
  • 我们将以径向可分数据集为例说明。
R 中的支持向量机

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

R 中的支持向量机

问题变换

  • 边界方程为 $x_1 ^ 2 + x_2 ^ 2 = 0.49$
  • 将 $x_1 ^ 2$ 映射为新变量 $X_1$,$x_2 ^ 2$ 映射为 $X_2$
  • 在 $X_1 - X_2$ 空间中的边界变为…
  • $X_1 + X_2 = 0.49$(一条直线!)
R 中的支持向量机

X1-X2 空间绘图 - 代码

  • 用 ggplot() 在 $X_1 - X_2$ 空间绘制数据集
  • 边界方程 $X_2 = -X_1 + 0.49$:
    • $slope = -1$
    • $yintercept = 0.49$
p <- ggplot(data = df4, aes(x = x1sq, y = x2sq, color = y)) + 
  geom_point() + 
  scale_color_manual(values = c("red", "blue")) +
  geom_abline(slope = -1, intercept = 0.49)

p
R 中的支持向量机

第 3.3 章 - 变换后的径向可分数据集与决策边界

R 中的支持向量机

多项式核 - 第 1 部分

  • 多项式核:(gamma * (u.v) + coef0) ^ degree
    • degree 为多项式次数
    • gamma 和 coef0 为调参项
    • u、v 为数据集中的向量(样本)
  • 可推测需要二次多项式(变换)
R 中的支持向量机

核函数

  • SVM 的数学形式要求具备特定性质的变换。
  • 满足这些性质的函数称为核函数
  • 核函数是向量点积的推广
  • 核心思路:选用能很好分开数据的核!
R 中的支持向量机

径向可分数据集 - 二次核

  • 80/20 训练/测试划分
  • 为径向可分数据集构建二次 SVM:
    • 设 degree = 2
    • 使用 cost、gamma、coef0 的默认值(1、1/2、0)
svm_model <- svm(y ~ ., data = trainset, type = "C-classification", kernel = "polynomial", degree = 2)
# Predictions
pred_test <- predict(svm_model, testset)
mean(pred_test == testset$y)
0.9354839
# Visualize model
plot(svm_model, trainset)
R 中的支持向量机

第 3.3 章 - 径向可分数据集,默认 cost 的二次核,使用 svm.plot 绘图

R 中的支持向量机

该练习了!

R 中的支持向量机

Preparing Video For Download...