David Smith
David Smith

Reputation: 11

Python Vetiver model - use alternative prediction method

I'm trying to use Vetiver to deploy an isolation forest model (for anomaly detection) to an API endpoint.

All is going well by adapting the example here.

However, when deployed, the endpoint uses the model.predict() method by default (which returns 1 for normal or -1 for anomaly).

I want the model to return a score between 0 and 1 as given by the model.score_samples() method.

Does anybody know how I can configure the Vetiver endpoint such that it uses .score_samples() rather than .predict() for scoring?

Thanks

Upvotes: 1

Views: 180

Answers (1)

Isabel Zimmerman
Isabel Zimmerman

Reputation: 66

vetiver.predict() primarily acts as a router to an API endpoint, so it does not have to have the same behavior as model.predict(). You can overload what function vetiver.predict() uses on your model by defining a custom handler.

In your case, an implementation might look something like below.

from vetiver.handlers.base import VetiverHandler

class ScoreSamplesHandler(VetiverHandler):
    def __init__(self, model, ptype_data):
        super().__init__(model, ptype_data)

    def handler_predict(self, input_data, check_ptype):
        """
        Define how to make predictions from your model
        """
        prediction = self.model.score_samples(input_data)
        
        return prediction

Initialize your custom handler and pass it into VetiverModel().

custom_model = ScoreSamplesHandler(model, ptype_data)

VetiverModel(custom_model, "model_name")

Then, when you use the vetiver.predict() function, it will return the values for model.score_samples(), rather than model.predict().

Upvotes: 2

Related Questions