Skip to content

Instantly share code, notes, and snippets.

@cereniyim
Last active October 19, 2023 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cereniyim/a6898a39ea44483a91f84b5ad2c843c3 to your computer and use it in GitHub Desktop.
Save cereniyim/a6898a39ea44483a91f84b5ad2c843c3 to your computer and use it in GitHub Desktop.
Estimator wrapper class
@dataclass
class ModelMetaData:
estimator: IsolationForest
model_path: str
class AnomalyDetector:
def __init__(self, estimator=None):
self._estimator = estimator or IsolationForest(
random_state=42,
contamination=0.001,
)
self._features = ["feature1", "feature2"]
self._models_directory = Path(__file__).parents[0] / "models"
def fit_and_save_model(self, data: pd.DataFrame) -> ModelMetaData:
features = data[self._features]
fitted_estimator = self._estimator.fit(features)
timestamp = int(datetime.now().timestamp())
filename = f"model_{timestamp}.pkl"
model_path = str(self._models_directory / filename)
with open(model_path, "wb") as model_file:
pickle.dump(fitted_estimator, model_file)
return ModelMetaData(estimator=fitted_estimator, model_path=model_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment