r - 预测函数将概率转换为 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***
我希望以小数而不是整数的形式返回数字。请帮我解决这个问题。
解决方案
要了解发生了什么,您需要查看结构内部。
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"))
应该做你想做的。
推荐阅读
- python - 在 matplotlib 中激活图形
- typescript - 带有查询的可重用类型化 react-apollo 组件
- java - 如何使用 Selenium 和 Java 通过 type="hidden" 的“输入”元素上传文件?
- java - 为什么进度对话框不显示?
- spring-boot - 来自 helm 的 Spring Boot 日志 secret.yaml
- html - 页脚问题 CSS
- java - JSON 字符串到 Object[]
- ibm-cloud - 没有 Watson Conversation 服务的 IBM Cloud UI 的对话
- c# - 以编程方式捕获确认提示
- symfony - 给定“字符串”、“App\Entity”类型的预期参数