除了预测类标签之外,在预测时是否可以返回新数据中每个观察的期望?
library(caret)
knnFit <- train(Species ~ ., data = iris, method = "knn",
trControl = trainControl(method = "cv", classProbs = TRUE))
x <- predict(knnFit, newdata = iris)
Run Code Online (Sandbox Code Playgroud)
返回预测类别的向量。
str(x)
Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
Run Code Online (Sandbox Code Playgroud)
如果我想要概率:
x <- predict(knnFit, newdata = iris, type = "prob")
> head(x)
setosa versicolor virginica
1 1 0 0
2 1 0 0
3 1 0 0
4 1 0 0
5 1 0 0
6 1 0 0
Run Code Online (Sandbox Code Playgroud)
是否可以让插入符号同时返回预测和概率?我知道我可以通过采用概率版本的 max.col 来计算,但我想知道是否有内置的方法来获得两者?
我把我的评论变成了一个答案。生成概率预测表后,您实际上不需要运行两次预测函数来获取类别。您可以通过应用一个简单的which.max函数(运行速度很快)来要求添加类列。这将c("setosa", "versicolor", "virginica")根据概率最高的情况为每一行分配列的名称(三个中的一个)。
根据要求,您将获得包含这两个信息的表格:
library(dplyr)
predict(knnFit, newdata = iris, type = "prob") %>%
mutate('class'=names(.)[apply(., 1, which.max)])
# a random sample of the resulting table:
#### setosa versicolor virginica class
#### 18 1 0.0000000 0.0000000 setosa
#### 64 0 0.6666667 0.3333333 versicolor
#### 90 0 1.0000000 0.0000000 versicolor
#### 121 0 0.0000000 1.0000000 virginica
Run Code Online (Sandbox Code Playgroud)
ps:这使用来自dplyr或magrittr包的管道操作符。点.表示何时重用上一条指令的结果