如何从 caret::predict() 获得 class 概率和预测?
How to get the class probabilities AND predictions from caret::predict()?
除了预测class标签外,是否可以在预测时return对新数据中每个观测值的期望?
library(caret)
knnFit <- train(Species ~ ., data = iris, method = "knn",
trControl = trainControl(method = "cv", classProbs = TRUE))
x <- predict(knnFit, newdata = iris)
Returns 预测的向量 classes.
str(x)
Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
如果我想要概率:
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
是否可以同时使用插入符号 return 预测和概率?我知道我可以通过采用概率版本的 max.col 来计算,但我想知道是否有一种内置的方法可以同时获得两者?
我把我的评论变成一个答案。
一旦生成 table 概率预测,您实际上不需要 运行 两倍的预测函数来获得 classes。您可以通过应用一个简单的 which.max
函数(在我看来 运行 速度很快)来请求添加 class 列。这将为每一行分配列的名称(三个中的一个 c("setosa", "versicolor", "virginica")
),基于哪个概率最高。
你得到这个 table 包含这两个信息,如所要求的:
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
ps:这使用来自 dplyr
或 magrittr
包的管道运算符。点 .
表示何时重用前一条指令的结果
除了预测class标签外,是否可以在预测时return对新数据中每个观测值的期望?
library(caret)
knnFit <- train(Species ~ ., data = iris, method = "knn",
trControl = trainControl(method = "cv", classProbs = TRUE))
x <- predict(knnFit, newdata = iris)
Returns 预测的向量 classes.
str(x)
Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
如果我想要概率:
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
是否可以同时使用插入符号 return 预测和概率?我知道我可以通过采用概率版本的 max.col 来计算,但我想知道是否有一种内置的方法可以同时获得两者?
我把我的评论变成一个答案。
一旦生成 table 概率预测,您实际上不需要 运行 两倍的预测函数来获得 classes。您可以通过应用一个简单的 which.max
函数(在我看来 运行 速度很快)来请求添加 class 列。这将为每一行分配列的名称(三个中的一个 c("setosa", "versicolor", "virginica")
),基于哪个概率最高。
你得到这个 table 包含这两个信息,如所要求的:
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
ps:这使用来自 dplyr
或 magrittr
包的管道运算符。点 .
表示何时重用前一条指令的结果