【发布时间】:2017-08-09 15:43:11
【问题描述】:
我担心的是,当我训练一个 nnet 时,该类是类型因子,但是当我进行预测时,我得到了一个返回的 chr。
这个例子我取自另一个帖子。
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 ...
对于 predict 的输出,我更喜欢一致的、基于因子的格式。在 nnet 的情况下将 predict 的字符输出转换为因子是行不通的,因为我不能保证所有级别都将作为字符变量存在。例如,在我的 650 个案例中,有一个案例具有唯一级别,有时可能在测试数据集中,有时不在,但我希望 predict 的输出知道它,即使它不在测试数据中。
谢谢。
【问题讨论】:
标签: r neural-network predict