在R中使用支持向量机( 3. e1071包和klaR包)

包e1071提供了对libsvm的接口。库libsvm包括了常用的核,如线性,多项式,RBF,sigmoid等。多分类通过一对一的投票机制(one-against-one voting scheme)而实现。predict()是训练函数,plot()可视化数据,支持向量,决策边界(如果提供的话)。参数调整tune()。

例如

> library("e1071")

> model <- svm(Species ~ ., data = iris,

method = "C-classification", kernel = "radial",

cost = 10, gamma = 0.1)

> summary(model)

Call:

svm(formula = Species ~ ., data = iris, method = "C-classification", kernel = "radial", cost = 10,

gamma = 0.1)

Parameters:

SVM-Type: C-classification

SVM-Kernel: radial

cost: 10

gamma: 0.1

Number of Support Vectors: 32

( 3 16 13 )

Number of Classes: 3

Levels:

setosa versicolor virginica

显示2-维数据投影及支持向量。

>plot(model, iris, Petal.Width ~

Petal.Length, slice = list(Sepal.Width = 3,

Sepal.Length = 4))

上图中,支持向量被标为"x",预测类区域以颜色背景标亮。

包klaR对库SVMlight进行了简单的包装,提供了函数svmlight()以分类,可视化。Svmlight()支持C-SVM进行分类,ε-SVM进行回归。以一对所有(one-against-all)进行多类分类。SVMlight支持高斯核,多项式,线性和sigmoid核。Svmlight()的参数形式为字符串形式。函数predict()返回每个case的标签。

> library("klaR")

> data("B3")

> Bmod <- svmlight(PHASEN ~ ., data = B3,

+ svm.options = "-c 10 -t 2 -g 0.1 -v 0")

> predict(Bmod, B3[c(4, 9, 30, 60, 80, 120),

+ -1])

$class

[1] 3 3 4 3 4 1

Levels: 1 2 3 4

$posterior

1 2 3 4

[1,] 0.09633177 0.09627103 0.71112031 0.09627689

[2,] 0.09628235 0.09632512 0.71119794 0.09619460

[3,] 0.09631525 0.09624314 0.09624798 0.71119362

[4,] 0.09632530 0.09629393 0.71115614 0.09622463

[5,] 0.09628295 0.09628679 0.09625447 0.71117579

[6,] 0.71123818 0.09627858 0.09620351 0.09627973

posted on 2009-04-14 19:23  zgw21cn  阅读(7223)  评论(2编辑  收藏  举报

导航