线性支持向量机#
library(ggplot2)
library(lattice)
library(kernlab)
library(caret)
#将数据使用留出采样法进行划分成训练集、测试集
train <- createDataPartition(y=iris$Species, p=0.75, list=FALSE)
training <- iris[train,]
testing <- iris[-train,]
#导入e1071包训练svm模型
library(e1071)
svmfit <- svm(Species ~ ., data = training, kernel = "linear", cost = 10, scale = FALSE)
#比较测试数据集预测结果
table(testing$Species, predict(svmfit, testing[, c(1, 2, 3, 4)]))
径向支持向量机#
library(ggplot2)
library(lattice)
library(kernlab)
library(caret)
#将数据使用留出采样法进行划分成训练集、测试集
train <- createDataPartition(y=iris$Species, p=0.75, list=FALSE)
training <- iris[train,]
testing <- iris[-train,]
#导入e1071包训练svm模型
library(e1071)
svmfit <- svm(Species ~ ., data = training, kernel = "radial", cost = 10, scale = FALSE)
#比较测试数据集预测结果
table(testing$Species, predict(svmfit, testing[, c(1, 2, 3, 4)]))
最优参数##
library(ggplot2)
library(lattice)
library(kernlab)
library(caret)
library(e1071)
train <- createDataPartition(y=iris$Species, p=0.75, list=FALSE)
training <- iris[train,]
tuned <- tune.svm(Species ~ ., data = training, gamma = 10^(-6:-1), cost = 10^(1:2)) # tune
summary (tuned)
网友评论