首页 > 解决方案 > 预测函数将概率转换为 0 到 1 并存储在数据框中

问题描述

Predict 函数代码返回这样的输出。

library(e1071)
model <- svm(Species ~ ., data = iris, probability=TRUE)
pred <- predict(model, iris, probability=TRUE)

head(attr(pred, "probabilities"))
#      setosa versicolor   virginica
# 1 0.9803339 0.01129740 0.008368729
# 2 0.9729193 0.01807053 0.009010195
# 3 0.9790435 0.01192820 0.009028276
# 4 0.9750030 0.01531171 0.009685342
# 5 0.9795183 0.01164689 0.008834838
# 6 0.9740730 0.01679643 0.009130620

所以,我写了一段这样的代码:-

Code:-

pred_df <- as.data.frame(pred)

这将返回这样的输出,(刚刚组成了值)

1 Setosa
2 Versicolor
3 Virginica
4 Setosa
5 Setosa

但我首选的输出是这样的(刚刚组成了值),

   Setosa      Versicolor       Virginica
1 0.62          0.11               0.27
2 0.41          0.55               0.04

***Pred is a factor and Pred_df is a dataframe***

我希望以小数而不是整数的形式返回数字。请帮我解决这个问题。

标签: r

解决方案


要了解发生了什么,您需要查看结构内部。

str(pred)
 Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
 - attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
 - attr(*, "probabilities")= num [1:150, 1:3] 0.979 0.971 0.978 0.973 0.978 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:150] "1" "2" "3" "4" ...
  .. ..$ : chr [1:3] "setosa" "versicolor" "virginica"

所以

as.data.frame(attr(pred,"probabilities"))

应该做你想做的。


推荐阅读