Python library
Python reference
Generated from yhatlabs 0.2.2. Each page of these docs explains a task with examples; this page lists what exists.
Client()
Section titled “Client()”Client(api_key: Optional[str] = None, *, base_url: Optional[str] = None, timeout: float = 300.0, max_retries: int = 3, max_concurrency: int = 4, limits: Optional[Limits] = None, http_client: Optional[httpx.Client] = None, mask_columns: bool = False)| Parameter | Type | Required / default | Description |
|---|---|---|---|
api_key |
Optional[str] | optional | Your key. Default: the YHAT_API_KEY environment variable. |
base_url |
Optional[str] | optional | The API’s address. Default: YHAT_BASE_URL, else https://api.yhatlabs.com. |
timeout |
float | 300.0 |
Seconds per request. |
max_retries |
int | 3 |
Retries of timeouts, connection errors and 408 / 409 / 429 / 5xx replies, with backoff. |
max_concurrency |
int | 4 |
Requests sent in parallel when a large input is split. |
limits |
Optional[Limits] | optional | Request caps to split batches by; read from GET /v1/limits on first use when left out. |
http_client |
Optional[httpx.Client] | optional | An httpx.Client to send requests with (proxies, custom transports). |
mask_columns |
bool | False |
Send every column name as c0, c1, … instead of its own; results come back under your names. Values, category labels and series ids are sent as they are. Each call can override it. |
Client
Section titled “Client”Synchronous client for the YHat Labs prediction API.
from yhatlabs import Client yh = Client() # reads YHAT_API_KEY (and YHAT_BASE_URL, if set) fc = yh.forecast(df, h=24) # df: unique_id, ds, y (+ covariates) m = yh.fit(train, “churn”) # tabular: fit once, then m.predict(rows) as often as you like
forecast
Section titled “forecast”forecast(data: Any, h: int, *, model: str = chakra-ts, quantiles: Any = None, level: Optional[Sequence[float]] = None, mean: bool = False, freq: Optional[str] = None, id_col: Optional[str] = None, time_col: Optional[str] = None, target_col: Target = None, known: Cols = None, past: Cols = None, static: Cols = None, future: Optional[pd.DataFrame] = None, season: Optional[int] = None, on_error: str = raise, calendar: Calendar = None, samples: Optional[int] = None, seed: Optional[int] = None, history: bool = False, mask_columns: Optional[bool] = None, store: Optional[bool] = None, preset: Optional[str] = None, tune: Any = None) -> ForecastResultForecast the next h steps of every series in data.
data: long DataFrame (id, timestamp, target[s], covariates), a Series with a DatetimeIndex, an array, or a dict of arrays
(arrays need freq=). quantiles: any levels in (0, 1) (default 0.1, 0.5, 0.9) or “all”; or level=[80] for central intervals.
mean=True adds a mean column next to the median (the point forecast), computed from the native quantiles and listed in
result.derived; use it when the quantity is summed later (totals over time or series), where the median is biased.
known: columns whose future values you know (pass them in future, see yhatlabs.features.make_future); past: history-only
columns; static: per-series constants (region, store size). on_error=“warn” returns the series that succeeded when some
batches fail (failures in result.errors). calendar=True adds hour / weekday / month / weekend as known covariates, with
no future= needed for them ({“holidays”: “US”} adds a holiday flag).
| Parameter | Type | Required / default | Description |
|---|---|---|---|
data |
Any | required | The history: a long table with an id column, a time column and the target (pandas, polars, Spark, Dask or Ray), a Series with a DatetimeIndex, a numpy array (one series per row), or a dict of arrays. Arrays need freq=. |
h |
int | required | How many steps to forecast, at the series’ own frequency. |
model |
str | 'chakra-ts' |
The model name, as GET /v1/models lists it. |
quantiles |
Any | optional | Quantile levels in (0, 1), e.g. [0.1, 0.5, 0.9], or “all” for every level the model produces. Default [0.1, 0.5, 0.9]. |
level |
Optional[Sequence[float]] | optional | Central intervals by width in percent, e.g. [80, 95]; the alternative to quantiles=. |
mean |
bool | False |
Add a mean column next to the median, computed from the quantiles (for forecasts summed later). |
freq |
Optional[str] | optional | The series’ frequency as a pandas alias (h, D, W-SUN, MS, 15min, …). Inferred from the timestamps when left out; required for arrays and integer time steps. |
id_col |
Optional[str] | optional | The column naming each series. Default: unique_id, id, item_id or series_id if present, else one series. |
time_col |
Optional[str] | optional | The timestamp column. Default: ds, timestamp, time, date or datetime if present. |
target_col |
Target | optional | The column (or list of columns) to forecast. Default: y, target or value if present, else the one numeric column. |
known |
Cols | optional | Covariate columns whose future values you know (prices, weather forecasts, holidays); their future values go in future=. |
past |
Cols | optional | Covariate columns known only up to now (observed loads, sensor readings). |
static |
Cols | optional | Columns that are constant per series (region, store size). |
future |
Optional[pd.DataFrame] | optional | The known covariates over the next h steps: id, time and the known columns. |
season |
Optional[int] | optional | The seasonal period in steps (24 for daily cycles of hourly data), to fix it instead of inferring it from freq. |
on_error |
str | 'raise' |
“raise” (default): the first failed batch raises. “warn”: return the series that succeeded; failures in result.errors. |
calendar |
Calendar | optional | True adds hour, weekday, month and weekend as known covariates (no future= needed for them); {“holidays”: “US”} also adds a holiday flag. |
samples |
Optional[int] | optional | Return this many sample paths per series (1 to 1000) in result.samples. |
seed |
Optional[int] | optional | Random seed for the sample paths. |
history |
bool | False |
Also return the model’s forecasts of the windows just before the forecast (result.history). |
mask_columns |
Optional[bool] | optional | Send target and covariate names as c0, c1, …; the result keeps your names. Default: the client’s setting (False). |
store |
Optional[bool] | optional | False: the call isn’t shown in your Logs (see the data-handling page in the docs). |
preset |
Optional[str] | optional | “fast” (default) or “pro”: slower and slightly sharper, on models that offer presets. |
tune |
Any | optional | A Tuned (or its id) from Client.tune(): forecast with the model tuned on your series. When the tune did not beat the zero-shot model on your latest window (tuned.used is False), this is the zero-shot forecast. |
tune(data: Any, h: int, *, model: str = chakra-ts, steps: int = 300, name: Optional[str] = None, ttl_days: Optional[float] = None, freq: Optional[str] = None, id_col: Optional[str] = None, time_col: Optional[str] = None, target_col: Target = None, known: Cols = None, past: Cols = None, static: Cols = None, future: Optional[pd.DataFrame] = None, season: Optional[int] = None, calendar: Calendar = None, background: bool = False, store: Optional[bool] = None) -> Union[Tuned, Job]Fine-tune the time-series model on your series, so later forecasts use what it learned from them (paydays, promotions, your own seasonality). Runs in the background on our side, a few minutes; returns a Tuned (or its Job with background=True).
The tune trains on all but the last h steps of every series and scores itself there against the zero-shot model:
tuned.used says whether it won, tuned.holdout has the numbers, and a tune that did not win forecasts like the zero-shot
model. Then: tuned.forecast(data) or client.forecast(data, h, tune=tuned). Numeric known covariates (with their
future values in future) are part of the tuning; the series need at least 2 x h + 64 values.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
data |
Any | required | The history, as for forecast(): a long table (id, time, target, covariates), a Series, an array or a dict. |
h |
int | required | The horizon the tune is for (and scored on). |
model |
str | 'chakra-ts' |
The time-series model to tune. |
steps |
int | 300 |
Training steps, 50 to 1000 (default 300); the best count is chosen on the holdout. |
name |
Optional[str] | optional | A label for the tune. |
ttl_days |
Optional[float] | optional | How long the tune is kept after its last use (default 30, at most 365). |
freq |
Optional[str] | optional | The series’ frequency as a pandas alias; inferred from the timestamps when left out. |
id_col |
Optional[str] | optional | The column naming each series. |
time_col |
Optional[str] | optional | The timestamp column. |
target_col |
Target | optional | The column (or columns) to forecast. |
known |
Cols | optional | Covariate columns whose future values you know; their next h values go in future=. |
past |
Cols | optional | Covariate columns known only up to now. |
static |
Cols | optional | Columns constant per series. |
future |
Optional[pd.DataFrame] | optional | The known covariates over the next h steps. |
season |
Optional[int] | optional | The seasonal period in steps, to fix it instead of inferring it from freq. |
calendar |
Calendar | optional | True adds hour, weekday, month and weekend as known covariates. |
background |
bool | False |
Return the Job at once; job.wait() gives the Tuned. |
store |
Optional[bool] | optional | False: the call isn’t shown in your Logs. |
evaluate
Section titled “evaluate”evaluate(data: Any, h: int, *, windows: int = 3, step: Optional[int] = None, models: Sequence[str] = (chakra-ts,), baselines: Sequence[str] = (seasonal_naive,), metrics: Sequence[str] = (mase, sql, wql, mae, rmse, coverage@0.8), compare: Optional[Dict[str, pd.DataFrame]] = None, season: Optional[int] = None, freq: Optional[str] = None, id_col: Optional[str] = None, time_col: Optional[str] = None, target_col: Target = None, known: Cols = None, past: Cols = None, static: Cols = None, calendar: Calendar = None, mask_columns: Optional[bool] = None) -> EvaluationResultRolling-origin backtest: windows cutoffs step apart (default h) at the end of each series, each forecast h ahead and
scored against the actuals. Known covariates are read from data itself. compare: your own forecasts to score alongside,
{“current”: df} with id, time and quantile columns (median, q10, …) or a point column ‘forecast’. The summary gives
skill against the first baseline (1 - geometric-mean error ratio; > 0 beats it).
| Parameter | Type | Required / default | Description |
|---|---|---|---|
data |
Any | required | The history: a long table with an id column, a time column and the target (pandas, polars, Spark, Dask or Ray), a Series with a DatetimeIndex, a numpy array (one series per row), or a dict of arrays. Arrays need freq=. |
h |
int | required | How many steps to forecast, at the series’ own frequency. |
windows |
int | 3 |
How many backtest windows, ending at the end of each series. |
step |
Optional[int] | optional | Steps between window cutoffs. Default: h (windows do not overlap). |
models |
Sequence[str] | ('chakra-ts',) |
The models to score. |
baselines |
Sequence[str] | ('seasonal_naive',) |
Simple forecasts to score against: seasonal_naive (repeats the last season: a week for daily data, a day for hourly; the last value when the history is shorter than two seasons) and naive (repeats the last value). |
metrics |
Sequence[str] | ('mase', 'sql', 'wql', 'mae', 'rmse', 'coverage@0.8') |
Scores to compute per window: mase, sql, wql, mae, rmse, coverage@<level>. |
compare |
Optional[Dict[str, pd.DataFrame]] | optional | Your own forecasts to score on the same windows: {name: table with the time (and id) column and quantile columns, or a forecast column}. |
season |
Optional[int] | optional | The seasonal period in steps (24 for daily cycles of hourly data), to fix it instead of inferring it from freq. |
freq |
Optional[str] | optional | The series’ frequency as a pandas alias (h, D, W-SUN, MS, 15min, …). Inferred from the timestamps when left out; required for arrays and integer time steps. |
id_col |
Optional[str] | optional | The column naming each series. Default: unique_id, id, item_id or series_id if present, else one series. |
time_col |
Optional[str] | optional | The timestamp column. Default: ds, timestamp, time, date or datetime if present. |
target_col |
Target | optional | The column (or list of columns) to forecast. Default: y, target or value if present, else the one numeric column. |
known |
Cols | optional | Covariate columns whose future values you know (prices, weather forecasts, holidays); their future values go in future=. |
past |
Cols | optional | Covariate columns known only up to now (observed loads, sensor readings). |
static |
Cols | optional | Columns that are constant per series (region, store size). |
calendar |
Calendar | optional | True adds hour, weekday, month and weekend as known covariates (no future= needed for them); {“holidays”: “US”} also adds a holiday flag. |
mask_columns |
Optional[bool] | optional | Send target and covariate names as c0, c1, …; results keep your names. Default: the client’s setting (False). |
scenarios
Section titled “scenarios”scenarios(data: Any, h: int, futures: Dict[str, pd.DataFrame], *, known: Sequence[str], model: str = chakra-ts, quantiles: Any = None, level: Optional[Sequence[float]] = None, **kw: Any) -> pd.DataFrameWhat-if: one forecast per scenario of the known covariates (e.g. {“base”: future, “price +10%”: future_up}), stacked
with a scenario column so the outcomes compare side by side.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
data |
Any | required | The history: a long table with an id column, a time column and the target (pandas, polars, Spark, Dask or Ray), a Series with a DatetimeIndex, a numpy array (one series per row), or a dict of arrays. Arrays need freq=. |
h |
int | required | How many steps to forecast, at the series’ own frequency. |
futures |
Dict[str, pd.DataFrame] | required | {scenario name: future table of the known covariates}, one table per scenario. |
known |
Sequence[str] | required | The covariate columns the scenarios set. |
model |
str | 'chakra-ts' |
The model name, as GET /v1/models lists it. |
quantiles |
Any | optional | Quantile levels in (0, 1), e.g. [0.1, 0.5, 0.9], or “all” for every level the model produces. Default [0.1, 0.5, 0.9]. |
level |
Optional[Sequence[float]] | optional | Central intervals by width in percent, e.g. [80, 95]; the alternative to quantiles=. |
**kwargs |
Any | optional | Any other forecast() option (id_col, time_col, freq, past, static, mask_columns, …). |
explain_forecast
Section titled “explain_forecast”explain_forecast(data: Any, h: int, *, known: Cols = None, past: Cols = None, future: Optional[pd.DataFrame] = None, model: str = chakra-ts, freq: Optional[str] = None, id_col: Optional[str] = None, time_col: Optional[str] = None, target_col: Target = None, static: Cols = None, season: Optional[int] = None, calendar: Calendar = None, mask_columns: Optional[bool] = None) -> pd.DataFrameHow much each covariate moves the forecast: forecasts once with every covariate, then once per covariate with it set to a neutral value (numbers: the series’ mean over the history and the future; categories and flags: their most common value). Costs one forecast plus one more per covariate in known and past.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
data |
Any | required | The history: a long table with an id column, a time column, the target and the covariates. |
h |
int | required | How many steps to forecast, at the series’ own frequency. |
known |
Cols | optional | The known covariates to explain (their future values in future=, or in the same table). |
past |
Cols | optional | The past covariates to explain. |
future |
Optional[pd.DataFrame] | optional | The known covariates over the next h steps: id, time and the known columns. |
model |
str | 'chakra-ts' |
The model name, as GET /v1/models lists it. |
freq |
Optional[str] | optional | The series’ frequency as a pandas alias (h, D, W-SUN, MS, 15min, …). Inferred from the timestamps when left out; required for arrays and integer time steps. |
id_col |
Optional[str] | optional | The column naming each series. Default: unique_id, id, item_id or series_id if present, else one series. |
time_col |
Optional[str] | optional | The timestamp column. Default: ds, timestamp, time, date or datetime if present. |
target_col |
Target | optional | The column (or list of columns) to forecast. Default: y, target or value if present, else the one numeric column. |
static |
Cols | optional | Columns that are constant per series (used in every forecast, not explained). |
season |
Optional[int] | optional | The seasonal period in steps (24 for daily cycles of hourly data), to fix it instead of inferring it from freq. |
calendar |
Calendar | optional | True adds hour, weekday, month and weekend as known covariates (used in every forecast, not explained). |
mask_columns |
Optional[bool] | optional | Send target and covariate names as c0, c1, …; results keep your names. Default: the client’s setting (False). |
detect_anomalies
Section titled “detect_anomalies”detect_anomalies(data: Any, *, h: Optional[int] = None, windows: int = 5, threshold: float = 3.0, model: str = chakra-ts, freq: Optional[str] = None, id_col: Optional[str] = None, time_col: Optional[str] = None, target_col: Target = None, known: Cols = None, past: Cols = None, static: Cols = None, season: Optional[int] = None, calendar: Calendar = None, mask_columns: Optional[bool] = None) -> pd.DataFrameScores the last windows x h points of each series against forecasts made from the history before each window.
score = (actual - median) / the forecast’s own spread; |score| > threshold marks anomaly. h defaults to one season.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
data |
Any | required | The history: a long table with an id column, a time column and the target (pandas, polars, Spark, Dask or Ray), a Series with a DatetimeIndex, a numpy array (one series per row), or a dict of arrays. Arrays need freq=. |
h |
Optional[int] | optional | Points scored per window. Default: max(season, 8). |
windows |
int | 5 |
How many windows back from the end are scored. |
threshold |
float | 3.0 |
Score above which a point is flagged (its distance from the forecast, in units of the forecast’s spread). |
model |
str | 'chakra-ts' |
The model name, as GET /v1/models lists it. |
freq |
Optional[str] | optional | The series’ frequency as a pandas alias (h, D, W-SUN, MS, 15min, …). Inferred from the timestamps when left out; required for arrays and integer time steps. |
id_col |
Optional[str] | optional | The column naming each series. Default: unique_id, id, item_id or series_id if present, else one series. |
time_col |
Optional[str] | optional | The timestamp column. Default: ds, timestamp, time, date or datetime if present. |
target_col |
Target | optional | The column (or list of columns) to forecast. Default: y, target or value if present, else the one numeric column. |
known |
Cols | optional | Covariate columns whose future values you know (prices, weather forecasts, holidays); their future values go in future=. |
past |
Cols | optional | Covariate columns known only up to now (observed loads, sensor readings). |
static |
Cols | optional | Columns that are constant per series (region, store size). |
season |
Optional[int] | optional | The seasonal period in steps (24 for daily cycles of hourly data), to fix it instead of inferring it from freq. |
calendar |
Calendar | optional | True adds hour, weekday, month and weekend as known covariates (no future= needed for them); {“holidays”: “US”} also adds a holiday flag. |
mask_columns |
Optional[bool] | optional | Send target and covariate names as c0, c1, …; results keep your names. Default: the client’s setting (False). |
anomaly_stream
Section titled “anomaly_stream”anomaly_stream(*, window: int = 512, threshold: float = 3.0, model: str = chakra-ts, freq: Optional[str] = None, id_col: Optional[str] = None, time_col: Optional[str] = None, target_col: Target = None, known: Cols = None, past: Cols = None, static: Cols = None, season: Optional[int] = None, calendar: Calendar = None, mask_columns: Optional[bool] = None) -> _anomaly.AnomalyStreamAnomaly detection on points as they arrive: stream.update(new_points) scores only the new points, against forecasts
from the recent history before them, and keeps the last window points of every series for the next update. Each
update is one detect_anomalies call (on the kept history plus the new points), whatever the number of series.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
window |
int | 512 |
Points kept per series as history for the next update. |
threshold |
float | 3.0 |
Score above which a point is flagged (its distance from the forecast, in units of the forecast’s spread). |
model |
str | 'chakra-ts' |
The model name, as GET /v1/models lists it. |
freq |
Optional[str] | optional | The series’ frequency as a pandas alias (h, D, W-SUN, MS, 15min, …). Inferred from the timestamps when left out; required for arrays and integer time steps. |
id_col |
Optional[str] | optional | The column naming each series. Default: unique_id, id, item_id or series_id if present, else one series. |
time_col |
Optional[str] | optional | The timestamp column. Default: ds, timestamp, time, date or datetime if present. |
target_col |
Target | optional | The column (or list of columns) to forecast. Default: y, target or value if present, else the one numeric column. |
known |
Cols | optional | Covariate columns whose future values you know, sent with each update’s points. |
past |
Cols | optional | Covariate columns known only up to now, sent with each update’s points. |
static |
Cols | optional | Columns that are constant per series (region, store size). |
season |
Optional[int] | optional | The seasonal period in steps (24 for daily cycles of hourly data), to fix it instead of inferring it from freq. |
calendar |
Calendar | optional | True adds hour, weekday, month and weekend as known covariates; {“holidays”: “US”} also adds a holiday flag. |
mask_columns |
Optional[bool] | optional | Send target and covariate names as c0, c1, …; results keep your names. Default: the client’s setting (False). |
fill_gaps
Section titled “fill_gaps”fill_gaps(data: Any, *, max_gap: Optional[int] = None, model: str = chakra-ts, freq: Optional[str] = None, id_col: Optional[str] = None, time_col: Optional[str] = None, target_col: Target = None, known: Cols = None, past: Cols = None, static: Cols = None, season: Optional[int] = None, mask_columns: Optional[bool] = None) -> pd.DataFrameFills missing values (and missing timestamps) inside each series with the median forecast from the history before the
gap. Returns the regular grid: id, time, targets, and a <target>_filled flag per target.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
data |
Any | required | The history: a long table with an id column, a time column and the target (pandas, polars, Spark, Dask or Ray), a Series with a DatetimeIndex, a numpy array (one series per row), or a dict of arrays. Arrays need freq=. |
max_gap |
Optional[int] | optional | Longest run of missing points to fill. Default: the API’s maximum horizon. |
model |
str | 'chakra-ts' |
The model name, as GET /v1/models lists it. |
freq |
Optional[str] | optional | The series’ frequency as a pandas alias (h, D, W-SUN, MS, 15min, …). Inferred from the timestamps when left out; required for arrays and integer time steps. |
id_col |
Optional[str] | optional | The column naming each series. Default: unique_id, id, item_id or series_id if present, else one series. |
time_col |
Optional[str] | optional | The timestamp column. Default: ds, timestamp, time, date or datetime if present. |
target_col |
Target | optional | The column (or list of columns) to forecast. Default: y, target or value if present, else the one numeric column. |
known |
Cols | optional | Covariate columns whose future values you know (prices, weather forecasts, holidays); their future values go in future=. |
past |
Cols | optional | Covariate columns known only up to now (observed loads, sensor readings). |
static |
Cols | optional | Columns that are constant per series (region, store size). |
season |
Optional[int] | optional | The seasonal period in steps (24 for daily cycles of hourly data), to fix it instead of inferring it from freq. |
mask_columns |
Optional[bool] | optional | Send target and covariate names as c0, c1, …; results keep your names. Default: the client’s setting (False). |
predict
Section titled “predict”predict(train: Any, target: str, test: Any = None, *, model: str = chakra-tab, task: Optional[str] = None, preset: Optional[str] = None, eval_metric: Optional[str] = None, time_limit: Optional[float] = None, quantiles: Any = None, seed: Optional[int] = None, groups: Optional[str] = None, time_col: Optional[str] = None, set_coverage: Optional[float] = None, compare: Any = None, store: Optional[bool] = None, background: bool = False, _refs: Optional[Dict[str, dict]] = None, mask_columns: Optional[bool] = None, _mask: Optional[Mask] = None) -> Union[PredictionResult, Job]Fit on train and predict test in one call (to predict again from the same fit, use fit()).
Without test=, the rows of train whose target is missing are predicted.
task: “classify”, “regress” or None to let the server infer it. Pass it for integer targets: a rating from 1 to 5 or a
small count may otherwise be inferred as classification.
preset: “fast” (the default: one holdout split), “medium” (3-fold bagging, about 3x slower and more accurate) or “pro”
(8-fold bagging, the most accurate). eval_metric: what validation optimises, e.g. log_loss (default), roc_auc, f1; rmse
(default), mae, r2 for regression. It does not change the decision rule. quantiles: regression prediction intervals,
e.g. [0.05, 0.5, 0.95], from each row’s own predictive distribution. time_limit: seconds for the whole call. seed: the
server uses 0 when omitted, so results are already reproducible.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
train |
Any | required | The training table: one row per example, the target column included. |
target |
str | required | The column to predict. |
test |
Any | optional | The rows to predict, with the same feature columns as train. Without it, the rows of train whose target is empty are predicted. |
model |
str | 'chakra-tab' |
The model name, as GET /v1/models lists it. |
task |
Optional[str] | optional | “classify”, “regress”, or None to let the server infer it. Pass it for integer targets (a 1-5 rating could be either). |
preset |
Optional[str] | optional | “fast” (default: one holdout split, the quickest), “medium” (3-fold bagging, about 3x the time) or “pro” (8-fold bagging, the most accurate; “full” is the same). |
eval_metric |
Optional[str] | optional | What validation optimises: log_loss (default), roc_auc, f1, … for classification; rmse (default), mae, r2 for regression. |
time_limit |
Optional[float] | optional | Seconds for the whole call. |
quantiles |
Any | optional | Regression: interval levels in (0, 1), e.g. [0.05, 0.5, 0.95], up to 32. |
seed |
Optional[int] | optional | Random seed; the server uses 0 when it is left out, so results are reproducible. |
groups |
Optional[str] | optional | A column whose rows belong together (machine, batch, patient, store): validation folds hold out whole groups, so intervals hold for groups the model has not seen. The column is not used as a feature. |
time_col |
Optional[str] | optional | A column of times: validation folds are contiguous periods of it, so intervals hold for later periods. It stays a feature. |
set_coverage |
Optional[float] | optional | Classification: return prediction sets that hold the true class this often, e.g. 0.9. |
compare |
Any | optional | Also train standard models on the same rows, for comparison: True for XGBoost, a random forest and a linear model, or a list of them (“xgboost”, “random_forest”, “linear”, “lightgbm”). Their predictions, with a naive baseline, are in result.comparison; result.comparison.score(actual) scores them. |
store |
Optional[bool] | optional | False: the call isn’t shown in your Logs (see the data-handling page in the docs). |
background |
bool | False |
Return a Job at once instead of waiting: job.wait() gives the result. A table too large for a direct call runs as a job anyway, and is waited for unless background=True. |
mask_columns |
Optional[bool] | optional | Send column names as c0, c1, …; results keep your names. Default: the client’s setting (False). |
fit(train: Any, target: Union[str, Sequence[str]], *, model: str = chakra-tab, task: Optional[str] = None, preset: Optional[str] = None, eval_metric: Optional[str] = None, time_limit: Optional[float] = None, seed: Optional[int] = None, ttl_hours: Optional[float] = None, profile: bool = True, groups: Optional[str] = None, time_col: Optional[str] = None, mask_columns: Optional[bool] = None, ttl_days: Optional[float] = None, store: Optional[bool] = None, background: bool = False) -> Union[FittedModel, FitGroup, Job]Fit once on our side and get a handle to predict (with intervals for regression) and explain as often as you like;
each prediction sends only the rows to score. The fit is kept 30 days after its last use (each prediction renews it;
ttl_days= sets 1 to 365) or until .delete(); with yh.fit(...) as m: deletes it on exit. Options as in predict().
profile=True keeps a summary of the training table on the handle (ranges, categories, up to 2,000 sample rows), so
predictions report out_of_range and novelty; it stays on your machine unless saved to a file (.save(), whose
sample=False leaves the rows out). False drops it.
target=[…] fits each target on the features alone (the other targets left out) and returns a FitGroup that predicts,
explains and deletes them together; task= may then be a dict per target. One fit’s quota per target.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
train |
Any | required | The training table: one row per example, the target column included. |
target |
Union[str, Sequence[str]] | required | The column to predict, or a list of columns: one fit per target, returned as a FitGroup. |
model |
str | 'chakra-tab' |
The model name, as GET /v1/models lists it. |
task |
Optional[str] | optional | “classify”, “regress”, or None to let the server infer it. Pass it for integer targets (a 1-5 rating could be either). |
preset |
Optional[str] | optional | “fast” (default: one holdout split, the quickest), “medium” (3-fold bagging, about 3x the time) or “pro” (8-fold bagging, the most accurate; “full” is the same). |
eval_metric |
Optional[str] | optional | What validation optimises: log_loss (default), roc_auc, f1, … for classification; rmse (default), mae, r2 for regression. |
time_limit |
Optional[float] | optional | Seconds for the whole call. |
seed |
Optional[int] | optional | Random seed; the server uses 0 when it is left out, so results are reproducible. |
ttl_hours |
Optional[float] | optional | The same in hours (ttl_days takes precedence). |
profile |
bool | True |
Keep a summary of the training table on the handle for out_of_range and novelty (stays on your machine). |
groups |
Optional[str] | optional | A column whose rows belong together (machine, batch, patient, store): validation folds hold out whole groups, so intervals hold for groups the model has not seen. The column is not used as a feature. |
time_col |
Optional[str] | optional | A column of times: validation folds are contiguous periods of it. It stays a feature. |
mask_columns |
Optional[bool] | optional | Send column names as c0, c1, …; results keep your names. Default: the client’s setting (False). |
ttl_days |
Optional[float] | optional | How many days the fit is kept after its last use, 1 to 365. Default: 30. |
store |
Optional[bool] | optional | False: the call isn’t shown in your Logs (see the data-handling page in the docs). |
background |
bool | False |
Return a Job at once instead of waiting: job.wait() gives the fitted model. One target only. |
compare
Section titled “compare”compare(train: Any, target: str, test: Any, *, models: Any = None, model: str = chakra-tab, task: Optional[str] = None, store: Optional[bool] = None, mask_columns: Optional[bool] = None) -> ComparisonTrain standard models on train and predict test with each, to compare with ChakraTab on the same rows:
XGBoost, a random forest and a linear model (LightGBM on request), plus a naive baseline (the most common class, or the mean).
result.score(actual, ChakraTab=prediction) scores them side by side. A direct call: tables up to the direct size.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
train |
Any | required | The training table: one row per example, the target column included. |
target |
str | required | The column to predict. |
test |
Any | required | The rows to predict, with the same feature columns as train. |
models |
Any | optional | Which standard models: a list of “xgboost”, “random_forest”, “linear”, “lightgbm”. Default: the first three. |
model |
str | 'chakra-tab' |
The model name, as GET /v1/models lists it. |
task |
Optional[str] | optional | “classify”, “regress”, or None to let the server infer it. |
store |
Optional[bool] | optional | False: the call isn’t shown in your Logs (see the data-handling page in the docs). |
mask_columns |
Optional[bool] | optional | Send column names as c0, c1, …; results keep your names. Default: the client’s setting (False). |
evaluate_table
Section titled “evaluate_table”evaluate_table(data: Any, target: str, *, cv: int = 5, groups: Any = None, time_col: Optional[str] = None, model: str = chakra-tab, task: Optional[str] = None, preset: Optional[str] = None, eval_metric: Optional[str] = None, quantiles: Any = None, seed: int = 0, mask_columns: Optional[bool] = None) -> TableEvaluationCross-validate on your own table: each row is predicted by a fit that never saw it, then scored for accuracy and for how honest the uncertainty is.
groups: a column name (or one value per row) whose rows must stay together, e.g. a machine or a batch, so the score is for groups the model has not seen. time_col: time-ordered folds instead (each fold trains only on earlier rows). Classification: accuracy, log loss, Brier score, AUC, calibration error, and a reliability table. Regression: MAE, RMSE, R2 and, with intervals (default quantiles 0.05 to 0.95), CRPS, coverage per interval and a PIT histogram. Cost: one fit-and-predict call per fold; the rows predicted add up to the table’s size.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
data |
Any | required | The whole table, target included; every row is predicted once by a fit that did not see it. |
target |
str | required | The column to predict. |
cv |
int | 5 |
Number of folds, at least 2. |
groups |
Any | optional | A column (or one value per row) whose rows stay in the same fold. |
time_col |
Optional[str] | optional | Time-ordered folds instead: each fold trains only on rows before its block. |
model |
str | 'chakra-tab' |
The model name, as GET /v1/models lists it. |
task |
Optional[str] | optional | “classify”, “regress”, or None to let the server infer it. Pass it for integer targets (a 1-5 rating could be either). |
preset |
Optional[str] | optional | “fast” (default: one holdout split, the quickest), “medium” (3-fold bagging, about 3x the time) or “pro” (8-fold bagging, the most accurate; “full” is the same). |
eval_metric |
Optional[str] | optional | What validation optimises: log_loss (default), roc_auc, f1, … for classification; rmse (default), mae, r2 for regression. |
quantiles |
Any | optional | Regression interval levels to score. Default: 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95. |
seed |
int | 0 |
Random seed; the server uses 0 when it is left out, so results are reproducible. |
mask_columns |
Optional[bool] | optional | Send column names as c0, c1, …; results keep your names. Default: the client’s setting (False). |
estimate_table
Section titled “estimate_table”estimate_table(train: Any = None, *, target: Optional[str] = None, test: Any = None, preset: Optional[str] = None, train_rows: Optional[int] = None, features: Optional[int] = None, predict_rows: Optional[int] = None, task: Optional[str] = None, quantiles: Any = None) -> Dict[str, Any]Credits a tabular call will cost, before making it: a fit on train plus predicting test, priced by the API at
your organization’s rates (POST /v1/estimate). Pass tables, or the counts (train_rows, features, predict_rows).
-> {“fit”, “predict”, “total”, “tokens”, “unit”}
| Parameter | Type | Required / default | Description |
|---|---|---|---|
train |
Any | optional | The training table (or pass train_rows and features). |
target |
Optional[str] | optional | The target column, left out of the feature count. |
test |
Any | optional | The rows to predict (or pass predict_rows). |
preset |
Optional[str] | optional | “fast” (default: one holdout split, the quickest), “medium” (3-fold bagging, about 3x the time) or “pro” (8-fold bagging, the most accurate; “full” is the same). |
train_rows |
Optional[int] | optional | Training rows, when no table is passed. |
features |
Optional[int] | optional | Feature columns, when no table is passed. |
predict_rows |
Optional[int] | optional | Rows to predict, when no table is passed. |
task |
Optional[str] | optional | “regress” adds what regression’s per-row intervals cost. Default: guessed from the target column, as the API does when predict() gets no task. |
quantiles |
Any | optional | The regression interval levels you will ask predict() for; their cost is added. |
impute
Section titled “impute”impute(df: pd.DataFrame, columns: Cols = None, *, model: str = chakra-tab, preset: Optional[str] = None, mask_columns: Optional[bool] = None) -> pd.DataFrameFills missing cells of a table: for each column with gaps, the model learns it from the other columns on the rows where it is present and predicts the rest (one call per column). The result’s .attrs[‘filled’] marks what was filled.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
df |
pd.DataFrame | required | The table with missing values. |
columns |
Cols | optional | Which columns to fill. Default: every column with missing values. |
model |
str | 'chakra-tab' |
The model name, as GET /v1/models lists it. |
preset |
Optional[str] | optional | “fast” (default: one holdout split, the quickest), “medium” (3-fold bagging, about 3x the time) or “pro” (8-fold bagging, the most accurate; “full” is the same). |
mask_columns |
Optional[bool] | optional | Send column names as c0, c1, …; results keep your names. Default: the client’s setting (False). |
get_fit
Section titled “get_fit”get_fit(fit_id: str) -> FittedModelReattach to a fit by id (labels come back as text unless the handle was pickled).
| Parameter | Type | Required / default | Description |
|---|---|---|---|
fit_id |
str | required |
fits() -> List[Dict[str, Any]]This key’s live fits: [{id, model, target, created_at, expires_at}].
get_tune
Section titled “get_tune”get_tune(tune_id: str) -> TunedReattach to a tune by id.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
tune_id |
str | required |
tunes() -> List[Dict[str, Any]]This project’s live tunes, newest first.
whoami
Section titled “whoami”whoami() -> Dict[str, Any]Checks the key and shows what it can do: the models it may use and its quota.
models
Section titled “models”models() -> List[Dict[str, Any]]Models this key can use: [{id, kind, description}].
usage() -> Dict[str, Any]Series (forecasts) and credits (tables) used and left, this month and in total.
server_limits
Section titled “server_limits”server_limits(apply: bool = True) -> Dict[str, Any]The API’s request caps (GET /v1/limits); with apply=True the client splits batches by them from now on.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
apply |
bool | True |
with_options
Section titled “with_options”with_options(*, timeout: Optional[float] = None, max_retries: Optional[int] = None, max_concurrency: Optional[int] = None, mask_columns: Optional[bool] = None) -> AnyA copy of this client with other settings, sharing its connection: yh.with_options(timeout=1800).fit(…).
| Parameter | Type | Required / default | Description |
|---|---|---|---|
timeout |
Optional[float] | optional | Seconds per request. |
max_retries |
Optional[int] | optional | Retries of timeouts, connection errors and 408 / 409 / 429 / 5xx replies. |
max_concurrency |
Optional[int] | optional | Requests sent in parallel when a large input is split. |
mask_columns |
Optional[bool] | optional | Send column names as c0, c1, … (results keep your names). |
ForecastResult
Section titled “ForecastResult”Forecasts as a DataFrame: id, timestamp, (target if several), then one column per quantile (median, q10, q90…).
derived lists quantile columns that were interpolated between the model’s native quantiles rather than produced directly.
intervals
Section titled “intervals”intervals(levels: Union[float, Sequence[float]] = 80) -> pd.DataFrameCentral prediction intervals by width in percent: lower_80 / upper_80 columns (from q10 / q90), next to the
median. The quantiles must be in the forecast: request them with level=[80] (or quantiles=) when forecasting.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
levels |
Union[float, Sequence[float]] | 80 |
Interval width in percent, or a list of widths. |
prob(*, above: Any = None, below: Any = None) -> pd.DataFrameProbability of exceeding (above=) or staying under (below=) a limit at every forecast step, read from the forecast’s quantiles. The limit is one number or one per row. More levels give a finer answer: forecast with quantiles=“all”. Beyond the outermost quantile the tail is extrapolated, so probabilities under 10% or over 90% are estimates.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
above |
Any | optional | A limit (one number or one per row): the chance of exceeding it. |
below |
Any | optional | A limit: the chance of staying under it. |
to_wide
Section titled “to_wide”to_wide(value: str = median) -> pd.DataFrameOne row per timestamp, one column per series (per series and target when there are several targets): the shape a spreadsheet or a plotting tool expects. value: which column to spread (median, mean, q10, …).
| Parameter | Type | Required / default | Description |
|---|---|---|---|
value |
str | 'median' |
The column to spread: median, mean, q10, … |
to_long
Section titled “to_long”to_long() -> pd.DataFrameHubverse-style long format: one row per (id, time, output): output_type ‘quantile’, output_type_id the level.
sample_paths
Section titled “sample_paths”sample_paths(uid: Any = None) -> AnySample paths of one series as an array [samples, h] (the first series by default). Sums, maxima or counts over the horizon get honest uncertainty from these: e.g. np.quantile(fc.sample_paths(“a”).sum(axis=1), [0.05, 0.95]).
| Parameter | Type | Required / default | Description |
|---|---|---|---|
uid |
Any | optional | The series. Default: the first one. |
plot(history: Optional[pd.DataFrame] = None, ids: Optional[List[Any]] = None, max_series: int = 4, ax: Any = None) -> AnyMedian and every central interval present (nested bands) per series, after the end of history if given (same
id / time columns). Needs matplotlib.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
history |
Optional[pd.DataFrame] | optional | |
ids |
Optional[List[Any]] | optional | |
max_series |
int | 4 |
|
ax |
Any | optional |
to_polars
Section titled “to_polars”to_polars() -> AnyEvaluationResult
Section titled “EvaluationResult”Backtest output. scores: one row per (model, series, [target], window) with each metric. summary: per model, the mean
of each metric, plus skill_<metric> = 1 - geometric mean of the model’s error relative to the baseline (higher is better).
calibration
Section titled “calibration”How honest the uncertainty is, per model, pooled over every scored point: kind “below”: share of actuals below each predicted quantile (a calibrated q10 has 10% below it); kind “interval”: share inside each central interval (a calibrated 80% interval holds 80%). gap = observed - nominal: near 0 is calibrated; a negative interval gap means intervals too narrow.
plot(ids: Optional[List[Any]] = None, max_series: int = 4, model: Optional[str] = None, ax: Any = None) -> AnyActuals across the windows, each window’s forecast and its cutoff. Needs matplotlib.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
ids |
Optional[List[Any]] | optional | |
max_series |
int | 4 |
|
model |
Optional[str] | optional | The model name, as GET /v1/models lists it. |
ax |
Any | optional |
plot_calibration
Section titled “plot_calibration”plot_calibration(ax: Any = None) -> AnyReliability plot: nominal vs observed share below each quantile, one line per model. Needs matplotlib.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
ax |
Any | optional |
PredictionResult
Section titled “PredictionResult”Tabular predictions aligned to the rows that were scored (index matches the input test rows).
Everything per row in one table: prediction, p_<class> or quantile columns, mean, prediction_set, indexed like test.
prob(*, above: Any = None, below: Any = None) -> pd.SeriesRegression: probability that each row’s value exceeds (above=) or stays under (below=) a limit (one number or one per row), read from the prediction intervals. Predict with several quantiles, e.g. quantiles=[0.05, 0.25, 0.5, 0.75, 0.95]. Classification already returns probabilities (result.probabilities).
| Parameter | Type | Required / default | Description |
|---|---|---|---|
above |
Any | optional | A limit (one number or one per row). |
below |
Any | optional | A limit. |
out_of_range
Section titled “out_of_range”Per row, the columns whose value is outside the training range, or a category training never had ([] = none). Predictions on such rows are extrapolations; treat their intervals with care. None when no training profile exists.
novelty
Section titled “novelty”Per row, how unlike the training data it is: the distance to its nearest training rows as a percentile of how far training rows are from each other (0.5 typical, 0.99 farther than 99% of them). Computed on first access.
to_polars
Section titled “to_polars”to_polars() -> AnyTuned(id: ‘str’, model: ‘str’, horizon: ‘int’, freq: ‘str’, series: ‘int’, steps: ‘int’, used: ‘bool’, report: ‘Dict[str, Any]’, created_at: ‘int’, expires_at: ‘int’, name: ‘Optional[str]’ = None, usage: ‘Dict[str, Any]’ = <factory>, _client: ‘Any’ = None)
forecast
Section titled “forecast”forecast(data: Any, h: Optional[int] = None, **kw: Any) -> AnyForecast with this tune; the same options as Client.forecast. h defaults to the tune’s horizon.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
data |
Any | required | The history: a long table with an id column, a time column and the target (pandas, polars, Spark, Dask or Ray), a Series with a DatetimeIndex, a numpy array (one series per row), or a dict of arrays. Arrays need freq=. |
h |
Optional[int] | optional | How many steps to forecast, at the series’ own frequency. |
**kwargs |
Any | optional |
delete
Section titled “delete”delete() -> NoneDeletes the tune on our side.
info() -> Dict[str, Any]The tune as the API shows it now (expiry, last use, report).
bind(client: Any) -> Tuned| Parameter | Type | Required / default | Description |
|---|---|---|---|
client |
Any | required |
FittedModel
Section titled “FittedModel”FittedModel(id: ‘str’, model: ‘str’, target: ‘str’, problem_type: ‘Optional[str]’, classes: ‘Optional[List[Any]]’, fit: ‘Dict[str, Any]’, created_at: ‘int’, expires_at: ‘int’, intervals: ‘bool’, features: ‘Optional[List[str]]’ = None, labels: ‘List[Any]’ = <factory>, _client: ‘Any’ = None, profile: ‘Optional[Dict[str, Any]]’ = None, mask: ‘Optional[Dict[str, str]]’ = None, usage: ‘Dict[str, Any]’ = <factory>, deleted: ‘bool’ = False)
predict
Section titled “predict”predict(test: Any, *, quantiles: Any = None, set_coverage: Optional[float] = None) -> PredictionResultScore rows with this fit. quantiles: regression only, any levels in (0, 1), e.g. [0.05, 0.5, 0.95]. set_coverage: classification only, e.g. 0.9: res.prediction_sets holds, per row, the classes that together contain the true one for 90% of new rows like the training ones (one class when the model is sure, several when it is not).
| Parameter | Type | Required / default | Description |
|---|---|---|---|
test |
Any | required | The rows to score, with the training table’s feature columns. |
quantiles |
Any | optional | Regression: interval levels in (0, 1). |
set_coverage |
Optional[float] | optional | Classification: prediction sets that hold the true class this often, e.g. 0.9. |
predict_proba
Section titled “predict_proba”predict_proba(test: Any) -> pd.DataFrameClassification: one probability column per class, indexed like test.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
test |
Any | required | The rows to predict, with the same feature columns as train. Without it, the rows of train whose target is empty are predicted. |
importance
Section titled “importance”importance(data: Any = None, *, subsample_size: int = 1000, num_shuffle_sets: int = 3, time_limit: Optional[float] = None) -> pd.DataFramePermutation importance per input column: how much the score drops when the column is shuffled (higher = more important). data: labeled rows the model has not seen (with the target column); best for medium/full fits. Without it, a fast fit uses its own validation split and a bagged fit falls back to training rows (in-sample, so importance is optimistic; see .attrs[‘source’]).
| Parameter | Type | Required / default | Description |
|---|---|---|---|
data |
Any | optional | Labeled rows the model has not seen (target included); the most honest numbers. |
subsample_size |
int | 1000 |
Rows used per shuffle. |
num_shuffle_sets |
int | 3 |
Repeats per column; more gives a tighter stddev. |
time_limit |
Optional[float] | optional | Seconds for the call. |
effect
Section titled “effect”effect(col: str, *, grid: Any = 20, data: Any = None, rows: int = 200, seed: int = 0) -> pd.DataFrameHow the prediction moves as one column varies, everything else as in real rows (partial dependence).
Takes rows rows (from data=, else the training sample kept on this handle), sets col to each grid value in turn
and predicts them all in one call: average is the mean prediction (class probability for classification, one curve
per class in output), low / high the 10th and 90th percentile across rows, which shows whether the effect is the
same everywhere. grid: a number of points (quantiles of the column; categories by frequency) or the values themselves.
Cost: rows x grid predicted rows (200 x 20 = 4,000 by default). Plot it with yhatlabs.plots.effect().
| Parameter | Type | Required / default | Description |
|---|---|---|---|
col |
str | required | The column to vary. |
grid |
Any | 20 |
Number of values (quantiles of the column, or its most frequent categories), or the values themselves. |
data |
Any | optional | Rows to vary. Default: the training sample kept on the handle. |
rows |
int | 200 |
How many rows to vary. |
seed |
int | 0 |
Seed for picking the rows. |
save(path: Any = None, *, sample: bool = True) -> Dict[str, Any]Writes the fit’s record to path as JSON, and returns it. Load it later, in another process or on another machine,
with yhatlabs.load(path). The fit itself lives on our side. The record holds the training profile (column ranges and
categories for out_of_range) and a sample of up to 2,000 training rows (for novelty and effect()); sample=False leaves
the rows out, and a fit made with profile=False has no profile at all.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
path |
Any | optional | Where to write the JSON record; None only returns it. |
sample |
bool | True |
Include the sample of training rows. |
delete
Section titled “delete”delete() -> NoneDelete the fit on our side (its stored training request and the fitted model). Expired fits are deleted anyway; a second delete() does nothing.
info() -> Dict[str, Any]The fit as the API holds it: model, target, summary, classes, expiry.
bind(client: Any) -> FittedModel| Parameter | Type | Required / default | Description |
|---|---|---|---|
client |
Any | required |
FitGroup
Section titled “FitGroup”One fit per target, from Client.fit(train, target=[…]): each target is fitted on the features only (the other targets
are left out), and predicted, explained and deleted together. fits[target] is that target’s FittedModel.
predict
Section titled “predict”predict(test: Any, *, quantiles: Any = None) -> GroupPredictionEvery target for the same rows (one call per target); quantiles= applies to the regression targets.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
test |
Any | required | The rows to predict, with the same feature columns as train. Without it, the rows of train whose target is empty are predicted. |
quantiles |
Any | optional | Quantile levels in (0, 1), e.g. [0.1, 0.5, 0.9], or “all” for every level the model produces. Default [0.1, 0.5, 0.9]. |
importance
Section titled “importance”importance(data: Any = None, **kw: Any) -> pd.DataFramePermutation importance per target, stacked with a target column.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
data |
Any | optional | The history: a long table with an id column, a time column and the target (pandas, polars, Spark, Dask or Ray), a Series with a DatetimeIndex, a numpy array (one series per row), or a dict of arrays. Arrays need freq=. |
**kwargs |
Any | optional |
effect
Section titled “effect”effect(col: str, **kw: Any) -> pd.DataFrameFittedModel.effect for every target, stacked with a target column.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
col |
str | required | |
**kwargs |
Any | optional |
save(path: Any = None, *, sample: bool = True) -> Dict[str, Any]Every target’s fit record in one file; yhatlabs.load(path) gives the FitGroup back. sample=False leaves out the training row samples, as in FittedModel.save().
| Parameter | Type | Required / default | Description |
|---|---|---|---|
path |
Any | optional | |
sample |
bool | True |
delete
Section titled “delete”delete() -> NoneTableEvaluation
Section titled “TableEvaluation”Cross-validated scores of a tabular model on your data. predictions: every row’s out-of-fold prediction (and fold);
scores: one row per fold; summary: the scores over all rows pooled. Classification adds reliability; regression with
intervals adds coverage and pit.
plot(ax: Any = None) -> AnyClassification: reliability diagram. Regression: predicted against actual, with the widest interval. Needs matplotlib.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
ax |
Any | optional |
Comparison
Section titled “Comparison”Each standard model’s predictions for the test rows (index = the test rows), and the naive baseline’s.
score(actual: Any, **others: Any) -> pd.DataFrameScores every model against the true values of the test rows, one row per model, best first.
Classification: accuracy, balanced accuracy and, where probabilities exist, log loss (and ROC AUC for two classes). Regression: MAE, RMSE, R2.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
actual |
Any | required | The true target values of the test rows, in the same order. |
**kwargs |
Any | optional |
A table call running in the background. status() checks it, wait() (or result()) blocks until it is done and returns what the direct call would have returned, cancel() stops it.
status
Section titled “status”status() -> strqueued, running, succeeded, failed or canceled.
wait(timeout: Optional[float] = 7200.0) -> AnyBlocks until the job is done and returns its result; raises JobFailedError if it failed or was canceled.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
timeout |
Optional[float] | 7200.0 |
Seconds to wait at most (default two hours; None: as long as it takes); raises TimeoutError past it, the job still runs. |
result
Section titled “result”result(timeout: Optional[float] = 7200.0) -> AnyThe same as wait().
| Parameter | Type | Required / default | Description |
|---|---|---|---|
timeout |
Optional[float] | 7200.0 |
cancel
Section titled “cancel”cancel() -> boolStops the job if it hasn’t finished; True when it was canceled.
AnomalyStream
Section titled “AnomalyStream”Anomaly scores for points as they arrive. Keeps the last window points of every series and scores only each update’s
new points, with one detect_anomalies call per update on the kept history plus the new points. Made by
Client.anomaly_stream().
update
Section titled “update”update(new: Any) -> pd.DataFrameScores the new points (one detect_anomalies call) and adds them to the kept history. A series is scored once it has enough history before the new points (two seasons, at least 8 points); until then its points are only kept. A point sent again (same id and time) replaces the kept one.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
new |
Any | required | The new points: a long table with the id, time and target columns (and the covariates the stream uses). |
yhatlabs
Section titled “yhatlabs”check(data: Any, *, h: Optional[int] = None, target: Optional[Union[str, Sequence[str]]] = None, id_col: Optional[str] = None, time_col: Optional[str] = None, freq: Optional[str] = None, limits: Optional[Limits] = None) -> DataCheckChecks data locally. With a time column it is read as time series (pass h= to also check the horizon); without one, as a
table to predict target from. Nothing leaves your machine.
import yhatlabs yhatlabs.check(df, h=24) # DataCheck(timeseries: 12 series, 1 warning, 2 notes)
| Parameter | Type | Required / default | Description |
|---|---|---|---|
data |
Any | required | A time-series table, or a tabular table with target=. |
h |
Optional[int] | optional | The horizon you plan to forecast (checks the history is long enough). |
target |
Optional[Union[str, Sequence[str]]] | optional | For tables: the target column(s); turns on the tabular checks. |
id_col |
Optional[str] | optional | The column naming each series. Default: unique_id, id, item_id or series_id if present, else one series. |
time_col |
Optional[str] | optional | The timestamp column. Default: ds, timestamp, time, date or datetime if present. |
freq |
Optional[str] | optional | The series’ frequency as a pandas alias (h, D, W-SUN, MS, 15min, …). Inferred from the timestamps when left out; required for arrays and integer time steps. |
limits |
Optional[Limits] | optional | Request caps to check against. Default: the published ones. |
outliers
Section titled “outliers”outliers(train: Any, data: Any = None, *, threshold: float = 0.99) -> pd.DataFrameScores rows by how unlike the training rows they are, locally: nothing is sent and no key is needed. novelty is the distance from a row to its nearest training rows, as a percentile of how far training rows are from each other (0.5 is typical, 0.99 farther than 99% of them); the same measure as PredictionResult.novelty.
import yhatlabs yhatlabs.outliers(train, new_rows) # novelty, outlier, out_of_range per new row yhatlabs.outliers(train) # each training row against the others
| Parameter | Type | Required / default | Description |
|---|---|---|---|
train |
Any | required | The reference table (pandas, polars, Spark, Dask or Ray). |
data |
Any | optional | The rows to score, against the columns they share with train. Default: the training rows themselves, each against the other rows (leave-one-out). |
threshold |
float | 0.99 |
Novelty above which a row is flagged as an outlier. |
load(source: Union[str, Path, Dict[str, Any]], client: Any = None) -> FittedModelA fitted model from a record written by FittedModel.save() (or a FitGroup from FitGroup.save()), attached to client
(default: a new Client()). Makes no request; if the fit has expired or been deleted, its first predict raises NotFoundError.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
source |
Union[str, Path, Dict[str, Any]] | required | |
client |
Any | optional |
yhatlabs.hierarchy
Section titled “yhatlabs.hierarchy”aggregate
Section titled “aggregate”aggregate(data: Any, levels: Sequence[Sequence[str]], *, time_col: str = ds, target_col: str = y, total: Optional[str] = total) -> Tuple[pd.DataFrame, Dict[str, List[str]]]Every level’s series from the bottom rows. levels: from the top down, each a list of the columns that define it; the last level is the bottom (one series per distinct combination). -> (long table with a unique_id column, {parent id: [child ids]}).
| Parameter | Type | Required / default | Description |
|---|---|---|---|
data |
Any | required | The bottom-level rows. |
levels |
Sequence[Sequence[str]] | required | From the top down, the columns that define each level; the last is the bottom. |
time_col |
str | 'ds' |
The timestamp column. Default: ds, timestamp, time, date or datetime if present. |
target_col |
str | 'y' |
The column (or list of columns) to forecast. Default: y, target or value if present, else the one numeric column. |
total |
Optional[str] | 'total' |
Name of the series summing everything, or None for no total. |
reconcile
Section titled “reconcile”reconcile(fc: Any, tree: Dict[str, List[str]]) -> AnyThe forecast with every value column (median, mean, each quantile) adjusted so parents equal the sum of their children. Quantiles are reconciled column by column: exact for the median and mean, an approximation for the interval edges (sums of quantiles are not quantiles of sums); use sample paths when the uncertainty of an aggregate matters.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
fc |
Any | required | A forecast of every series in the tree. |
tree |
Dict[str, List[str]] | required | {parent id: [child ids]}, as aggregate() returns it. |
yhatlabs.plots
Section titled “yhatlabs.plots”forecast
Section titled “forecast”forecast(fc: Any, history: Optional[pd.DataFrame] = None, ids: Optional[List[Any]] = None, max_series: int = 4, ax: Any = None) -> AnyMedian and nested interval bands per series, after the end of history.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
fc |
Any | required | |
history |
Optional[pd.DataFrame] | optional | |
ids |
Optional[List[Any]] | optional | |
max_series |
int | 4 |
|
ax |
Any | optional |
backtest
Section titled “backtest”backtest(ev: Any, ids: Optional[List[Any]] = None, max_series: int = 4, model: Optional[str] = None, ax: Any = None) -> AnyActuals across the backtest windows, each window’s forecast and its cutoff.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
ev |
Any | required | |
ids |
Optional[List[Any]] | optional | |
max_series |
int | 4 |
|
model |
Optional[str] | optional | The model name, as GET /v1/models lists it. |
ax |
Any | optional |
anomalies
Section titled “anomalies”anomalies(flags: pd.DataFrame, ids: Optional[List[Any]] = None, max_series: int = 4, ax: Any = None) -> AnyThe series, its expected range and the flagged points (from detect_anomalies).
| Parameter | Type | Required / default | Description |
|---|---|---|---|
flags |
pd.DataFrame | required | |
ids |
Optional[List[Any]] | optional | |
max_series |
int | 4 |
|
ax |
Any | optional |
scenarios
Section titled “scenarios”scenarios(frame: pd.DataFrame, history: Optional[pd.DataFrame] = None, ids: Optional[List[Any]] = None, max_series: int = 4, ax: Any = None) -> AnyOne median line and interval band per scenario, per series.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
frame |
pd.DataFrame | required | |
history |
Optional[pd.DataFrame] | optional | |
ids |
Optional[List[Any]] | optional | |
max_series |
int | 4 |
|
ax |
Any | optional |
calibration
Section titled “calibration”calibration(ev: Any, ax: Any = None) -> AnyForecast calibration: nominal quantile level against the share of actuals below it.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
ev |
Any | required | |
ax |
Any | optional |
reliability
Section titled “reliability”reliability(ev: Any, ax: Any = None) -> AnyClassification calibration: predicted probability against observed frequency (from evaluate_table).
| Parameter | Type | Required / default | Description |
|---|---|---|---|
ev |
Any | required | |
ax |
Any | optional |
predicted_vs_actual
Section titled “predicted_vs_actual”predicted_vs_actual(res: Any, actual: Any, ax: Any = None) -> AnyRegression: predictions against true values, with the widest interval as error bars.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
res |
Any | required | |
actual |
Any | required | |
ax |
Any | optional |
importance
Section titled “importance”importance(imp: pd.DataFrame, top: int = 20, ax: Any = None) -> AnyPermutation importance bars with their spread (from FittedModel.importance).
| Parameter | Type | Required / default | Description |
|---|---|---|---|
imp |
pd.DataFrame | required | |
top |
int | 20 |
|
ax |
Any | optional |
effect
Section titled “effect”effect(eff: pd.DataFrame, ax: Any = None) -> AnyAn effect curve: the average prediction as one column varies, with the spread across rows.
| Parameter | Type | Required / default | Description |
|---|---|---|---|
eff |
pd.DataFrame | required | |
ax |
Any | optional |

