API Reference
ModelSpec
dataclass
Specification for a model registered in TanML.
Attributes:
| Name | Type | Description |
|---|---|---|
task |
Task
|
Either 'classification' or 'regression'. |
import_path |
str
|
Fully qualified path to the estimator class. |
defaults |
dict[str, Any]
|
Default hyperparameters for the estimator. |
ui_schema |
dict[str, tuple[str, tuple[Any, ...] | None, str | None]]
|
Metadata for rendering parameter inputs in the UI. |
aliases |
dict[str, str]
|
Mapping of UI parameter names to estimator-specific names. |
Source code in tanml/models/registry.py
build_estimator(library, algo, params=None)
Factory function to create a scikit-learn compatible estimator instance.
This is the primary entry point for programmatic model creation in TanML. It resolves the requested model from the internal registry, applies sane defaults for the specific task, and overrides them with any user-provided parameters.
Supported Libraries
sklearn: LogisticRegression, RandomForestClassifier, SVC, OLS, etc.xgboost: XGBClassifier, XGBRegressor.lightgbm: LGBMClassifier, LGBMRegressor.catboost: CatBoostClassifier, CatBoostRegressor.statsmodels: Logit, OLS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
library
|
str
|
The library containing the model (e.g., 'sklearn', 'xgboost'). |
required |
algo
|
str
|
The specific algorithm class name (e.g., 'RandomForestClassifier'). |
required |
params
|
dict[str, Any] | None
|
Optional dictionary of hyperparameters to override the pre-configured TanML defaults. |
None
|
Returns:
| Type | Description |
|---|---|
|
An initialized estimator object. For most libraries, this is a |
|
|
standard scikit-learn compatible object. For |
|
|
is a wrapped instance that supports the |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the library/algo combination is not in the registry. |
ImportError
|
If the underlying library (e.g., xgboost) is not installed. |
Example
Create a Random Forest with custom depth:
from tanml.models.registry import build_estimator model = build_estimator( ... library="sklearn", ... algo="RandomForestClassifier", ... params={"max_depth": 5} ... ) print(model.max_depth) 5
Source code in tanml/models/registry.py
list_models(task=None)
List all registered models in the TanML ecosystem.
This function returns the metadata specifications for all models that the system is capable of building and validating.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
Task | None
|
Optional filter. Use 'classification' for classifiers, 'regression' for regressors, or None for the full registry. |
None
|
Returns:
| Type | Description |
|---|---|
dict[tuple[str, str], ModelSpec]
|
A dictionary where:
- Keys: (library_name, algorithm_name) strings, e.g., ("sklearn", "RandomForestClassifier").
- Values: A |
Source code in tanml/models/registry.py
get_spec(library, algo)
Retrieve the ModelSpec for a specific library and algorithm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
library
|
str
|
e.g., 'sklearn', 'xgboost'. |
required |
algo
|
str
|
e.g., 'RandomForestClassifier'. |
required |
Returns:
| Type | Description |
|---|---|
ModelSpec
|
The matched ModelSpec instance. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the library/algorithm combination is not registered. |
Source code in tanml/models/registry.py
Feature drift analysis module for internal and external validation.
This module provides statistical tools to detect whether the distribution of machine learning features has changed between two points in time or between two datasets (e.g., Training vs. Serving).
Key Metrics
- PSI (Population Stability Index): A single number indicating the magnitude of the shift.
- KS Test (Kolmogorov-Smirnov): A non-parametric test to determine if two samples come from different distributions.
Example
import pandas as pd from tanml.analysis.drift import analyze_drift
Compare Training and Serving data
results = analyze_drift(train_df, serving_df) for col, metrics in results.items(): ... if metrics["has_drift"]: ... print(f"Drift detected in {col}: PSI={metrics['psi']:.3f}")
calculate_psi(expected, actual, bins=10)
Calculate Population Stability Index (PSI) between two distributions.
PSI measures how much a distribution has shifted. Thresholds: - PSI < 0.1: No significant shift - 0.1 <= PSI < 0.2: Moderate shift (investigate) - PSI >= 0.2: Large shift (action needed)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expected
|
Series
|
Expected/baseline distribution (e.g., training data) |
required |
actual
|
Series
|
Actual/new distribution (e.g., test data) |
required |
bins
|
int
|
Number of bins for discretization |
10
|
Returns:
| Type | Description |
|---|---|
float
|
PSI value (float) |
Source code in tanml/analysis/drift.py
calculate_ks(expected, actual)
Calculate Kolmogorov-Smirnov statistic between two distributions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expected
|
Series
|
Expected/baseline distribution |
required |
actual
|
Series
|
Actual/new distribution |
required |
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Tuple of (KS statistic, p-value) |
Source code in tanml/analysis/drift.py
analyze_drift(train_df, test_df, numeric_cols=None, psi_threshold=0.1, ks_threshold=0.05)
Perform a comprehensive drift analysis on all continuous features.
This function iterates through the numeric columns, calculates both PSI and KS statistics, and flags features that exceed regulatory or statistical thresholds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_df
|
DataFrame
|
The baseline/reference dataset (e.g., historical training data). |
required |
test_df
|
DataFrame
|
The target dataset to check for drift (e.g., current production batch). |
required |
numeric_cols
|
list[str] | None
|
List of columns to analyze. If None, all numeric columns common to both datasets will be checked. |
None
|
psi_threshold
|
float
|
The PSI value above which drift is considered "moderate". Default is 0.1. |
0.1
|
ks_threshold
|
float
|
The p-value below which the KS test is considered statistically significant (identifying a difference). Default is 0.05. |
0.05
|
Returns:
| Type | Description |
|---|---|
dict[str, dict[str, Any]]
|
A dictionary mapping column names to their drift metadata:
- |
Source code in tanml/analysis/drift.py
Feature correlation and VIF analysis module.
Provides correlation matrix calculation and Variance Inflation Factor (VIF) for detecting multicollinearity.
Example
from tanml.analysis.correlation import calculate_vif, calculate_correlation_matrix
corr_matrix = calculate_correlation_matrix(df, method="pearson") vif_results = calculate_vif(df, features=["age", "income", "score"])
calculate_correlation_matrix(df, method='pearson', numeric_only=True)
Calculate correlation matrix for numeric features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input DataFrame |
required |
method
|
str
|
Correlation method ("pearson", "spearman", or "kendall") |
'pearson'
|
numeric_only
|
bool
|
Whether to include only numeric columns |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Correlation matrix as DataFrame |
Source code in tanml/analysis/correlation.py
find_highly_correlated_pairs(corr_matrix, threshold=0.8)
Find pairs of features with high correlation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corr_matrix
|
DataFrame
|
Correlation matrix |
required |
threshold
|
float
|
Absolute correlation threshold |
0.8
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of dictionaries with correlated pairs |
Source code in tanml/analysis/correlation.py
calculate_vif(df, features=None, threshold=5.0)
Calculate Variance Inflation Factor (VIF) for features.
VIF measures how much the variance of a regression coefficient is inflated due to multicollinearity. Thresholds: - VIF < 5: Low multicollinearity - 5 <= VIF < 10: Moderate multicollinearity - VIF >= 10: High multicollinearity
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input DataFrame |
required |
features
|
list[str] | None
|
List of features to analyze (auto-detected if None) |
None
|
threshold
|
float
|
VIF threshold for flagging |
5.0
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with VIF values and flagged features |
Source code in tanml/analysis/correlation.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | |
analyze_feature_relationships(df, features=None, corr_method='pearson', corr_threshold=0.8, vif_threshold=5.0)
Comprehensive feature relationship analysis.
Combines correlation and VIF analysis for a complete picture of feature relationships.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input DataFrame |
required |
features
|
list[str] | None
|
List of features to analyze |
None
|
corr_method
|
str
|
Correlation method |
'pearson'
|
corr_threshold
|
float
|
Threshold for flagging high correlations |
0.8
|
vif_threshold
|
float
|
Threshold for flagging high VIF |
5.0
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Combined analysis results |
Source code in tanml/analysis/correlation.py
Input cluster coverage analysis module.
Analyzes whether test data falls within the same input space as training data using clustering techniques.
Example
from tanml.analysis.clustering import analyze_cluster_coverage
coverage = analyze_cluster_coverage( X_train=train_features, X_test=test_features, n_clusters=5, )
print(f"Coverage: {coverage['coverage_pct']:.1f}%")
analyze_cluster_coverage(X_train, X_test, n_clusters=5, max_k=10, auto_select_k=False)
Analyze how well test data is covered by training data clusters.
This check identifies whether test samples fall into regions of the input space that were seen during training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_train
|
DataFrame
|
Training features |
required |
X_test
|
DataFrame
|
Test features |
required |
n_clusters
|
int
|
Number of clusters (if auto_select_k=False) |
5
|
max_k
|
int
|
Maximum clusters to try (if auto_select_k=True) |
10
|
auto_select_k
|
bool
|
Whether to auto-select optimal k using elbow method |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with: - coverage_pct: Percentage of test samples in training clusters - cluster_distribution: Test samples per cluster - uncovered_indices: Indices of uncovered test samples - n_clusters: Actual number of clusters used - pca_coords: 2D PCA coordinates for visualization |
Source code in tanml/analysis/clustering.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | |
StressTestCheck
Task-aware stress test
- Classification: accuracy, auc, delta_accuracy, delta_auc
- Regression: rmse, r2, delta_rmse, delta_r2
For each numeric feature, perturb a random subset of rows by (1 ± epsilon).
Source code in tanml/checks/stress_test.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | |
SHAPCheck
Bases: BaseCheck
SHAP for regression + binary classification (no multiclass).
Config under rule_config["explainability"]["shap"]: - enabled: bool (default True, also checked under rule_config["SHAPCheck"]["enabled"]) - task: "auto" | "classification" | "regression" (default "auto") - algorithm: "auto" | "tree" | "linear" | "kernel" | "permutation" (default "auto") - model_output: "auto" | "raw" | "log_odds" | "probability" (tree-only hint; default "auto") - background_strategy: "sample" | "kmeans" (default "sample") - background_sample_size: int (default 100) - test_sample_size: int (default 200) - max_display: int (default 20) - seed: int (default 42) - out_dir: str (optional) (preferred save folder)
Source code in tanml/checks/explainability/shap_check.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | |