0

I have 20 classes, and I want to classify and predict class label:

library("caret")
model=train(x=df_train,y=train_class, method="nnet")
pred=predict(model,df_test)

The output of pred is real number (it performs regression), How can I ask to return me prediction of class labels?

Cina
  • 135

1 Answers1

2

This question might be better suited to stackoverflow, though you have not given a reproducible example.

The following predicts the species class label for the iris dataset, adapting the example from ?train

library(caret)
library(MASS)
data(iris)
set.seed(1)
TestRows     <- c(sample(50,15), sample(50,15)+50, sample(50,15)+100)
TrainData    <- iris[-TestRows,1:4]
TrainClasses <- iris[-TestRows,5]
TestData     <- iris[TestRows,1:4]
TestClasses  <- iris[TestRows,5]
nnetFit <- train(x=TrainData, y=TrainClasses,
                 method = "nnet",
                 preProcess = "range", 
                 tuneLength = 2,
                 trace = FALSE,
                 maxit = 100)

and gives the following result for the training set:

> table(TrainClasses, predict(nnetFit)) 

TrainClasses setosa versicolor virginica
  setosa         35          0         0
  versicolor      0         34         1
  virginica       0          1        34

and for the test set

> table(TestClasses,  predict(nnetFit,TestData))  

TestClasses  setosa versicolor virginica
  setosa         15          0         0
  versicolor      0         15         0
  virginica       0          3        12

which I find surprisingly accurate for the versicolor/virginica distinction

Henry
  • 39,459
  • Thank you for the solution. But, when I apply to my data predict(nnetFit,TestData)[1] is 0.9923. It returns regression prediction of my data. I think the problem comes from levels of data. levels(iris) shows the three classes but levels(myData) is Null. Do this levels is problem? how to fix this? – Cina Apr 16 '17 at 07:11
  • No - this works without levels in the input data. But without seeing your data, it is difficult to say much more. What type of data is your train_class – Henry Apr 16 '17 at 08:03