2

In the classification I use the variable x as the value and y as the labels. As here in the example for 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")

This solution works for many classifiers, however when I try to do it in nnet and get error:

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

Or on another data set gets an error:

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

How should I change the variables to classify?

Rick_H
  • 77
  • 6
  • 1
    using the `formula` syntax seems to work: `nnet::nnet(Species ~ ., data = iris, size = 1)` is that an options? The docs say y must be a matrix of data frame, but I get the same error using `as.data.frame(iris_train_labels)` and `as.matrix(iris_train_labels)` – Nate May 03 '20 at 23:37
  • Thank you, your answer is correct, write it in the post, I will give it as a solution – Rick_H May 04 '20 at 08:38
  • Maybe you know how to use it to predict a test data set using the predict function from caret ? – Rick_H May 04 '20 at 08:46

1 Answers1

1

The formula syntax works:

library(nnet)

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

But the matrix syntax does not:

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

I don't understand why this doesn't work, but at least there is a work around.

predict works fine with the formula syntax:

?predict.nnet

predict(model_nnet,
        iris[c(1,51,101), 1:4],
        type = "class") # true classese are ['setosa', 'versicolor', 'virginica']
Nate
  • 10,361
  • 3
  • 33
  • 40