From 07f30dfde52866b507e74c662314a410ccec9b51 Mon Sep 17 00:00:00 2001 From: Aiden010200 <150222139+Aiden010200@users.noreply.github.com> Date: Tue, 4 Feb 2025 00:09:56 +0800 Subject: [PATCH] Upload a SGD classifier predictor example (#3783) This example uses aiplatform and scikit-learn library to provide a SGD classifier. --- .../sklearn/predictor_SGDClassifier.py | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 community-content/vertex_cpr_samples/sklearn/predictor_SGDClassifier.py diff --git a/community-content/vertex_cpr_samples/sklearn/predictor_SGDClassifier.py b/community-content/vertex_cpr_samples/sklearn/predictor_SGDClassifier.py new file mode 100644 index 000000000..0c137ccd0 --- /dev/null +++ b/community-content/vertex_cpr_samples/sklearn/predictor_SGDClassifier.py @@ -0,0 +1,33 @@ +import numpy as np +import os +import pickle + +from google.cloud.aiplatform.constants import prediction +from google.cloud.aiplatform.utils import prediction_utils +from google.cloud.aiplatform.prediction.predictor import Predictor +from sklearn.linear_model import SGDClassifier + +class SGDClassifierPredictor(Predictor): + + def __init__(self): + return + + def load(self, artifacts_uri: str) -> None: + prediction_utils.download_model_artifacts(artifacts_uri) + if os.path.exists(prediction.MODEL_FILENAME_PKL): + self._model = pickle.load(open(prediction.MODEL_FILENAME_PKL, "rb")) + else: + self._model = SGDClassifier(max_iter=5) + X = [[0., 0.], [1., 1.]] + y = [0, 1] + self._model.fit(X, y) + + def preprocess(self, prediction_input: dict) -> np.ndarray: + instances = prediction_input["instances"] + return np.asarray(instances) + + def predict(self, instances: np.ndarray) -> np.ndarray: + return self._model.predict(instances) + + def postprocess(self, prediction_results: np.ndarray) -> dict: + return {"predictions": prediction_results.tolist()}