0

The Predict function code returns output like this.

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

So, I wrote a piece of code like this :-

Code:-

pred_df <- as.data.frame(pred)

This returns output like this, (have just made up the values)

1 Setosa
2 Versicolor
3 Virginica
4 Setosa
5 Setosa

But my preferred output would be something like this (have just made up the values),

   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***

I am looking to return the numbers in the form of a decimal rather than a whole number. Kindly help me with this.

1 Answers1

2

To see what's going on you need to look inside the structure.

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"

So

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

should do what you want.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453