|
| 1 | +import logging |
| 2 | +import joblib |
| 3 | +import numpy as np |
| 4 | +from azureml.core.model import Model |
| 5 | + |
| 6 | +# Configure logging at INFO level |
| 7 | +logger = logging.getLogger(__name__) |
| 8 | +logger.setLevel(logging.INFO) |
| 9 | + |
| 10 | +def init(): |
| 11 | + """ |
| 12 | + Initialize the global model variable. |
| 13 | + This function is called once when the service starts. |
| 14 | + """ |
| 15 | + global model |
| 16 | + try: |
| 17 | + model_path = Model.get_model_path("my_model_RegressionModel") |
| 18 | + model = joblib.load(model_path) |
| 19 | + logger.info("Model loaded successfully from: %s", model_path) |
| 20 | + except Exception as e: |
| 21 | + logger.error("Failed to load model due to: %s", e) |
| 22 | + raise |
| 23 | + |
| 24 | +def run(data: dict) -> dict: |
| 25 | + """ |
| 26 | + Run scoring on the input data. |
| 27 | +
|
| 28 | + Parameters: |
| 29 | + data (dict): A dictionary containing the key "data" mapped to the input features. |
| 30 | + |
| 31 | + Returns: |
| 32 | + dict: A dictionary with key 'result' containing model predictions, |
| 33 | + or key 'error' with an error message. |
| 34 | + """ |
| 35 | + try: |
| 36 | + # Validate input |
| 37 | + if not isinstance(data, dict): |
| 38 | + raise ValueError("Input must be a dictionary with key 'data'.") |
| 39 | + raw_data = data.get("data") |
| 40 | + if raw_data is None: |
| 41 | + raise ValueError("Missing 'data' key in input.") |
| 42 | + |
| 43 | + # Convert to numpy array |
| 44 | + input_data = np.array(raw_data) |
| 45 | + logger.info("Input data converted to numpy array with shape: %s", input_data.shape) |
| 46 | + |
| 47 | + # Generate predictions |
| 48 | + predictions = model.predict(input_data) |
| 49 | + logger.info("Prediction successful.") |
| 50 | + |
| 51 | + # Return results in a structured format |
| 52 | + return {"result": predictions.tolist()} |
| 53 | + except Exception as e: |
| 54 | + logger.error("Error during run: %s", e) |
| 55 | + return {"error": str(e)} |
0 commit comments