Enrique
Enrique

Reputation: 10117

Write custom classifier in R and predict function

I would like to implement my own custom classifier in R, e.g., myClassifier(trainingSet, ...) which returns the learnt model m from a specified training set. I would like to call it just like any other classifier in r:

m <- myClassifier(trainingSet)

and then I want to overload (I don't know if this is the correct word) the generic function predict()

result <- predict(m, myNewData)

I have just a basic knowledge in R. I don't know which resources I should read in order to accomplish the desired task. In order for this to work, do I need to create a package?. I am looking for some initial directions.

Does the model m contain information about the overriden predict method?, or how does R knows which predict.* method corresponds to model m?

Upvotes: 6

Views: 2743

Answers (1)

tchakravarty
tchakravarty

Reputation: 10964

Here is some code that shows how to write a method for your own class for a generic function.

# create a function that returns an object of class myClassifierClass
myClassifier = function(trainingData, ...) {
  model = structure(list(x = trainingData[, -1], y = trainingData[, 1]), 
                    class = "myClassifierClass") 
  return(model)
}

# create a method for function print for class myClassifierClass
predict.myClassifierClass = function(modelObject) {
  return(rlogis(length(modelObject$y)))
} 

# test
mA = matrix(rnorm(100*10), nrow = 100, ncol = 10)
modelA = myClassifier(mA)
predict(modelA)

Upvotes: 15

Related Questions