如何在 R 中为 nnet classification/predict 准备变量?

How to prepare variables for nnet classification/predict in R?

在分类中我使用变量x作为值,y作为标签。如此处的 randomForest 示例所示:

    iris_train_values <- iris[,c(1:4)]
    iris_train_labels <- iris[,5]
    model_RF <- randomForest(x = iris_train_values, y = iris_train_labels, importance = TRUE,
                          replace = TRUE, mtry = 4, ntree = 500, na.action=na.omit,
                          do.trace = 100, type = "classification")

此解决方案适用于许多分类器,但是当我尝试在 nnet 中执行此操作时出现错误:

model_nnet <- nnet(x = iris_train_values, y = iris_train_labels, size = 1, decay = 0.1)

Error in nnet.default(x = iris_train_values, y = iris_train_labels, size = 1,  : 
  NA/NaN/Inf in foreign function call (arg 2)
In addition: Warning message:
In nnet.default(x = iris_train_values, y = iris_train_labels, size = 1,  :
  NAs introduced by coercion

或者在另一个数据集上出现错误:

Error in y - tmp : non-numeric argument to binary operator

我应该如何更改变量进行分类?

公式语法有效:

library(nnet)

model_nnet <- nnet(Species ~ ., data = iris, size = 1)

但矩阵语法没有:

nnet::nnet(x = iris_train_values, y = as.matrix(iris_train_labels), size = 1)

我不明白为什么这不起作用,但至少有解决方法。

predict 适用于公式语法:

?predict.nnet

predict(model_nnet,
        iris[c(1,51,101), 1:4],
        type = "class") # true classese are ['setosa', 'versicolor', 'virginica']