|
| 1 | +import pandas as pd |
| 2 | + |
| 3 | +from ..meta import _model_meta |
| 4 | +from .base import BaseHandler |
| 5 | + |
| 6 | +xgb_exists = True |
| 7 | +try: |
| 8 | + import xgboost |
| 9 | +except ImportError: |
| 10 | + xgb_exists = False |
| 11 | + |
| 12 | + |
| 13 | +class XGBoostHandler(BaseHandler): |
| 14 | + """Handler class for creating VetiverModels with statsmodels. |
| 15 | +
|
| 16 | + Parameters |
| 17 | + ---------- |
| 18 | + model : statsmodels |
| 19 | + a trained and fit statsmodels model |
| 20 | + """ |
| 21 | + |
| 22 | + model_class = staticmethod(lambda: xgboost.Booster) |
| 23 | + |
| 24 | + def __init__(self, model, ptype_data): |
| 25 | + super().__init__(model, ptype_data) |
| 26 | + |
| 27 | + def describe(self): |
| 28 | + """Create description for xgboost model""" |
| 29 | + desc = f"Statsmodels {self.model.__class__} model." |
| 30 | + return desc |
| 31 | + |
| 32 | + def create_meta( |
| 33 | + user: list = None, |
| 34 | + version: str = None, |
| 35 | + url: str = None, |
| 36 | + required_pkgs: list = [], |
| 37 | + ): |
| 38 | + """Create metadata for statsmodel""" |
| 39 | + required_pkgs = required_pkgs + ["xgboost"] |
| 40 | + meta = _model_meta(user, version, url, required_pkgs) |
| 41 | + |
| 42 | + return meta |
| 43 | + |
| 44 | + def handler_predict(self, input_data, check_ptype): |
| 45 | + """Generates method for /predict endpoint in VetiverAPI |
| 46 | +
|
| 47 | + The `handler_predict` function executes at each API call. Use this |
| 48 | + function for calling `predict()` and any other tasks that must be executed |
| 49 | + at each API call. |
| 50 | +
|
| 51 | + Parameters |
| 52 | + ---------- |
| 53 | + input_data: |
| 54 | + Test data |
| 55 | +
|
| 56 | + Returns |
| 57 | + ------- |
| 58 | + prediction |
| 59 | + Prediction from model |
| 60 | + """ |
| 61 | + |
| 62 | + if xgb_exists: |
| 63 | + if not isinstance(input_data, xgboost.DMatrix): |
| 64 | + if isinstance(input_data, pd.DataFrame): |
| 65 | + input_data = xgboost.DMatrix(input_data) |
| 66 | + else: |
| 67 | + input_data = xgboost.DMatrix( |
| 68 | + input_data, label=self.model.feature_names |
| 69 | + ) |
| 70 | + |
| 71 | + prediction = self.model.predict(input_data) |
| 72 | + else: |
| 73 | + raise ImportError("Cannot import `xgboost`") |
| 74 | + |
| 75 | + return prediction |
0 commit comments