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個案例,有一個案例具有獨特的級別,這有時可能在測試數據集中,有時可能不會,但是我希望預測的輸出知道它,即使它不在測試數據中。
感謝。
感謝尼克,這看起來工作。 –