top of page
Search
Writer's pictureWalf Sun

An AI journey with Python and SAP BTP

Build, deploy, and scale machine learning model using SAP AI Core and AI Foundation


Formulation:

  • Install the SAP AI Core SDK in Python Environment: pip install sap-ai-core-sdk

  • Set up your SAP BTP account and ensure you have access to SAP AI Core and AI Foundation.

  • Create an AI Core instance and set up the necessary service keys.


Process:

  • Authenticate with the SAP AI Core using service keys.

  • Define and train a simple example RandomForest model using scikit-learn.

  • Upload trained model to SAP AI Core, and deploy.

  • Make predictions using the deployed model.


Process attempt in Python:

import os

from sap.aicore.client import Client

from sap.aicore.ml import Model, Deployment


# Define the SAP AI Core service credentials

SERVICE_KEY = {

"clientid": "your_client_id",

"clientsecret": "your_client_secret",

"url": "https://your-ai-core-instance.cfapps.your-region.hana.ondemand.com"

}


# Authenticate and create a client instance

client = Client(

url=SERVICE_KEY["url"],

clientid=SERVICE_KEY["clientid"],

clientsecret=SERVICE_KEY["clientsecret"]

)


# Define the model you want to train and deploy

model = Model(

client=client,

name="my-ml-model",

description="Example of a machine learning model"

)


# Define the simple machine learning model using scikit-learn

from sklearn.datasets import load_iris

from sklearn.model_selection import train_test_split

from sklearn.ensemble import RandomForestClassifier

from sklearn.metrics import accuracy_score

import joblib


# Load dataset

iris = load_iris()

X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42)


# Train a RandomForest model

clf = RandomForestClassifier(n_estimators=100)

clf.fit(X_train, y_train)


# Evaluate the model

y_pred = clf.predict(X_test)

accuracy = accuracy_score(y_test, y_pred)

print(f"Model accuracy: {accuracy}")


# Save the model

joblib.dump(clf, "random_forest_model.pkl")


# Upload the model artifact to SAP AI Core

model.upload_artifact("random_forest_model.pkl")


# Deploy the model

deployment = Deployment(

client=client,

name="random-forest-deployment",

model=model

)

#Execute deployment

deployment.create()

print("Model deployed successfully!")


# Now you can make predictions using the deployed model

response = deployment.predict(X_test)

print("Predictions: ", response)


Notes:

  • Replace "your_client_id", "your_client_secret", and "url" with your actual SAP AI Core service credentials.

  • Include error handling, logging, and possibly development of more complex model training and deployment pipelines.


9 views0 comments

Comentarios


Featured Blog Post

bottom of page