本文参考:《精通机器学习:基于R》5.3节
数据集来自R包(MASS),包含了532位女性的信息,存储在两个数据框中,具体变量表述如下:
npreg:怀孕次数
glu:血糖浓度, 由口服葡萄糖耐量测试给出
bp:舒张压
skin:三头肌皮褶厚度
bmi:身体质量指数
ped:糖尿病家族影响因素
age:年龄
type:是否患有糖尿病(yes/no)
目的:研究这类人群,对可能导致糖尿病的风险因素进行预测。
1. 数据预处理
# 载入相关R包和数据
library(e1071)
library(caret)
library(MASS)
library(reshape2)
library(ggplot2)
library(kernlab)
# train
data("Pima.tr")
# test
data("Pima.te")
# 合并数据,便于把数据的特征可视化
pima <- rbind(Pima.tr, Pima.te)
pima.melt <- melt(pima, id.vars = "type")
# 画箱线图进行对比
ggplot(data = pima.melt, aes(x = type, y = value, fill = type)) + geom_boxplot() +
facet_wrap(~ variable, ncol = 2)
从图中可以看出,两种人群除了glu有明显的差距外,其余的都看不出来区别,原因就是这几种特征的数值差别太大,所以我们要对数据进行归一化处理,好让我们看到更明显的结果。
# data.frame格式的数据scale之后会自动变成一个矩阵,所以要重新将其变为data.frame
pima.scale <- data.frame(scale(pima[, -8]))
pima.scale$type <- pima$type
pima.scale.melt <- melt(pima.scale, id.vars = "type")
ggplot(data = pima.scale.melt, aes(x = type, y = value, fill = type)) + geom_boxplot() +
facet_wrap(~ variable, ncol = 2)
这样作出的图就明显一些, 但其实只是从扁的变长了一点,还需要进一步分析。
> # 查看相关性
> cor(pima.scale[-8])
npreg glu bp skin bmi ped age
npreg 1.000000000 0.1253296 0.204663421 0.09508511 0.008576282 0.007435104 0.64074687
glu 0.125329647 1.0000000 0.219177950 0.22659042 0.247079294 0.165817411 0.27890711
bp 0.204663421 0.2191779 1.000000000 0.22607244 0.307356904 0.008047249 0.34693872
skin 0.095085114 0.2265904 0.226072440 1.00000000 0.647422386 0.118635569 0.16133614
bmi 0.008576282 0.2470793 0.307356904 0.64742239 1.000000000 0.151107136 0.07343826
ped 0.007435104 0.1658174 0.008047249 0.11863557 0.151107136 1.000000000 0.07165413
age 0.640746866 0.2789071 0.346938723 0.16133614 0.073438257 0.071654133 1.00000000
可以看出,skin和bmi、npreg和age之间具有很高的相关性。但貌似还是看不出与type有多大关系,我们继续。
# 设置一个随机数种子,之后可以复现结果
set.seed(123)
# 把数据呼啦呼啦(随机打乱),然后三七分,七为训练集,三为测试集
ind <- sample(2, nrow(pima.scale), replace = TRUE, prob = c(0.7, 0.3))
train <- pima.scale[ind == 1, ]
test <- pima.scale[ind == 2, ]
2. 建模
我们使用e1071包来构建svm模型,e1071包中的svm()包含四种内核,我们依次测试四种kernel,看哪一个结果最好。不过在这里我们使用tune.svm(),因为该函数可以进行参数调优,kernel的种类也是可以选择的。
kernel
the kernel used in training and predicting. You might consider changing some of the following parameters, depending on the kernel type.linear:
*u’v
polynomial:
(gamma*u’v + coef0)^degree
radial basis:
exp(-gamma|u-v|^2)
sigmoid:
*tanh(gamma*u’v + coef0)
1. linear
# linear
set.seed(123)
# 寻找最优参数
linear.tune <- tune.svm(type ~., data = train, kernal = "linear",
cost = c(0.001, 0.01, 0.1, 1, 5, 10))
summary(linear.tune)
# 利用最优模型来预测
best.linear <- linear.tune$best.model
linear.test <- predict(best.linear, newdata = test)
# 查看预测准确率
linear.tab <- table(linear.test, test$type)
linear.tab
# diag():对角线相加
sum