Error in UseMethod("train")

Hi everybody!

This is my script for a KNN model:

library(class)
library(ggplot2)
library(gmodels)
library(scales)

db_dati <- iris
db_class <- as.data.frame(db_dati)
unique(db_class$Species)
table(db_class$Species)
#--------

#TRAIN E TEST
#--------
db_train <- db_class
#--------

# KNN
#-------
library(generics)
model_knn<-train(Species ~ ., data = db_train, method = "knn",tuneLength = 10)
summary(model_knn)
#-------

#PREDICTION NEW RECORD
#-------
test_data <- c(4.6, 2.9, 1.3)
predict(model_knn, newdata=test_data, interval='confidence')
#-------

But I have this error:

Error in UseMethod("train") :
no applicable method for 'train' applied to an object of class "formula"

how can i fix it?

Thanks

It seems that you are loading no packages that hold a method for train(). The generics package has a generic named train(), but none of the other packages you load export a train() method/function, especially none for formulas. Also, it should never be necessary to load the generics package manually in a script, the generics package is for use by other packages as far as I understand its purpose.

Read more about generics and methods here.

It might be worth it for you to check out tidymodels, it is a perfect framework for what you are trying to achieve.

Perhaps the script needs a library(caret) at the top.

I tried to add this library but I still have the same error

The strange thing is that I tried the same script (adding the caret library) on another computer and it works. I can't understand the reason

did you remove the library(generics), because if that is happening after library(caret) then it will mask train

library(generics)

Attaching package: ‘generics’

The following object is masked from ‘package:caret’:

    train

to summarise, do load caret, dont load generics

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.