8.7 SVM

关于支持向量机SVM的介绍参见视频

e1071包的tune()函数能够对超参数进行网格搜索,并保留最优模型。

library(e1071)

# 设置参数范围,进行网格搜索
tune_grid <- list(
  cost = c(0.1, 0.5, 1, 5),
  gamma = c(0.01, 0.1, 1, 10),
  kernel = c('radial', 'linear')
)
set.seed(123)
# tune()函数能够自行调优
model_tune_svm <- tune(
  METHOD = svm,
  train.x = label ~ score + departure,
  data = train_set,
  ranges = tune_grid,
  tunecontrol = tune.control(
    sampling = "cross",             # 交叉验证
    cross = 5,                      # 5折交叉验证
    best.model = TRUE               # 保留最佳模型
  )
  )

summary(model_tune_svm)
model_tune_svm$best.parameters            # 最优参数组合
model_svm <- model_tune_svm$best.model    # 提取最优模型
fit_svm <- predict(model_svm, train_set)  # 测试集预测