Search code examples
rneural-networknnet

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


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?


Solution

  • 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']