SAP Home Learn Build Integrate Model Operate Extend with AI ConnectTutorial navigator Knowledge Graph API Devtoberfest Developer Advocates App Space

Manage my Account SAP Devs YouTube ↗ Learnings ↗ Community ↗ Provide Feedback ↗
Logout
โคข Open full site

Generate Metrics and Compare Models in SAP AI Core

Explore different ways of logging metrics during training and compare generated models.

Overview

🎓 beginner 45 min. SAP Ai CoreBeginnerArtificial IntelligenceMachine LearningSAP Ai Launchpad

You will learn

  • โœ”How to log simple metrics on validation data and training data
  • โœ”How to log step information along with metrics
  • โœ”How to log custom metrics structure
Dhrubajyoti Paul D Dhrubajyoti Paul September 11, 2025
Created by June 9, 2022
Contributors

Prerequisites

Prerequisites

  • A BTP global account If you are an SAP Developer or SAP employee, please refer to the following links ( for internal SAP stakeholders only ) - How to create a BTP Account (internal) SAP AI Core If you are an external developer or a customer or a partner kindly refer to this tutorial
  • You have an understanding of using data and generating models in SAP AI Core, from this tutorial

Steps

Intro

In this tutorial, you’ll use SAP AI Launchpad to compare two models that have been generated using SAP AI Core. This tutorial builds on the previous tutorials on house price prediction and ingesting data.

Important: Comparing models is only available using SAP AI Launchpad, and not the API endpoints. The comparison step is optional.


Step 1 Starter code
โ€”

Create a folder named hello-aicore-metrics. Within it, create a file called main.py, and paste the following starter code to this file.

Python
import os
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import KFold, train_test_split
from sklearn.inspection import permutation_importance
from datetime import datetime
import pandas as pd
from ai_core_sdk.models import Metric, MetricTag, MetricCustomInfo, MetricLabel
#
# Logging Metrics: SAP AI Core connection (Step 2)
# <PASTE CODE HERE>
#
# Variables
DATA_PATH = '/app/data/train.csv'
DT_MAX_DEPTH= int(os.getenv('DT_MAX_DEPTH'))
MODEL_PATH = '/app/model/model.pkl'
#
# Load Datasets
df = pd.read_csv(DATA_PATH)
X = df.drop('target', axis=1)
y = df['target']
#
# Metric Logging: Basic (Step 3)
# <PASTE CODE HERE>
#
# Partition into Train and test dataset
train_x, test_x, train_y, test_y = train_test_split(X, y, test_size=0.3)
#
# K-fold
kf = KFold(n_splits=5, random_state=31, shuffle=True)
i = 0 # storing step count
for train_index, val_index in kf.split(train_x):
    i += 1
    # Train model on subset
    clf = DecisionTreeRegressor(max_depth=DT_MAX_DEPTH, random_state=31)
    clf.fit(train_x.iloc[train_index], train_y.iloc[train_index])
    # Score on validation data (hold-out dataset)
    val_step_r2 = clf.score(train_x.iloc[val_index], train_y.iloc[val_index])
    # Metric Logging: Step Information (Step 4)
    # <PASTE CODE HERE>
    # Delete step model
    del(clf)
#
# Final Model
clf = DecisionTreeRegressor(max_depth=DT_MAX_DEPTH, random_state=31)
clf.fit(train_x, train_y)
# Scoring over test data
test_r2_score = clf.score(test_x, test_y)
# Metric Logging: Attaching to metrics to generated model (Step 5)
# <PASTE CODE HERE>
#
# Model Explaination
r = permutation_importance(
    clf, test_x, test_y,
    n_repeats=30,
    random_state=0
)
# Feature importances
feature_importances = str('')
for i in r.importances_mean.argsort()[::-1]:
    feature_importances += f"{df.columns[i]}: {r.importances_mean[i]:.3f} +/- {r.importances_std[i]:.3f} \n"
# Metric Logging: Custom Structure (Step 6)
# <PASTE CODE HERE>
#
# Save model
import pickle
pickle.dump(clf, open(MODEL_PATH, 'wb'))
#
# Metric Logging: Tagging the execution (Step 7)
# <PASTE CODE HERE>

The snippet includes some placeholders that state # &lt;PASTE CODE HERE&gt;. You’ll complete these entries throughout the tutorial. For clarity, the comments in the code also include the relevant step number.

This Python script contains all of the modifications needed for logging metrics, meaning that you can leave your previous workflows as they are.

Step 2 Add connection
+
Step 3 Add basic metric logging
+
Step 4 Step information
+
Step 5 Attach metrics to generated model
+
Step 6 Custom metrics for model inspection
+
Step 7 Add tags for execution meta after training
+
Step 8 Complete files
+
Step 9 Create configuration and execution
+
Step 10 Retrieve metrics
+
Step 11 Compare metrics (optional)
+

Resources

Discussion

Share feedback on this tutorial or join the conversation in SAP Community.

Submit detailed feedback Discuss in Community
Steps
Step 1 of 11
1. Starter code 2. Add connection 3. Add basic metric logging 4. Step information 5. Attach metrics to generated model 6. Custom metrics for model inspection 7. Add tags for execution meta after training 8. Complete files 9. Create configuration and execution 10. Retrieve metrics 11. Compare metrics (optional)

Learn more →