8

我有一些数据,Y 变量是一个因素 - 好或坏。我正在使用“caret”包中的“train”方法构建支持向量机。使用“训练”功能,我能够最终确定各种调整参数的值并获得最终的支持向量机。对于测试数据,我可以预测“类”。但是当我尝试预测测试数据的概率时,我得到了以下错误(例如,我的模型告诉我测试数据中的第一个数据点有 y='good',但我想知道获得'good'的概率是多少...通常在支持向量机的情况下,模型将计算预测概率..如果 Y 变量有 2 个结果,则模型将预测每个结果的概率。具有最大概率的结果被认为是最终解决方案)

**Warning message:  
In probFunction(method, modelFit, ppUnk) :  
  kernlab class probability calculations failed; returning NAs**

示例代码如下

library(caret)
trainset <- data.frame( 
     class=factor(c("Good",    "Bad",   "Good", "Good", "Bad",  "Good", "Good", "Good", "Good", "Bad",  "Bad",  "Bad")),
     age=c(67,  22, 49, 45, 53, 35, 53, 35, 61, 28, 25, 24))

testset <- data.frame( 
     class=factor(c("Good",    "Bad",   "Good"  )),
    age=c(64,   23, 50))



library(kernlab)
set.seed(231)

### finding optimal value of a tuning parameter
sigDist <- sigest(class ~ ., data = trainset, frac = 1)
### creating a grid of two tuning parameters, .sigma comes from the earlier line. we are trying to find best value of .C
svmTuneGrid <- data.frame(.sigma = sigDist[1], .C = 2^(-2:7))

set.seed(1056)
svmFit <- train(class ~ .,
                data = trainset,
                method = "svmRadial",
                preProc = c("center", "scale"),
                tuneGrid = svmTuneGrid,
                trControl = trainControl(method = "repeatedcv", repeats = 5))

### svmFit finds the optimal values of tuning parameters and builds the model using the best parameters

### to predict class of test data
predictedClasses <- predict(svmFit, testset )
str(predictedClasses)


### predict probablities but i get an error
predictedProbs <- predict(svmFit, newdata = testset , type = "prob")
head(predictedProbs)

此行下方的新问题:根据以下输出,有 9 个支持向量。如何识别这 9 个训练数据点中的 12 个?

svmFit$finalModel

“ksvm”类的支持向量机对象

SV 类型:C-svc(分类)参数:成本 C = 1

高斯径向基核函数。超参数:sigma = 0.72640759446315

支持向量数:9

目标函数值:-5.6994 训练误差:0.083333

4

1 回答 1

14

在 train control 语句中,您必须指定是否要classProbs = TRUE返回类概率。

svmFit <- train(class ~ .,
    data = trainset,
    method = "svmRadial",
    preProc = c("center", "scale"),
    tuneGrid = svmTuneGrid,
    trControl = trainControl(method = "repeatedcv", repeats = 5, 
classProbs =  TRUE))

predictedClasses <- predict(svmFit, testset )
predictedProbs <- predict(svmFit, newdata = testset , type = "prob")

给出在测试数据集中属于坏类或好类的概率:

print(predictedProbs)
    Bad      Good
1 0.2302979 0.7697021
2 0.7135050 0.2864950
3 0.2230889 0.7769111

编辑

要回答您的新问题,您可以使用alphaindex(svmFit$finalModel)with coefficients访问原始数据集中支持向量的位置coef(svmFit$finalModel)

于 2013-07-25T20:48:09.743 回答