SAP HANA ML Python Client (hana-ml)
Package Version: 2.22.241011
Last Verified: 2025-11-27
Table of Contents
Installation & Setup
pip install hana-ml
Requirements: Python 3.8+, SAP HANA 2.0 SPS03+ or SAP HANA Cloud
Quick Start
Connection & DataFrame
from hana_ml import ConnectionContext
# Connect
conn = ConnectionContext(
address='<hostname>',
port=443,
user='<username>',
password='<password>',
encrypt=True
)
# Create DataFrame
df = conn.table('MY_TABLE', schema='MY_SCHEMA')
print(f"Shape: {df.shape}")
df.head(10).collect()
PAL Classification
from hana_ml.algorithms.pal.unified_classification import UnifiedClassification
# Train model
clf = UnifiedClassification(func='RandomDecisionTree')
clf.fit(train_df, features=['F1', 'F2', 'F3'], label='TARGET')
# Predict & evaluate
predictions = clf.predict(test_df, features=['F1', 'F2', 'F3'])
score = clf.score(test_df, features=['F1', 'F2', 'F3'], label='TARGET')
APL AutoML
from hana_ml.algorithms.apl.classification import AutoClassifier
# Automated classification
auto_clf = AutoClassifier()
auto_clf.fit(train_df, label='TARGET')
predictions = auto_clf.predict(test_df)
Model Persistence
from hana_ml.model_storage import ModelStorage
ms = ModelStorage(conn)
clf.name = 'MY_CLASSIFIER'
ms.save_model(model=clf, if_exists='replace')
Core Libraries
PAL (Predictive Analysis Library)
- 100+ algorithms executed in-database
- Categories: Classification, Regression, Clustering, Time Series, Preprocessing
- Key classes:
UnifiedClassification, UnifiedRegression, KMeans, ARIMA
- See:
references/PAL_ALGORITHMS.md for complete list
APL (Automated Predictive Library)
- AutoML capabilities with automatic feature engineering
- Key classes:
AutoClassifier, AutoRegressor, GradientBoostingClassifier
- See:
references/APL_ALGORITHMS.md for details
DataFrames
- Lazy evaluation - builds SQL until
collect() called
- In-database processing for optimal performance
- See:
references/DATAFRAME_REFERENCE.md for complete API
Visualizers
- EDA plots, model explanations, metrics
- SHAP integration for model interpretability
- See:
references/VISUALIZERS.md for 14 visualization modules
Common Patterns
Train-Test Split
from hana_ml.algorithms.pal.partition import train_test_val_split
train, test, val = train_test_val_split(
data=df,
training_percentage=0.7,
testing_percentage=0.2,
validation_percentage=0.1
)
Feature Importance
# APL models
importance = auto_clf.get_feature_importances()
# PAL models
from hana_ml.algorithms.pal.preprocessing import FeatureSelection
fs = FeatureSelection()
fs.fit(train_df, features=features, label='TARGET')
Pipeline
from hana_ml.algorithms.pal.pipeline import Pipeline
from hana_ml.algorithms.pal.preprocessing import Imputer, FeatureNormalizer
pipeline = Pipeline([
('imputer', Imputer(strategy='mean')),
('normalizer', FeatureNormalizer()),
('classifier', UnifiedClassification(func='RandomDecisionTree'))
])
Best Practices
- Use lazy evaluation - Operations build SQL without execution until
collect()
- Leverage in-database processing - Keep data in HANA for performance
- Use Unified interfaces - Consistent APIs across algorithms
- Save models - Use
ModelStorage for persistence
- Explain predictions - Use SHAP explainers for interpretability
- Monitor AutoML - Use
PipelineProgressStatusMonitor for long-running jobs
Bundled Resources
Reference Files
references/DATAFRAME_REFERENCE.md (479 lines)
- ConnectionContext API, DataFrame operations, SQL generation
references/PAL_ALGORITHMS.md (869 lines)
- Complete PAL algorithm reference (100+ algorithms)
- Classification, Regression, Clustering, Time Series, Preprocessing
references/APL_ALGORITHMS.md (534 lines)
- AutoML capabilities, automated feature engineering
- AutoClassifier, AutoRegressor, GradientBoosting classes
references/VISUALIZERS.md (704 lines)
- 14 visualization modules (EDA, SHAP, metrics, time series)
- Plot types, configuration, export options
references/SUPPORTING_MODULES.md (626 lines)
- Model storage, spatial analytics, graph algorithms
- Text mining, statistics, error handling
Error Handling
from hana_ml.ml_exceptions import Error
try:
clf.fit(train_df, features=features, label='TARGET')
except Error as e:
print(f"HANA ML Error: {e}")
Documentation
1---2name: sap-hana-ml3description: SAP HANA Machine Learning Python Client (hana-ml) development skill. Use when: Building ML solutions with SAP HANA's in-database machine learning using Python hana-ml library for PAL/APL algorithms, DataFrame operations, AutoML, model persistence, and visualization. Keywords: hana-ml, SAP HANA, machine learning, PAL, APL, predictive analytics, HANA DataFrame, ConnectionContext, classification, regression, clustering, time series, ARIMA, gradient boosting, AutoML, SHAP, model storage4license: GPL-3.05---6
7# SAP HANA ML Python Client (hana-ml)
8
9**Package Version**: 2.22.241011
10**Last Verified**: 2025-11-27
11
12## Table of Contents
13
14- [Installation & Setup](#installation--setup)
15- [Quick Start](#quick-start)
16- [Core Libraries](#core-libraries)
17- [Common Patterns](#common-patterns)
18- [Best Practices](#best-practices)
19- [Bundled Resources](#bundled-resources)
20
21---
22
23## Installation & Setup
24
25```bash
26pip install hana-ml
27```
28
29**Requirements**: Python 3.8+, SAP HANA 2.0 SPS03+ or SAP HANA Cloud
30
31---
32
33## Quick Start
34
35### Connection & DataFrame
36
37```python
38from hana_ml import ConnectionContext
39
40# Connect
41conn = ConnectionContext(
42 address='<hostname>',
43 port=443,
44 user='<username>',
45 password='<password>',
46 encrypt=True
47)
48
49# Create DataFrame
50df = conn.table('MY_TABLE', schema='MY_SCHEMA')
51print(f"Shape: {df.shape}")
52df.head(10).collect()
53```
54
55### PAL Classification
56
57```python
58from hana_ml.algorithms.pal.unified_classification import UnifiedClassification
59
60# Train model
61clf = UnifiedClassification(func='RandomDecisionTree')
62clf.fit(train_df, features=['F1', 'F2', 'F3'], label='TARGET')
63
64# Predict & evaluate
65predictions = clf.predict(test_df, features=['F1', 'F2', 'F3'])
66score = clf.score(test_df, features=['F1', 'F2', 'F3'], label='TARGET')
67```
68
69### APL AutoML
70
71```python
72from hana_ml.algorithms.apl.classification import AutoClassifier
73
74# Automated classification
75auto_clf = AutoClassifier()
76auto_clf.fit(train_df, label='TARGET')
77predictions = auto_clf.predict(test_df)
78```
79
80### Model Persistence
81
82```python
83from hana_ml.model_storage import ModelStorage
84
85ms = ModelStorage(conn)
86clf.name = 'MY_CLASSIFIER'
87ms.save_model(model=clf, if_exists='replace')
88```
89
90---
91
92## Core Libraries
93
94### PAL (Predictive Analysis Library)
95- **100+ algorithms** executed in-database
96- Categories: Classification, Regression, Clustering, Time Series, Preprocessing
97- **Key classes**: `UnifiedClassification`, `UnifiedRegression`, `KMeans`, `ARIMA`
98- See: `references/PAL_ALGORITHMS.md` for complete list
99
100### APL (Automated Predictive Library)
101- **AutoML capabilities** with automatic feature engineering
102- **Key classes**: `AutoClassifier`, `AutoRegressor`, `GradientBoostingClassifier`
103- See: `references/APL_ALGORITHMS.md` for details
104
105### DataFrames
106- **Lazy evaluation** - builds SQL until `collect()` called
107- **In-database processing** for optimal performance
108- See: `references/DATAFRAME_REFERENCE.md` for complete API
109
110### Visualizers
111- **EDA plots**, model explanations, metrics
112- **SHAP integration** for model interpretability
113- See: `references/VISUALIZERS.md` for 14 visualization modules
114
115---
116
117## Common Patterns
118
119### Train-Test Split
120```python
121from hana_ml.algorithms.pal.partition import train_test_val_split
122
123train, test, val = train_test_val_split(
124 data=df,
125 training_percentage=0.7,
126 testing_percentage=0.2,
127 validation_percentage=0.1
128)
129```
130
131### Feature Importance
132```python
133# APL models
134importance = auto_clf.get_feature_importances()
135
136# PAL models
137from hana_ml.algorithms.pal.preprocessing import FeatureSelection
138fs = FeatureSelection()
139fs.fit(train_df, features=features, label='TARGET')
140```
141
142### Pipeline
143```python
144from hana_ml.algorithms.pal.pipeline import Pipeline
145from hana_ml.algorithms.pal.preprocessing import Imputer, FeatureNormalizer
146
147pipeline = Pipeline([
148 ('imputer', Imputer(strategy='mean')),
149 ('normalizer', FeatureNormalizer()),
150 ('classifier', UnifiedClassification(func='RandomDecisionTree'))
151])
152```
153
154---
155
156## Best Practices
157
1581. **Use lazy evaluation** - Operations build SQL without execution until `collect()`
1592. **Leverage in-database processing** - Keep data in HANA for performance
1603. **Use Unified interfaces** - Consistent APIs across algorithms
1614. **Save models** - Use `ModelStorage` for persistence
1625. **Explain predictions** - Use SHAP explainers for interpretability
1636. **Monitor AutoML** - Use `PipelineProgressStatusMonitor` for long-running jobs
164
165---
166
167## Bundled Resources
168
169### Reference Files
170- **`references/DATAFRAME_REFERENCE.md`** (479 lines)
171 - ConnectionContext API, DataFrame operations, SQL generation
172
173- **`references/PAL_ALGORITHMS.md`** (869 lines)
174 - Complete PAL algorithm reference (100+ algorithms)
175 - Classification, Regression, Clustering, Time Series, Preprocessing
176
177- **`references/APL_ALGORITHMS.md`** (534 lines)
178 - AutoML capabilities, automated feature engineering
179 - AutoClassifier, AutoRegressor, GradientBoosting classes
180
181- **`references/VISUALIZERS.md`** (704 lines)
182 - 14 visualization modules (EDA, SHAP, metrics, time series)
183 - Plot types, configuration, export options
184
185- **`references/SUPPORTING_MODULES.md`** (626 lines)
186 - Model storage, spatial analytics, graph algorithms
187 - Text mining, statistics, error handling
188
189---
190
191## Error Handling
192
193```python
194from hana_ml.ml_exceptions import Error
195
196try:
197 clf.fit(train_df, features=features, label='TARGET')
198except Error as e:
199 print(f"HANA ML Error: {e}")
200```
201
202---
203
204## Documentation
205
206- **Official Docs**: [https://help.sap.com/doc/1d0ebfe5e8dd44d09606814d83308d4b/2.0.07/en-US/hana_ml.html](https://help.sap.com/doc/1d0ebfe5e8dd44d09606814d83308d4b/2.0.07/en-US/hana_ml.html)
207- **PyPI Package**: [https://pypi.org/project/hana-ml/](https://pypi.org/project/hana-ml/)