2017-03-17 18 views
1

我擔心的是,當我訓練一個nnet時,這個類是類型因子,但是當我做一個預測時,我會返回一個chr。來自nnet的預測是一個字符而不是一個因子

我從另一篇文章中看到了這個例子。

library(nnet) 
library(C50) 
library(caret) 
attach(iris) 
set.seed(3456) 
trainIndex <- createDataPartition(iris$Species, p = .8, 
          list = FALSE, 
          times = 1) 
irisTrain <- iris[ trainIndex,] 
irisTest <- iris[-trainIndex,] 

irispred <- nnet(Species ~ ., data=irisTrain, size=10) 
predicted <- predict(irispred,irisTest,type="class") 

> str(irisTrain) 
'data.frame': 120 obs. of 5 variables: 
$ Sepal.Length: num 5.1 4.9 4.6 5 5.4 5 4.4 4.9 5.4 4.8 ... 
$ Sepal.Width : num 3.5 3 3.1 3.6 3.9 3.4 2.9 3.1 3.7 3 ... 
$ Petal.Length: num 1.4 1.4 1.5 1.4 1.7 1.5 1.4 1.5 1.5 1.4 ... 
$ Petal.Width : num 0.2 0.2 0.2 0.2 0.4 0.2 0.2 0.1 0.2 0.1 ... 
$ Species  : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ... 
> str(irisTest) 
'data.frame': 30 obs. of 5 variables: 
$ Sepal.Length: num 4.7 4.6 4.8 4.3 5.4 4.6 5 5 4.6 5.3 ... 
$ Sepal.Width : num 3.2 3.4 3.4 3 3.4 3.6 3.5 3.5 3.2 3.7 ... 
$ Petal.Length: num 1.3 1.4 1.6 1.1 1.7 1 1.3 1.6 1.4 1.5 ... 
$ Petal.Width : num 0.2 0.3 0.2 0.1 0.2 0.2 0.3 0.6 0.2 0.2 ... 
$ Species  : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ... 

所以在訓練和測試數據集物種的因素,但

str(predicted) 
chr [1:30] "setosa" "setosa" "setosa" "setosa" "setosa" ... 

預測的結果是字符。我使用其他數據挖掘軟件包,例如C50,以及他們從預測返回因素,

> irispred <- C5.0(Species ~ ., data=irisTrain) 
> predicted <- predict(irispred,irisTest,type="class") 
> str(predicted) 
Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 2 1 1 ... 

我寧願基於一致的,因素,格式預測的輸出。在nnet的情況下將預測的字符輸出轉換爲因子將不起作用,因爲我無法保證所有的級別都將作爲字符變量存在。例如,對於我的650個案例,有一個案例具有獨特的級別,這有時可能在測試數據集中,有時可能不會,但是我希望預測的輸出知道它,即使它不在測試數據中。

感謝。

回答

1

在玩過0​​後,它將類的等級存儲在其結果的lev成員中。即使級別不包含在訓練集中,輸入數據也會保留級別的排序。通過使用factor(predicted_class, levels = model_object$lev)可以輕鬆地將預測的類別重新制作成一個因子。例如:

iris2 <- iris 
iris2$Species <- factor(iris2$Species, 
    levels = c("versicolor", "banana", "setosa", "cherry", "virginica")) 
iris_pred <- nnet(Species ~ ., data = iris2[trainIndex, ], size = 10) 

#Warning message: 
#In nnet.formula(Species ~ ., data = iris2[trainIndex, ], size = 10) : 
# groups ‘banana’ ‘cherry’ are empty 

identical(iris_pred$lev, levels(iris2$Species)) 
#[1] TRUE 

predicted <- predict(iris_pred, iris2[-trainIndex, ], type="class") 
predicted_fac <- factor(predicted, levels = iris_pred$lev) 
table(iris2[-trainIndex, "Species"], predicted_fac) 

#   predicted_fac 
#    versicolor banana setosa cherry virginica 
# versicolor   10  0  0  0   0 
# banana    0  0  0  0   0 
# setosa    0  0  10  0   0 
# cherry    0  0  0  0   0 
# virginica   0  0  0  0  10 
+0

感謝尼克,這看起來工作。 –

相關問題