-
Notifications
You must be signed in to change notification settings - Fork 18
implement statsmodels handler #100
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
2eb1c43
initial statsmodels support
isabelizimm 005ff97
test serialization
isabelizimm aebf597
clean up docs
isabelizimm 5e98300
github actions tweaks
isabelizimm a65fcc9
request to json
isabelizimm 5b6854b
request to json
isabelizimm 2edf364
no ptype and batch tests
isabelizimm 35a709d
more scalable language
isabelizimm 2cd6976
fix up imports
isabelizimm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -48,3 +48,6 @@ dev = | |
|
|
||
| torch = | ||
| torch | ||
|
|
||
| statsmodels = | ||
| statsmodels | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| import pandas as pd | ||
|
|
||
| from ..meta import _model_meta | ||
| from .base import BaseHandler | ||
|
|
||
| sm_exists = True | ||
| try: | ||
| import statsmodels.api | ||
| except ImportError: | ||
| sm_exists = False | ||
|
|
||
|
|
||
| class StatsmodelsHandler(BaseHandler): | ||
| """Handler class for creating VetiverModels with statsmodels. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| model : statsmodels | ||
| a trained and fit statsmodels model | ||
| """ | ||
|
|
||
| model_class = staticmethod(lambda: statsmodels.base.wrapper.ResultsWrapper) | ||
|
|
||
| def __init__(self, model, ptype_data): | ||
| super().__init__(model, ptype_data) | ||
|
|
||
| def describe(self): | ||
| """Create description for statsmodels model""" | ||
| desc = f"Statsmodels {self.model.__class__} model." | ||
| return desc | ||
|
|
||
| def create_meta( | ||
| user: list = None, | ||
| version: str = None, | ||
| url: str = None, | ||
| required_pkgs: list = [], | ||
| ): | ||
| """Create metadata for statsmodel""" | ||
| required_pkgs = required_pkgs + ["statsmodels"] | ||
| meta = _model_meta(user, version, url, required_pkgs) | ||
|
|
||
| return meta | ||
|
|
||
| def handler_predict(self, input_data, check_ptype): | ||
| """Generates method for /predict endpoint in VetiverAPI | ||
|
|
||
| The `handler_predict` function executes at each API call. Use this | ||
| function for calling `predict()` and any other tasks that must be executed | ||
| at each API call. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| input_data: | ||
| Test data | ||
|
|
||
| Returns | ||
| ------- | ||
| prediction | ||
| Prediction from model | ||
| """ | ||
| if sm_exists: | ||
| if isinstance(input_data, (list, pd.DataFrame)): | ||
| prediction = self.model.predict(input_data) | ||
| else: | ||
| prediction = self.model.predict([input_data]) | ||
| else: | ||
| raise ImportError("Cannot import `statsmodels`") | ||
|
|
||
| return prediction | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| import pytest | ||
|
|
||
| sm = pytest.importorskip("statsmodels.api", reason="statsmodels library not installed") | ||
|
|
||
| statsmodels = pytest.importorskip( | ||
| "statsmodels", reason="statsmodels library not installed" | ||
| ) | ||
|
|
||
| import numpy as np # noqa | ||
| import pandas as pd # noqa | ||
| from fastapi.testclient import TestClient # noqa | ||
|
|
||
| import vetiver # noqa | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def build_sm(): | ||
|
|
||
| X, y = vetiver.get_mock_data() | ||
| glm = sm.GLM(y, X).fit() | ||
|
|
||
| v = vetiver.VetiverModel(glm, "glm", X) | ||
| return v | ||
|
|
||
|
|
||
| def test_vetiver_build(build_sm): | ||
| api = vetiver.VetiverAPI(build_sm) | ||
| client = TestClient(api.app) | ||
| data = [{"B": 0, "C": 0, "D": 0}] | ||
|
|
||
| response = vetiver.predict(endpoint=client, data=data) | ||
|
|
||
| assert response.iloc[0, 0] == 0.0 | ||
| assert len(response) == 1 | ||
|
|
||
|
|
||
| def test_batch(build_sm): | ||
| api = vetiver.VetiverAPI(build_sm) | ||
| client = TestClient(api.app) | ||
| data = pd.DataFrame(np.random.randint(0, 100, size=(100, 4)), columns=list("ABCD")) | ||
|
|
||
| response = vetiver.predict(endpoint=client, data=data) | ||
|
|
||
| assert len(response) == 100 | ||
|
|
||
|
|
||
| def test_no_ptype(build_sm): | ||
| api = vetiver.VetiverAPI(build_sm, check_ptype=False) | ||
| client = TestClient(api.app) | ||
| data = [0, 0, 0] | ||
|
|
||
| response = vetiver.predict(endpoint=client, data=data) | ||
|
|
||
| assert response.iloc[0, 0] == 0.0 | ||
| assert len(response) == 1 | ||
|
|
||
|
|
||
| def test_serialize(build_sm): | ||
| import pins | ||
|
|
||
| board = pins.board_temp(allow_pickle_read=True) | ||
| vetiver.vetiver_pin_write(board=board, model=build_sm) | ||
| assert isinstance( | ||
| board.pin_read("glm"), | ||
| statsmodels.genmod.generalized_linear_model.GLMResultsWrapper, | ||
| ) | ||
| board.pin_delete("glm") |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
for models with a
predictmethod, using this class seems to be sufficient to identifystatsmodelsmodels