This is the abridged developer documentation for YHat Labs # Documentation > Time-series forecasting and tabular prediction with the YHat Labs foundation models, from Python, the command line, coding agents or the REST API. Pretrained models that forecast any time series and predict on any table, from one API call. Send the data you already have; get predictions back, each with how sure the model is. Nothing to train, tune or maintain. Forecast any time series Accurate forecasts with uncertainty, for one series or thousands, with no training. A replacement for ARIMA, ETS, Prophet and hand-built ML forecasting pipelines. [**ChakraTS**](/models/docs/models/chakra-ts) · 1st among zero-shot models on fev-bench, GIFT-Eval and TIME Predict on any table Classification and regression on raw tables, with probabilities or intervals for every row and no training or tuning. A replacement for XGBoost, LightGBM, CatBoost and AutoML. [**ChakraTab**](/models/docs/models/chakra-tab) · 3rd on TabArena and RamanBench ## Start here [Section titled “Start here”](#start-here) [Quickstart](/models/docs/quickstart)Install the library, set your key, make a forecast and a prediction. [Choosing a model](/models/docs/choosing-a-model)Which model fits your problem, and what each one returns. [Cookbook](/models/docs/cookbook)Worked examples on real data, from loading it to a scored result. [API reference](/models/docs/api/overview)Every endpoint, request and response, for any language. ## Ways to use the models [Section titled “Ways to use the models”](#ways-to-use-the-models) | | | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | **Python** | `pip install yhatlabs`: the official library, with pandas in and pandas out ([Python library](/models/docs/tools/python)) | | **Command line** | `yhatlabs forecast sales.csv --h 28`: CSV or parquet files from a terminal or a scheduler ([CLI](/models/docs/tools/cli)) | | **Coding agents** | `yhatlabs skills install`: teaches Claude Code, Cursor or Codex the calls and the rules ([Agent skills](/models/docs/agents/skills)) | | **Any language** | the REST API at `https://api.yhatlabs.com` ([API reference](/models/docs/api/overview)) | These docs are also available to AI tools as plain text, starting at [llms.txt](/llms.txt). # Docs for AI tools > Plain-text versions of these docs for chat assistants, coding agents and retrieval pipelines. These docs are published in formats AI tools read directly: | URL | Contains | | ---------------------------------- | -------------------------------------------------------------------------- | | [/llms.txt](/llms.txt) | what these docs cover, the main calls, and links to the two versions below | | [/llms-full.txt](/llms-full.txt) | the full docs in one Markdown file | | [/llms-small.txt](/llms-small.txt) | a shorter version for small context windows | Paste one of these links into a chat assistant, or point a retrieval pipeline at it, to answer questions from the current docs. For coding agents, the [agent skill](/models/docs/agents/skills) is the better fit: it loads automatically when a task needs it. # Agent skills > Teach coding agents such as Claude Code, Cursor and Codex how to use the YHat Labs models. A skill is a short reference that coding agents load when a task matches: what the models do, the calls, and the rules. With it, an agent asked to “forecast next month’s demand” or “predict churn from this table” uses the library correctly instead of guessing. ```sh pip install yhatlabs yhatlabs skills install ``` This writes the skill into the current project, at `.claude/skills/yhatlabs/SKILL.md` and `.agents/skills/yhatlabs/SKILL.md`, the two places agents look. `yhatlabs skills show` prints it; `--dir PATH` installs it into another folder. The skill covers: * checking data first, locally; * forecasting (95% and 99% intervals, sample paths, chances of crossing a limit, the `fast` and `pro` presets), backtesting, hierarchies, anomalies (also on points as they arrive, with `anomaly_stream`), gaps, and how much each covariate moves a forecast (`explain_forecast`); * tuning the model on the user’s own series (`tune`), checking whether it helped (`used`, `holdout`) and forecasting with it; * fitting, evaluating on the user’s own table, predicting with intervals or prediction sets, importance and effects, saving and loading fits, and finding rows unlike the training rows (`yhatlabs.outliers`, local); * comparing with standard models on the same rows (`compare=True`), and running large tables in the background (`background=True`; tables too large for a direct call run as jobs on their own); * the CLI, with `--json` for machine-readable output; * the rules: keys come from `YHAT_API_KEY` and are never printed; the column names it looks for (`unique_id`, `ds`, `y`, …) and when to pass `id_col=` / `time_col=` / `target_col=`; the 2,048-step horizon and resampling very fine data first; rows grouped by machine, batch or patient get `groups=`, rows over time `time_col=`; uncertainty is reported with the numbers the result gives; what the table presets (`fast`, `medium`, `pro`) cost in credits and time, how predicting from a saved model is charged, which regression column is the point forecast, and `store=False` to keep a call out of the Logs. Run `yhatlabs skills install` again after upgrading the library, so the skill matches the installed version. Combined with `--json` on the CLI, an agent can check data, forecast and read the results without writing any glue code. # API keys > Get a key, keep it out of your code, check what it can do, and understand the quota. Every request to the models needs an API key. This page covers where to keep it, how to check it, and how usage is counted. ## Get a key [Section titled “Get a key”](#get-a-key) [Create an account](https://yhatlabs.com/models/signup), make a key on the [API keys page](https://yhatlabs.com/models/account#keys), and request credits on the Credits page. A key looks like `yh-...`, belongs to a project of your organization, and spends the organization’s credits. ## Organizations, projects and keys [Section titled “Organizations, projects and keys”](#organizations-projects-and-keys) * **Organization:** your company, lab or team. It holds the members, the credits and the projects. You can belong to several. * **Project:** one use of the models, such as a pipeline, a product or a client. Each project has its own keys and its own usage and logs. Every organization starts with a **Default** project, and owners and admins can create more on the [Projects page](https://yhatlabs.com/models/account#projects). * **Key:** belongs to one project. A member’s own key is handed to the project if they leave. A **project key** (made by an owner or admin) is for production and keeps working when people come and go. Credits are shared by the whole organization. To stop one project from spending them all, give it a monthly or total **cap**; each key can also have its own cap. Archiving a project revokes its keys and keeps its usage. ## Keep it out of your code [Section titled “Keep it out of your code”](#keep-it-out-of-your-code) Set the key as an environment variable. The Python library, the command line and agent skills all read it from there: ```sh export YHAT_API_KEY="" ``` * **Python:** `Client()` reads `YHAT_API_KEY`. You can also pass `Client(api_key="...")`, or keep the key in a `.env` file loaded with [python-dotenv](https://pypi.org/project/python-dotenv/). * **HTTP:** send it as `Authorization: Bearer `. * Never commit a key, paste it into a shared notebook, or log it. The library never writes it to disk or to its logs. ## Check your key [Section titled “Check your key”](#check-your-key) This confirms the key works and shows which models it can use and how much of its quota is left: * Python ```python from yhatlabs import Client yh = Client() # reads YHAT_API_KEY from the environment me = yh.whoami() print(me["models"]) print(me["usage"]["left"]) ``` Output ```text ['chakra-ts', 'chakra-tab'] {'monthly': None, 'total': 1000} ``` * CLI ```sh yhatlabs whoami ``` Output ```text { "base_url": "https://api.yhatlabs.com", "key": "yh-...a1b2", "models": [ "chakra-ts", "chakra-tab" ], "usage": { "unit": "series", "used": { "monthly": 1000, "total": 1000 }, "quota": { "monthly": null, "total": 1000 }, "left": { "monthly": null, "total": 1000 }, "credits": { "used": { "monthly": 1000, "total": 1000 }, "quota": { "monthly": null, "total": null }, "left": { "monthly": null, "total": null } } } } ``` Parameters: [`Client.whoami`](/models/docs/reference/python#client-whoami) `models` lists the models the key may call. `usage.left` is what remains of its quota per period: `None` in Python (`null` in the CLI’s JSON) means no cap for that period. ## Tags [Section titled “Tags”](#tags) Tags add up spend by experiment, pipeline or client. Give a key tags on its edit page (for example `prod` or `client-acme`); they go on every call it makes. A call can add its own with a header: ```sh curl https://api.yhatlabs.com/v1/series/forecast \ -H "Authorization: Bearer $YHAT_API_KEY" \ -H "X-Yhat-Tags: experiment-12,weekly" \ -H "Content-Type: application/json" -d @request.json ``` Up to 10 tags per key and 10 per call: lowercase letters, digits and `. _ : -`, at most 40 characters each. Usage shows spend by tag, and the logs filter by it. ## Credits [Section titled “Credits”](#credits) Calls spend credits from your organization. Each call is counted in tokens, from the work it causes (a forecast by its history and horizon, a table call by its rows and columns), and paid in credits at your organization’s rate (1 credit per 1M tokens by default). Amounts are shown with decimals: a small call costs about `0.02` credits, and every reply states its cost in `usage.credits`. [Limits](/models/docs/resources/limits#pricing) has the rules, and `POST /v1/estimate` (or `yh.estimate_table()`) the cost of a call before you make it. Your balance, what refills it and the last 30 days of use are on the [Credits page](https://yhatlabs.com/models/account#credits). When the organization has no credits left, calls fail with HTTP 402 and error type `no_credits`; owners request more on the Credits page. When a key’s or a project’s cap is reached, calls fail with HTTP 429 and error type `quota_exceeded`. A call that fails on our side does not count. Keys we issued directly (for example for a benchmark) carry their own quota instead: forecasts counted in series, tables in credits, each with an optional monthly and total cap. When one is used up, calls fail with HTTP 429 and error type `quota_exceeded` (`RateLimitError` in Python), which is not retried. ## Use your own deployment [Section titled “Use your own deployment”](#use-your-own-deployment) To send requests to a dedicated or self-hosted deployment instead of the hosted API, set its address: ```sh export YHAT_BASE_URL="https://your-deployment.example.com" ``` In Python, `Client(base_url=...)` does the same for one client. # Models, usage and limits > The models a key can use, its quota, and the API's request caps. Three read-only endpoints describe what your key can do. None of them uses quota. ## Models [Section titled “Models”](#models) GET`/v1/models` ```json {"models": [ {"id": "chakra-ts", "kind": "timeseries", "description": "ChakraTS: zero-shot probabilistic time-series forecasting"}, {"id": "chakra-tab", "kind": "tabular", "description": "ChakraTab: in-context classification and regression on tables"} ]} ``` ## Usage [Section titled “Usage”](#usage) GET`/v1/usage` ```json {"unit": "series", "used": {"monthly": 120, "total": 4310}, "quota": {"monthly": null, "total": 100000}, "left": {"monthly": null, "total": 95690}, "credits": {"used": {"monthly": 0.014, "total": 0.052}, "quota": {"monthly": null, "total": 2.5}, "left": {"monthly": null, "total": 2.448}}} ``` For a key of an organization, every call is counted in `credits` (forecasts too), and `workspace.balance` is the organization’s balance. For a key without an organization, the top level counts forecasts (in series) and `credits` counts tabular calls. `null` means no cap for that period; see [Limits](/models/docs/resources/limits#pricing) for the rates. ## Limits [Section titled “Limits”](#limits) GET`/v1/limits` ```json { "forecast": {"max_series": 256, "max_points_per_series": 32768, "max_total_points": 8000000, "max_horizon": 2048, "max_columns": 256, "native_quantile_levels": [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]}, "tabular": {"max_rows": 200000, "max_columns": 2000, "max_cells_async": 50000000, "max_bytes": 67108864, "direct": {"fast": {"rows": 100000, "columns": 100}, "medium": {"rows": 25000, "columns": 100}, "pro": {"rows": 25000, "columns": 100}}, "presets": ["fast", "medium", "pro"], "max_quantiles": 32, "fit_ttl_days": {"default": 30, "max": 365}, ...}, "pricing": {...}, "rate": {...}, "capabilities": {...} } ``` # Errors > The error shape, every error type, and what to do about each. Every error has the same shape. This sends an invalid horizon: ```sh curl -s https://api.yhatlabs.com/v1/series/forecast \ -H "Authorization: Bearer $YHAT_API_KEY" \ -H "Content-Type: application/json" \ -d '{"horizon": 0, "series": [{"id": "a", "values": [1, 2, 3]}]}' ``` Output ```text {"error":{"type":"invalid_request_error","message":"'horizon' must be a positive integer.","request_id":"eea9b5ec-b5ed-463d-a6b8-3d4296491787"}} ``` Every error body carries `request_id`, the same value as the `X-Request-Id` header. Quote it when you contact us. | Status | `type` | Meaning | What to do | | ------ | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | 400 | `invalid_request_error` | the request is malformed | fix it; the message says how | | 401 | `authentication_error` | missing, invalid, revoked or expired key | check `YHAT_API_KEY` | | 402 | `no_credits` | the organization’s credits ran out | owners request more on the Credits page | | 403 | `model_not_allowed` | the key was limited to other models | use one of the models the message lists, or change the key | | 403 | `organization_suspended` | the organization is suspended | write to us | | 404 | `model_not_found` | no such model for this key’s organization | see `GET /v1/models` | | 410 | `model_retired` | the model was retired | pick another from `GET /v1/models` | | 404 | `fit_not_found` | the fit expired, was deleted, or belongs to another project | fit again | | 404 | `job_not_found` | no such job in this project | check the id | | 413 | `async_required` | a direct table call past its preset’s direct size ([Limits](/models/docs/resources/limits)) | send it again with `"async": true` ([Async jobs](/models/docs/api/jobs)); the Python library does this for you | | 413 | `request_too_large` | over a hard size limit (200,000 rows, 2,000 columns, 50,000,000 cells as a job) | sample or split the input ([Limits](/models/docs/resources/limits)) | | 409 | `request_in_progress` | a call with the same `Idempotency-Key` is still running | retry after `Retry-After` | | 422 | `invalid_request_error` | the model could not use this data; the message says why when it is about your input (one class, too few rows, a missing column, an invalid parquet file) | fix the input | | 403 | `forbidden` | only whoever made a fit (or a project admin) may rename or delete it | ask them | | 429 | `quota_exceeded` | a key’s or project’s cap is used up; `period`, `limit` and `used` are included | wait for the next period, or raise the cap | | 502 | `upstream_error` | the model failed on this request: a bug on our side, not your data | retrying rarely helps; send us the request id | | 503 | `model_unavailable` | the model is starting or temporarily down; a `Retry-After` header says when to retry | retry after the wait | Retry 408, 409, 429 (except `quota_exceeded`) and 5xx with backoff; the Python library does this for you. For calls that switched to a streamed `200` response, an error arrives in the body ([Overview](/models/docs/api/overview#conventions)). # Fits > Fit a table once, then predict from the stored fit and compute importance. | Method and path | What it does | | ----------------------------------------------- | ----------------------------------- | | `POST /v1/table/fits` | creates a fit | | `POST /v1/table/fits/{id}/predict` | predicts rows from it | | `POST /v1/table/fits/{id}/importance` | column importance | | `GET /v1/table/fits`, `GET /v1/table/fits/{id}` | lists the project’s fits, reads one | | `PATCH /v1/table/fits/{id}` | renames a fit, or keeps it longer | | `DELETE /v1/table/fits/{id}` | deletes a fit | A fit is stored on our side until it expires or you delete it, so each later call sends only the rows to score. This creates a fit, predicts two rows from it and deletes it: ```sh # fit once FIT=$(curl -s https://api.yhatlabs.com/v1/table/fits \ -H "Authorization: Bearer $YHAT_API_KEY" -H "Content-Type: application/json" \ -d '{"target": "y", "problem_type": "regression", "ttl_hours": 1, "train": [{"x": 1, "y": 2.1}, {"x": 2, "y": 3.9}, {"x": 3, "y": 6.2}, {"x": 4, "y": 8.1}, {"x": 5, "y": 9.8}, {"x": 6, "y": 12.2}, {"x": 7, "y": 13.9}, {"x": 8, "y": 16.1}, {"x": 9, "y": 18.0}, {"x": 10, "y": 19.9}]}' \ | python3 -c "import sys, json; print(json.load(sys.stdin)['id'])") echo "fit: ${FIT:0:8}..." # predict from it, as often as you like curl -s https://api.yhatlabs.com/v1/table/fits/$FIT/predict \ -H "Authorization: Bearer $YHAT_API_KEY" -H "Content-Type: application/json" \ -d '{"test": [{"x": 11}, {"x": 12}]}' \ | python3 -c "import sys, json; r = json.load(sys.stdin); print(r['predictions'], r['usage'])" # delete it when done curl -s -X DELETE https://api.yhatlabs.com/v1/table/fits/$FIT -H "Authorization: Bearer $YHAT_API_KEY" \ | python3 -c "import sys, json; print(json.load(sys.stdin)['deleted'])" ``` Output ```text fit: fit_4c47... [21.531238555908203, 23.052967071533203] {'rows': 2, 'credits': 0.02} True ``` ## Create a fit [Section titled “Create a fit”](#create-a-fit) POST`/v1/table/fits` It takes: | Field | Type | Required / default | Description | | -------------- | ------------------------------------ | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `train` | table | **required** | Rows including the target column. | | `target` | string | **required** | The column to predict. | | `name` | string | optional | A name to find it by. (max length 120) | | `async` | boolean | optional | Queue the fit and answer 202 with a job; GET /v1/jobs/{id} gives the fit when done. | | `ttl_days` | number | `30` | Days the fit is kept after its last use; each prediction starts the count again. (max 365) | | `model` | string | `"chakra-tab"` | The model, as GET /v1/models lists it. | | `preset` | `fast`, `medium`, `pro`, `full` | `"fast"` | fast: the quickest; medium: more accurate, about 3x the credits and 2-3x the time; pro: the most accurate, about 8x the credits and 4-8x the time (full is the same, its earlier name). | | `problem_type` | `binary`, `multiclass`, `regression` | optional | Inferred from the target when left out. | | `eval_metric` | string | optional | What validation optimises: log_loss (default), roc_auc, f1, …; rmse (default), mae, r2. | | `time_limit` | number | optional | Seconds for the whole call. | | `seed` | integer | `0` | Random seed; the same seed gives the same fit. | | `store` | boolean | `true` | false keeps this call out of your Logs (we still keep a copy to look into errors; never used for training). | | `groups` | string | optional | A train column: validation folds hold out whole groups; not used as a feature. | | `time_col` | string | optional | A train column: validation folds are contiguous periods. | It returns: | Field | Type | Description | | ----------------- | ------------------------------------ | --------------------------------------------------------------------------------------- | | `id` | string | fit\_… | | `object` | `"fit"` | | | `model` | string | | | `target` | string | | | `created_at` | integer | Unix seconds. | | `expires_at` | integer | Unix seconds; the fit is deleted then. | | `fit` | object | Rows, features, seconds, problem type, metric, preset, seed, version, groups, time_col. | | `classes` | array of number or string or boolean | Classification: the classes. | | `intervals` | boolean | Regression: whether quantiles= is available. | | `prediction_sets` | boolean | Classification: whether set_coverage= is available. | | `usage` | object | | ## Predict from a fit [Section titled “Predict from a fit”](#predict-from-a-fit) POST`/v1/table/fits/{id}/predict` It takes: | Field | Type | Required / default | Description | | -------------- | --------------- | ------------------ | --------------------------------------------------- | | `test` | table | **required** | Rows to predict, with the fit’s feature columns. | | `quantiles` | array of number | optional | Regression: interval levels. (at most 32) | | `set_coverage` | number | optional | Classification: prediction sets with this coverage. | and returns the prediction fields of [/v1/table/predict](/models/docs/api/tabular-predict#response), plus `fit_id` and `restored`. `restored: true` means the fit was rebuilt from its stored training table during this call (same seed, so the same model): slower, same result. A prediction is charged on the fit’s training table (0.5 x its cells) plus the predicted cells, so scoring a few rows from a large fit still costs a share of it. For a regression, `quantiles` (ranges) add a fixed cost, and about 10-20 seconds the first time they are asked of a fit. `predictions` is the point forecast to use; with `quantiles`, `median` and `mean` describe each row’s predicted distribution. ## Importance [Section titled “Importance”](#importance) POST`/v1/table/fits/{id}/importance` It takes, all fields optional: | Field | Type | Required / default | Description | | ------------------ | ------- | ------------------ | ----------------------------------------------------------------------------- | | `data` | table | optional | Labeled rows the fit has not seen (target included); the most honest numbers. | | `subsample_size` | integer | `1000` | Rows per shuffle. (max 20000) | | `num_shuffle_sets` | integer | `3` | Repeats per column. (max 20) | | `time_limit` | number | optional | Seconds. | It returns: | Field | Type | Description | | ---------- | ----------------------------- | ------------------------------------------------------------ | | `fit_id` | string | | | `metric` | string | | | `source` | `data`, `validation`, `train` | Which rows were shuffled; train is in-sample, so optimistic. | | `features` | array of object | | | `usage` | object | | `features` runs from most to least important. ## List, get and delete [Section titled “List, get and delete”](#list-get-and-delete) | | | | ---------------------------- | ----------------------------------------------------------------------------------------------- | | `GET /v1/table/fits` | the project’s live fits: `{"object": "list", "data": [...]}` | | `GET /v1/table/fits/{id}` | one fit | | `PATCH /v1/table/fits/{id}` | `{"name": ..., "ttl_days": ...}`: renames it, or changes how long it is kept after its last use | | `DELETE /v1/table/fits/{id}` | deletes the fit and its stored training table: `{"id": ..., "deleted": true}` | A fit belongs to its project: every key of the project, and the playground, can predict from it; it shows on the project’s Saved models page. Only whoever made it, or an admin of the project, may rename or delete it. A fit lists: | Field | | | ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | `target`, `classes` | the column it predicts, and its classes for a classification | | `columns` | the inputs it needs, each `{"name", "type"}` with type `number` or `category`; extra columns are left out when you predict, a missing one fails the call | | `made_by` | `{"user_id", "key_id", "playground"}`: the member who made it (null for a production key) | | `ttl_days`, `last_used_at`, `expires_at` | kept `ttl_days` (30 by default, 1 to 365) after its last use | | `saved`, `saved_bytes` | whether the trained model itself is stored (it reloads in seconds) | An expired or deleted fit returns `404` with type `fit_not_found`. Every call states its cost in `usage.tokens` and `usage.credits` ([Limits](/models/docs/resources/limits#pricing)). A fit past its preset’s direct size (`fast` 100,000 training rows x 100 columns, `medium` and `pro` 25,000 x 100) answers `async_required`: send it with `"async": true` to run it as an [async job](/models/docs/api/jobs). # Forecast > Forecast a batch of series with ChakraTS. POST`/v1/series/forecast` Forecasts every series in the request `horizon` steps ahead, with nine quantiles at every step. This forecasts monthly airline passengers: the Python and CLI tabs send the whole history and ask for two years; the cURL tab writes the last twelve months into the request by hand and asks for two months: * Python ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" df = pd.read_csv(url + "airline-passengers.csv") # columns: Month, Passengers yh = Client() fc = yh.forecast(df, h=24, time_col="Month", target_col="Passengers", level=[80]) print(fc.df.head(3).round(1)) ``` Output | unique_id | Month | q10 | median | q90 | | --------- | ---------- | ----- | ------ | ----- | | series_0 | 1961-01-01 | 430.5 | 448.5 | 468.0 | | series_0 | 1961-02-01 | 408.9 | 430.9 | 452.0 | | series_0 | 1961-03-01 | 449.0 | 486.7 | 508.2 | * CLI ```sh curl -sO https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv yhatlabs forecast airline-passengers.csv --h 24 \ --time-col Month --target-col Passengers --level 80 -o forecast.csv head -4 forecast.csv ``` Output ```text unique_id,Month,q10,median,q90 series_0,1961-01-01,430.53720868618353,448.541455316843,467.97666760754703 series_0,1961-02-01,408.9291654372314,430.8968252966604,451.962356383921 series_0,1961-03-01,449.0440194902994,486.74538766574983,508.24449670833036 ``` * cURL ```sh curl -s https://api.yhatlabs.com/v1/series/forecast \ -H "Authorization: Bearer $YHAT_API_KEY" \ -H "Content-Type: application/json" \ -d '{"freq": "MS", "horizon": 2, "series": [{"id": "passengers", "values": [417, 391, 419, 461, 472, 535, 622, 606, 508, 461, 390, 432]}]}' ``` Output ```text {"id":"3a90dd3d-e737-465e-b1f9-ca3c8941d464","model":"chakra-ts","horizon":2,"quantile_levels":[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9],"forecasts":[{"id":"passengers","quantiles":[[383.0753173828125,402.9498291015625,413.9801025390625,422.4678039550781,434.37628173828125,446.0346374511719,460.8013610839844,478.62322998046875,502.9939880371094],[364.9206237792969,390.9168395996094,410.5889892578125,423.1913757324219,436.617431640625,454.6253662109375,474.06512451171875,497.9351806640625,532.4006958007812]]}],"usage":{"series":1}} ``` Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast) The cURL tab is the raw request; the other tabs build it from a table for you. ## Request [Section titled “Request”](#request) | Field | Type | Required / default | Description | | ----------------- | --------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `model` | string | `"chakra-ts"` | The model, as GET /v1/models lists it. | | `series` | array of Series | **required** | 1 to 256 series; 8,000,000 points in total, counting covariates. (at most 256) | | `horizon` | integer | **required** | Steps to forecast, at freq. (min 1, max 2048) | | `freq` | string | `"h"` | A pandas frequency alias: 15min, h, D, 2D, W-SUN, MS, QS-OCT, YE-DEC. | | `season` | integer | optional | The seasonal period in steps, to fix it instead of inferring it from freq. (min 1) | | `quantile_levels` | array of number | optional | Any levels in (0, 1); default the nine deciles. (at most 32) | | `samples` | integer | optional | Sample paths per series over the horizon. (min 1, max 1000) | | `seed` | integer | optional | Seed for the sample paths. | | `store` | boolean | `true` | false keeps this call out of your Logs (we still keep a copy to look into errors; never used for training). | | `history` | boolean | `false` | Also return the model’s forecasts of the windows just before the forecast. | | `preset` | `fast`, `pro` | `"fast"` | pro: slower, slightly sharper (models that have presets). | | `tune` | string | optional | Forecast with a tune (POST /v1/series/tunes): the tuned model when it beat the model as it is on your latest window, else the model as it is. The reply’s `tune` says which. | Each series: | Field | Type | Required / default | Description | | ------------------ | ------------------------ | ------------------ | ----------------------------------------------------------------- | | `id` | string | **required** | Unique within the request. (max length 256) | | `values` | array of numbers or null | optional | Oldest first, equally spaced at freq; null marks a missing value. | | `targets` | object | optional | Instead of values: several targets of equal length. | | `past_covariates` | object of arrays | optional | Each as long as the history. | | `known_covariates` | object of arrays | optional | Each as long as the history plus horizon. | Covariates may be numbers, short text categories or `null`. A request may carry 8,000,000 points in total, counting covariates. ## Response [Section titled “Response”](#response) | Field | Type | Description | | ----------------- | ----------------- | ------------------------------------------------------- | | `id` | string | The request id (also the X-Request-Id header). | | `model` | string | | | `horizon` | integer | | | `quantile_levels` | array of number | The levels of every quantiles row, in order. | | `forecasts` | array of Forecast | One per series, in request order. | | `usage` | object | Quota units used: one per target column of each series. | Each entry of `forecasts`: | Field | Type | Description | | ---------------- | ------------------------ | ------------------------------------------------------------------------------------------ | | `id` | string | The series’ id from the request. | | `quantiles` | array of array of number | One row per step, one value per quantile level (\[horizon]\[levels]). | | `targets` | object | Several targets: {column: quantiles}, instead of quantiles. | | `samples` | array of array of number | With samples=N: N paths over the horizon (\[samples]\[horizon]). | | `target_samples` | object | Several targets: {column: samples}. | | `history` | array of Window | With history: the model’s forecasts of the windows just before the forecast, oldest first. | | `target_history` | object | Several targets: {column: history}. | Levels beyond the deciles (`quantile_levels` such as 0.025 or 0.99), `samples` and `history` are listed in the `capabilities` of [GET /v1/limits](/models/docs/api/account). # Async jobs > Run a large table call in the background and fetch its result when it is done. A table call can take minutes. Sent with `"async": true` (or `?async=true`), it runs in the background instead: the reply comes at once, and you fetch the result when the job is done. A fit or one-shot predict past its preset’s direct size (`fast` 100,000 training rows x 100 columns, `medium` and `pro` 25,000 x 100; [Limits](/models/docs/resources/limits)) must run this way: sent directly, it answers `413` with error type `async_required`. | Method and path | What it does | | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | `POST /v1/table/predict`, `POST /v1/table/fits` with `"async": true` | queues the call: `202 {"id": "job_...", "object": "job", "status": "queued"}` | | `GET /v1/jobs/{id}` | its status, and once it succeeded its `result`: the same reply the direct call gives | | `GET /v1/jobs` | the project’s last 100 jobs | | `DELETE /v1/jobs/{id}` | cancels a queued or running job: `{"id": ..., "object": "job", "status": "canceled"}` | ```sh curl https://api.yhatlabs.com/v1/table/fits -H "Authorization: Bearer $YHAT_API_KEY" -H "Content-Type: application/json" \ -d '{"train": [...], "target": "y", "preset": "pro", "async": true}' # {"id": "job_3f1c...", "object": "job", "kind": "fit", "model": "chakra-tab", "status": "queued", "created_at": 1761300000} curl https://api.yhatlabs.com/v1/jobs/job_3f1c... -H "Authorization: Bearer $YHAT_API_KEY" # {"id": "job_3f1c...", "status": "succeeded", "result": {"id": "fit_...", "object": "fit", ...}, ...} ``` A job goes `queued`, `running`, then `succeeded`, `failed` (with an `error` like any other) or `canceled`. Poll every few seconds; a job that waits in the queue for 12 hours expires. Canceling a job that has already finished answers `409`. Its credits are held when it is queued and settled when it ends; a job that fails on our side costs nothing. Jobs show on the project’s Saved models page, under Jobs. A direct table call that is still running after about 20 minutes comes back as a job too: a `202` with `{"object": "job", "id": "job_...", ...}` instead of the result. Check `object` and poll `GET /v1/jobs/{id}` as above. ## In Python [Section titled “In Python”](#in-python) The library does all of this for you. A table past the direct size is sent as a job and waited for, and so is a call that comes back as a job, so `fit` and `predict` return the same result either way. `background=True` returns a `Job` at once: ```python job = yh.fit(train, "target", preset="pro", background=True) job.status() # "queued", "running", "succeeded", "failed" or "canceled" model = job.wait() # the fitted model; waits up to two hours by default (timeout=None: as long as it takes) job.cancel() # True when it was canceled ``` `job.result()` is the same as `job.wait()`. A failed or canceled job raises `JobFailedError`, whose `job_id` names it. # API overview > Base URL, authentication and the conventions every endpoint follows. The REST API serves both models. The Python library and the command line are built on it, and any language can call it directly. ```plaintext https://api.yhatlabs.com ``` ## Authentication [Section titled “Authentication”](#authentication) Send your key in the `Authorization` header. This reads the API’s request limits, a quick way to check the key works: ```sh curl -s https://api.yhatlabs.com/v1/limits -H "Authorization: Bearer $YHAT_API_KEY" | python3 -m json.tool ``` Output ```text { "forecast": { "max_series": 256, "max_points_per_series": 32768, "max_total_points": 8000000, "max_horizon": 2048, "max_columns": 256, "native_quantile_levels": [ 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 ] }, "tabular": { "max_rows": 200000, "max_bytes": 67108864, "presets": [ "fast", "medium", "full" ], "max_quantiles": 32, "fit_ttl_hours": { "default": 24, "max": 168 }, "max_upload_bytes": 1073741824, "max_table_storage_bytes": 10737418240, "max_tables": 200 }, "pricing": { "forecast": { "unit": "series", "counts": "one per target column of each series" }, "tabular": { "unit": "credits", "fit_cells_per_credit": 1000000, "preset_multiplier": { "fast": 1, "medium": 3, "full": 8 }, "predict_rows_per_credit": 10000, "importance_rows_per_credit": 10000, "min_credits": 1 } }, "rate": { "requests_per_minute": 120, "concurrent": { "forecast": 8, "tabular": 2, "upload": 4 } }, "capabilities": { "idempotency_keys": true, "gzip_requests": true, "forecast_quantile_levels": true, "forecast_samples": true, "forecast_history": true, "tabular_distribution": true, "tabular_prediction_sets": true, "fit_groups": true, "table_uploads": true } } ``` ## Endpoints [Section titled “Endpoints”](#endpoints) | Method | Path | What it does | | -------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | | `POST` | [/v1/series/forecast](/models/docs/api/forecast) | forecasts a batch of series | | `POST` | [/v1/table/predict](/models/docs/api/tabular-predict) | fits on a table and predicts rows, in one call | | `POST` | [/v1/table/fits](/models/docs/api/fits) | fits a table once and keeps the fit | | `POST` | [/v1/table/fits/{id}/predict](/models/docs/api/fits#predict-from-a-fit) | predicts rows from a stored fit | | `POST` | [/v1/table/fits/{id}/importance](/models/docs/api/fits#importance) | column importance of a stored fit | | `GET` | [/v1/table/fits](/models/docs/api/fits#list-get-and-delete), `/v1/table/fits/{id}` | lists fits, reads one | | `DELETE` | `/v1/table/fits/{id}` | deletes a fit | | `GET` | [/v1/models](/models/docs/api/account#models), [/v1/usage](/models/docs/api/account#usage), [/v1/limits](/models/docs/api/account#limits) | the key’s models, its quota, and the request caps | | `POST` | [/v1/uploads](/models/docs/api/uploads) | uploads a large table once, to use by reference | | `GET` | [/v1/openapi.json](https://api.yhatlabs.com/v1/openapi.json) | the OpenAPI 3.1 description of every endpoint and field, for client generators and tools | ## Conventions [Section titled “Conventions”](#conventions) * Requests and responses are JSON (`Content-Type: application/json`). * Every response has an `X-Request-Id` header. Quote it when you contact us. * Errors have one shape: `{"error": {"type": ..., "message": ..., "request_id": ...}}`; see [Errors](/models/docs/api/errors). * **Retries without duplicates:** `POST /v1/table/fits` and `POST /v1/table/predict` accept an `Idempotency-Key` header (8 to 128 letters, digits, `-` or `_`). Send the same key when you retry: a call that already succeeded returns its first reply, marked `Idempotent-Replayed: true`, with no second fit and no second charge; a retry that arrives while the first call still runs gets `409 request_in_progress` with `Retry-After`. Failed calls are not kept, so their retry runs again. Keys are kept for 24 hours, per API key. ```sh BODY='{"train": [{"x": 1, "y": 0}, {"x": 2, "y": 0}, {"x": 3, "y": 1}, {"x": 4, "y": 1}, {"x": 5, "y": 1}, {"x": 6, "y": 0}], "target": "y", "test": [{"x": 2.5}]}' KEY="retry-$(date +%s)" for attempt in 1 2; do # the second call is what a retry after a dropped connection sends curl -s -D - -o /dev/null https://api.yhatlabs.com/v1/table/predict \ -H "Authorization: Bearer $YHAT_API_KEY" -H "Idempotency-Key: $KEY" -H "Content-Type: application/json" -d "$BODY" \ | grep -iE "^HTTP|^idempotent-replayed" | tr -d '\r' done ``` Output ```text HTTP/2 200 HTTP/2 409 ``` * **Capabilities:** `GET /v1/limits` lists, under `capabilities`, the features this API has switched on (`idempotency_keys`, `gzip_requests`, …). A missing flag means off. * **Long calls:** a call that runs longer than 30 seconds (a large tabular fit, for example) switches to a `200` response that sends a space every 20 seconds and then the JSON body. Leading spaces are valid JSON, so ordinary clients parse it unchanged, and the connection never idles long enough for a proxy to drop it. An error after the switch arrives in the body as `{"error": ...}` with status `200`, so check for an `error` key. # Table predict > Fit ChakraTab on a table and predict rows, in one call. POST`/v1/table/predict` Fits on `train` and predicts `test` in one call, and keeps nothing afterwards. To predict repeatedly from one fit, use [/v1/table/fits](/models/docs/api/fits). This learns whether a customer bought from ten rows and predicts two new ones: * Python ```python from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from yhatlabs import Client X, y = load_breast_cancer(return_X_y=True, as_frame=True) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) yh = Client() model = yh.fit(X_train.assign(diagnosis=y_train), target="diagnosis") res = model.predict(X_test) print(res.df.head(3).round(3)) print("accuracy:", round((res.predictions == y_test).mean(), 3)) model.delete() ``` Output | | prediction | p_0 | p_1 | | --- | ---------- | ----- | ----- | | 512 | 0 | 1.000 | 0.000 | | 457 | 1 | 0.013 | 0.987 | | 439 | 1 | 0.000 | 1.000 | ``` accuracy: 0.979 ``` * cURL ```sh curl -s https://api.yhatlabs.com/v1/table/predict \ -H "Authorization: Bearer $YHAT_API_KEY" \ -H "Content-Type: application/json" \ -d '{"target": "bought", "train": [{"visits": 1, "plan": "free", "bought": 0}, {"visits": 9, "plan": "pro", "bought": 1}, {"visits": 2, "plan": "free", "bought": 0}, {"visits": 7, "plan": "pro", "bought": 1}, {"visits": 3, "plan": "free", "bought": 0}, {"visits": 8, "plan": "pro", "bought": 1}, {"visits": 1, "plan": "pro", "bought": 0}, {"visits": 6, "plan": "free", "bought": 1}, {"visits": 2, "plan": "pro", "bought": 0}, {"visits": 9, "plan": "free", "bought": 1}], "test": [{"visits": 8, "plan": "pro"}, {"visits": 1, "plan": "free"}]}' \ | python3 -c "import sys, json; r = json.load(sys.stdin); print(r['predictions'], r['classes'], r['probabilities'])" ``` Output ```text [1, 0] [0, 1] [[0.000736, 0.999264], [0.999706, 0.000294]] ``` Parameters: [`Client.predict`](/models/docs/reference/python#client-predict) ## Request [Section titled “Request”](#request) | Field | Type | Required / default | Description | | -------------- | ------------------------------------ | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `train` | table | **required** | Rows including the target column. | | `target` | string | **required** | The column to predict. | | `test` | table | **required** | Rows to predict, with the same feature columns. | | `quantiles` | array of number | optional | Regression: interval levels, 1 to 32. (at most 32) | | `set_coverage` | number | optional | Classification: prediction sets with this coverage. | | `model` | string | `"chakra-tab"` | The model, as GET /v1/models lists it. | | `preset` | `fast`, `medium`, `pro`, `full` | `"fast"` | fast: the quickest; medium: more accurate, about 3x the credits and 2-3x the time; pro: the most accurate, about 8x the credits and 4-8x the time (full is the same, its earlier name). | | `problem_type` | `binary`, `multiclass`, `regression` | optional | Inferred from the target when left out. | | `eval_metric` | string | optional | What validation optimises: log_loss (default), roc_auc, f1, …; rmse (default), mae, r2. | | `time_limit` | number | optional | Seconds for the whole call. | | `seed` | integer | `0` | Random seed; the same seed gives the same fit. | | `store` | boolean | `true` | false keeps this call out of your Logs (we still keep a copy to look into errors; never used for training). | | `groups` | string | optional | A train column: validation folds hold out whole groups; not used as a feature. | | `time_col` | string | optional | A train column: validation folds are contiguous periods. | **URL parameters:** `model`, `async` and `store` can also go on the URL. | Parameter | Example | Same as | | --------- | ---------------------- | -------------------------------------------------------------------------------------------- | | `model` | `?model=chakra-tab-v2` | `model` in the body. Naming one model in the URL and another in the body answers `400`. | | `async` | `?async=true` | `"async": true`: run the call as a [job](/models/docs/api/jobs). | | `store` | `?store=false` | `"store": false`: keep the call out of your Logs. The `X-Store: false` header does the same. | A **table** is a list of row objects, `{"format": "parquet_b64", "bytes": ""}`, or an uploaded table `{"format": "table", "id": "tbl_...", "rows": [...], "drop": [...]}` ([/v1/uploads](/models/docs/api/uploads)). Up to 200,000 rows in a call, and 64 MB per request body. **Presets:** start on `fast`, which takes seconds on a few thousand rows; `medium` is more accurate, about 3x the credits and 2-3x as long; `pro` is the most accurate, about 8x the credits and 4-8x as long as `fast` (`full` is still accepted, as `pro`). **Size:** a direct call takes up to 100,000 training rows x 100 columns on `fast`, and 25,000 x 100 on `medium` and `pro`. Past that it answers `413` with error type `async_required`: send it with `"async": true` to run it as a [job](/models/docs/api/jobs). A direct call that runs longer than about 20 minutes comes back as a job object (`"object": "job"`) to poll. **Logs:** `"store": false` and the call isn’t shown in your Logs ([Data handling](/models/docs/resources/data-handling)). **Large requests:** a request body over 4 MB is stored as it arrives and runs as a job, so its size caps are a job’s (50,000,000 training cells); the reply still comes back directly, or as a job after about 20 minutes. Its fields and uploaded tables work as in any request. For large tables, [upload](/models/docs/api/uploads) them once and refer to them: the Python library does this for any table over 8 MB. ## Response [Section titled “Response”](#response) | Field | Type | Description | | ----------------- | --------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | `predictions` | array of number or string or boolean | One per test row: a number, or a class label in its own type. | | `probabilities` | array of array of number | Classification: one row per test row, one column per class. | | `classes` | array of number or string or boolean | Classification: the class of each probabilities column. | | `quantile_levels` | array of number | Regression with quantiles: the levels. | | `quantiles` | array of array of number | Regression with quantiles: one row per test row. | | `interval_method` | `distribution`, `conformal` | distribution: each row’s own predictive distribution; conformal: the same width for every row (fallback). | | `mean` | array of number | Of each row’s predictive distribution. | | `median` | array of number | | | `prediction_sets` | array of array of number or string or boolean | Classification with set_coverage: the classes per row that hold the true one that often. | | `set_coverage` | number | The coverage the sets were built for. | | `restored` | boolean | Fits only: the fit was rebuilt from its training table before predicting (it had to be loaded again). | | `fit` | object | One-shot predict only: rows, features, seconds, problem type, metric, preset, seed, version. | | `usage` | object | Predicted rows, and the credits the call cost (up to 3 decimals, e.g. 0.02). | Class labels come back in their own type: a class trained as `1` is `1`, and `true` is `true`. The call costs the credits of a fit plus a prediction ([Limits](/models/docs/resources/limits)); `usage.credits` says how many. ## Compare with standard models [Section titled “Compare with standard models”](#compare-with-standard-models) POST`/v1/table/compare` Trains standard models on the same `train` and predicts the same `test`, so ChakraTab can be scored against them on equal terms. It takes `train`, `target` and `test` as above (a `test` that still holds the target column is fine; it is ignored), `problem_type`, `store`, and `models`: a list of `xgboost`, `random_forest`, `linear` (the default three) and `lightgbm`. The reply has each model’s `predictions` (and `probabilities` for a classification), its training time `fit_s`, and a naive `baseline` (the most common class, or the mean). Scores are left to you, so every model is scored the same way; in Python, `res.comparison.score(actual, ChakraTab=res)` does it ([Evaluating](/models/docs/tabular/evaluating#compare-with-standard-models)). It is a direct call, up to 100,000 training rows x 100 columns, and costs training rows x feature columns x 0.5 plus the predicted cells, in tokens ([Limits](/models/docs/resources/limits#pricing)). # Tunes > Fine-tune ChakraTS on your series, then forecast with the tune. | Method and path | What it does | | ---------------------------------------------------- | ------------------------------------------------ | | `POST /v1/series/tunes` | starts a tune (a background job) | | `GET /v1/jobs/{id}` | the job; once it succeeded, `result` is the tune | | `GET /v1/series/tunes`, `GET /v1/series/tunes/{id}` | lists the project’s tunes, reads one | | `DELETE /v1/series/tunes/{id}` | deletes a tune | | `POST /v1/series/forecast` with `"tune": "tune_..."` | forecasts with a tune | In Python and the CLI this is `yh.tune(...)` and `yhatlabs tune`, from yhatlabs 0.2.2. See [Tuning on your data](/models/docs/time-series/tuning) for what a tune does and when it helps. ## Start a tune [Section titled “Start a tune”](#start-a-tune) POST`/v1/series/tunes` The body is a [forecast request](/models/docs/api/forecast) (`series`, `horizon`, `freq`, `season`, `model`) plus: | Field | Type | Meaning | | ---------- | -------------------- | ----------------------------------------------------------------------------- | | `steps` | integer, 50 to 1,000 | training steps (default 300); the best count is picked on the held-back steps | | `name` | string | a label | | `ttl_days` | number, at most 365 | how long the tune is kept after its last use (default 30) | The reply is `202` with a job: `{"id": "job_...", "object": "job", "kind": "tune", "status": "queued"}`. Poll `GET /v1/jobs/{id}` (a tune takes a few minutes). A series shorter than `2 x horizon + 64` values fails the job with an `invalid_request_error` saying so, and its credits are given back. ## The tune [Section titled “The tune”](#the-tune) | Field | Meaning | | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `id` | `tune_...`, for `"tune"` in a forecast | | `used` | `true` when the tuned forecast beat the model as it is on the last `horizon` steps of your series; otherwise forecasts with this tune are the model as it is | | `report.holdout` | `zero_shot` and `tuned` scores on those steps: `wape` and `loss` (scaled quantile loss) | | `horizon`, `freq`, `series`, `steps`, `model`, `name` | what was tuned | | `ttl_days`, `last_used_at`, `expires_at` | how long it is kept | | `usage` | tokens and credits | ## Forecast with a tune [Section titled “Forecast with a tune”](#forecast-with-a-tune) Add `"tune": "tune_..."` to a forecast request with the same `model`. The reply carries `"tune": {"id", "used", "holdout"}`, so every forecast says whether it used the tuning. # Uploads > Store a large table once, by content hash, and refer to it from any tabular call. | Method and path | What it does | | ------------------------- | -------------------------------------------------- | | `POST /v1/uploads` | asks for an upload slot for a file, by its SHA-256 | | `PUT /v1/uploads/{id}` | sends the file, when no signed URL is given | | `GET /v1/uploads/{id}` | reads an upload’s record | | `DELETE /v1/uploads/{id}` | deletes a stored table | Tables too large to send inline (the Python library uploads any table over 8 MB as parquet; for your own client, anything over about 4 MB) are stored once and referred to by id. The same file is never sent twice: its id comes from its SHA-256, and asking for a slot for a stored file answers `exists: true`. ## Ask for a slot [Section titled “Ask for a slot”](#ask-for-a-slot) POST`/v1/uploads` It takes: | Field | Type | Required / default | Description | | ------------ | ----------- | ------------------ | --------------------------------------------------------------------- | | `sha256` | string | **required** | The file’s SHA-256, lowercase hex; the table’s id is derived from it. | | `size_bytes` | integer | **required** | The file’s size, at most 1 GB. | | `format` | `"parquet"` | `"parquet"` | | It returns: | Field | Type | Description | | -------- | ------- | ------------------------------------------------------------------------------------------------------------------ | | `id` | string | tbl\_…, for {format: table, id} in any tabular call. | | `exists` | boolean | true: already stored, nothing to send. | | `upload` | object | Where to PUT the file: a signed storage URL (auth false), or a path on this API to send with your key (auth true). | PUT the file to `upload.url`: a signed storage URL needs no key; a path on this API (`auth: true`) is sent with your key. ## Use it [Section titled “Use it”](#use-it) Any tabular field that takes a table (`train`, `test`, `data`) takes `{"format": "table", "id": "tbl_..."}`, optionally with `rows` (row positions to use) and `drop` (columns to leave out). One upload can then serve every fold of a cross-validation: each call names its rows, and the test rows drop the target. A table is checked the first time a call uses it: its bytes must match the hash it was uploaded under and be a parquet file; one that fails is deleted and the call gets a clear error. ## Limits and housekeeping [Section titled “Limits and housekeeping”](#limits-and-housekeeping) | | | | ------------------------- | ----------------------------------------------------------------------------------- | | One file | 1 GB; at most 1,000,000 rows, 100,000,000 cells and 4 GB once decompressed | | Per key | 10 GB and 200 tables in total; over either, `413 storage_full`: delete tables first | | `GET /v1/uploads/{id}` | the table’s size and upload time | | `DELETE /v1/uploads/{id}` | deletes it; a fit made from it can no longer be rebuilt | Uploaded tables are private to the key that uploaded them: nothing can download them except the model, for that key’s calls. # Choosing a model > Decide between time-series forecasting and tabular prediction, and see what each returns. There are two models. Pick by the shape of your data and the question you are asking. | You have | You want | Use | | ------------------------------------------------------------------ | ----------------------------- | ---------------------------------------------------------------------------------- | | Values over time: sales, load, traffic, sensor readings | What comes next, with a range | **ChakraTS**: [`yh.forecast`](/models/docs/time-series/forecasting) | | The same, plus things you know ahead (prices, weather, promotions) | A forecast that uses them | **ChakraTS** with [`known=`](/models/docs/time-series/covariates) | | Recent values over time | Which points were unusual | **ChakraTS**: [`yh.detect_anomalies`](/models/docs/time-series/anomalies-and-gaps) | | Rows with an answer column (churned, price, diagnosis) | The answer for new rows | **ChakraTab**: [`yh.fit(...).predict(...)`](/models/docs/tabular/predicting) | | A table with empty cells | The most likely values | **ChakraTab**: [`yh.impute`](/models/docs/tabular/imputation) | ## Time series or a table? [Section titled “Time series or a table?”](#time-series-or-a-table) * **Time series:** the order of the rows matters, and the question is “what happens next”. Each series is a column of values at regular times. * **Table:** each row stands on its own, and the question is “what is the answer for this row”. Some problems could be either. Predicting which customers churn next month is a **table**: each customer is a row with features. Forecasting how many customers churn per month is a **time series**: one value per month. ## What each returns [Section titled “What each returns”](#what-each-returns) | | ChakraTS | ChakraTab | | ----------- | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | Best guess | the median for every future step | a class, or a number | | Uncertainty | intervals at any level for every step, and sample paths | class probabilities and prediction sets, or a per-row distribution with intervals at any level | | Checking it | backtests and calibration | accuracy on held-out rows, column importance | | State | nothing is stored | one-shot, or a stored fit you predict from repeatedly | Details, limits and benchmark results: [ChakraTS](/models/docs/models/chakra-ts), [ChakraTab](/models/docs/models/chakra-tab). # Cookbook > Getting-started notebooks for each model and end-to-end recipes on public data. Worked examples on public data, from loading the data to scoring the result. Each one is a notebook in the [yhatlabs-cookbook](https://github.com/yhatlabs/yhatlabs-cookbook) repository: open it and run it. ## Get started [Section titled “Get started”](#get-started) One notebook per model, from install to a scored result in a few minutes. Time seriesAPI ### [ChakraTS](https://github.com/yhatlabs/yhatlabs-cookbook/blob/main/getting-started/chakrats.ipynb) Forecasts a week of electricity demand with ranges, checks the model on past days, adds known future information, and fine-tunes it. [Open in Colab](https://colab.research.google.com/github/yhatlabs/yhatlabs-cookbook/blob/main/getting-started/chakrats.ipynb)[](https://github.com/yhatlabs/yhatlabs-cookbook/blob/main/getting-started/chakrats.ipynb "View on GitHub") TablesAPI ### [ChakraTab](https://github.com/yhatlabs/yhatlabs-cookbook/blob/main/getting-started/chakratab.ipynb) Predicts credit risk with probabilities, compares with standard models, shows which columns matter, and predicts house prices with ranges. [Open in Colab](https://colab.research.google.com/github/yhatlabs/yhatlabs-cookbook/blob/main/getting-started/chakratab.ipynb)[](https://github.com/yhatlabs/yhatlabs-cookbook/blob/main/getting-started/chakratab.ipynb "View on GitHub") Time seriesOpen weights ### [ChakraTS-OS-10M](https://github.com/yhatlabs/yhatlabs-cookbook/blob/main/getting-started/chakrats-os-10m.ipynb) The ChakraTS steps on your own machine, using yhatmodels, with no API key. [Open in Colab](https://colab.research.google.com/github/yhatlabs/yhatlabs-cookbook/blob/main/getting-started/chakrats-os-10m.ipynb)[](https://github.com/yhatlabs/yhatlabs-cookbook/blob/main/getting-started/chakrats-os-10m.ipynb "View on GitHub") ## Recipes [Section titled “Recipes”](#recipes) The recipes use our hosted models through the Python library and need an API key. Time seriesTablesAPI ### [Forecasting with ChakraTab](https://github.com/yhatlabs/yhatlabs-cookbook/blob/main/recipes/forecasting/forecasting_with_chakratab.ipynb) Daily forecasts from a table of drivers, scored on held-out weeks. [Open in Colab](https://colab.research.google.com/github/yhatlabs/yhatlabs-cookbook/blob/main/recipes/forecasting/forecasting_with_chakratab.ipynb)[](https://github.com/yhatlabs/yhatlabs-cookbook/blob/main/recipes/forecasting/forecasting_with_chakratab.ipynb "View on GitHub") More recipes are coming soon. # ChakraTab > Predict on any table without training or tuning. What ChakraTab does, what it replaces, and its results on real data and public benchmarks. **Predict on any table, with no training or tuning.** Send rows with the answers you have and the rows to answer; get a class with probabilities, or a number with an interval, for every new row. ChakraTab replaces tuning XGBoost, LightGBM or CatBoost and long AutoML runs. | | | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Benchmarks** | 3rd on [TabArena and RamanBench](#public-benchmarks), run by the benchmark teams through our API | | **Against classical methods** | better than tuned and combined gradient boosting on most tables, with no feature engineering | | **Speed** | seconds to minutes per table | | **Use it as** | model `chakra-tab` in the [Python library](/models/docs/tools/python), the [CLI](/models/docs/tools/cli) or the [API](/models/docs/api/tabular-predict) | | **Model card** | [huggingface.co/yhatlabs/ChakraTab](https://huggingface.co/yhatlabs/ChakraTab) | ## What it replaces [Section titled “What it replaces”](#what-it-replaces) | Today | With ChakraTab | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Encoding categories, imputing missing values, scaling | the table as it is: numbers, categories, dates and missing values | | Hyperparameter search and model selection | one call; `preset=` trades time for accuracy | | Probabilities to recalibrate, intervals from extra models | calibrated probabilities, [prediction sets](/models/docs/tabular/intervals-and-importance#sets-of-classes), and a [distribution for every row](/models/docs/tabular/intervals-and-importance#prediction-intervals) | | A training pipeline to maintain | a new fit in one call when the data changes | ## A prediction in one call [Section titled “A prediction in one call”](#a-prediction-in-one-call) * Python ```python from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from yhatlabs import Client X, y = load_breast_cancer(return_X_y=True, as_frame=True) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) yh = Client() model = yh.fit(X_train.assign(diagnosis=y_train), target="diagnosis") res = model.predict(X_test) print(res.df.head(3).round(3)) print("accuracy:", round((res.predictions == y_test).mean(), 3)) model.delete() ``` Output | | prediction | p_0 | p_1 | | --- | ---------- | ----- | ----- | | 512 | 0 | 1.000 | 0.000 | | 457 | 1 | 0.013 | 0.987 | | 439 | 1 | 0.000 | 1.000 | ``` accuracy: 0.979 ``` * cURL ```sh curl -s https://api.yhatlabs.com/v1/table/predict \ -H "Authorization: Bearer $YHAT_API_KEY" \ -H "Content-Type: application/json" \ -d '{"target": "bought", "train": [{"visits": 1, "plan": "free", "bought": 0}, {"visits": 9, "plan": "pro", "bought": 1}, {"visits": 2, "plan": "free", "bought": 0}, {"visits": 7, "plan": "pro", "bought": 1}, {"visits": 3, "plan": "free", "bought": 0}, {"visits": 8, "plan": "pro", "bought": 1}, {"visits": 1, "plan": "pro", "bought": 0}, {"visits": 6, "plan": "free", "bought": 1}, {"visits": 2, "plan": "pro", "bought": 0}, {"visits": 9, "plan": "free", "bought": 1}], "test": [{"visits": 8, "plan": "pro"}, {"visits": 1, "plan": "free"}]}' \ | python3 -c "import sys, json; r = json.load(sys.stdin); print(r['predictions'], r['classes'], r['probabilities'])" ``` Output ```text [1, 0] [0, 1] [[0.000736, 0.999264], [0.999706, 0.000294]] ``` Parameters: [`Client.predict`](/models/docs/reference/python#client-predict) ## What it does [Section titled “What it does”](#what-it-does) | | | | ----------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | [Predicting](/models/docs/tabular/predicting) | binary and multiclass classification, regression, several targets at once; one-shot or from a stored fit | | [Intervals and sets](/models/docs/tabular/intervals-and-importance) | an interval at any level for every row, prediction sets for classes, honest for new groups with `groups=` | | [Evaluating](/models/docs/tabular/evaluating) | cross-validation on your own table: accuracy and calibration | | [Checking predictions](/models/docs/tabular/checking-predictions) | which rows lie outside the training data, and the chance of crossing a limit | | [Importance and effects](/models/docs/tabular/intervals-and-importance#column-importance) | which columns matter, and how each one moves the prediction | | [Imputation](/models/docs/tabular/imputation) | missing cells filled from the other columns | ## Results on real data [Section titled “Results on real data”](#results-on-real-data) Error against the best of tuned and combined CatBoost, LightGBM and XGBoost on each dataset, on the TabArena protocol: 1 − AUC, log loss or RMSE. | Industry | Task | Data | Error vs best classical | | ---------- | ---------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------- | | Retail | **Campaign response** | [Marketing campaign, 2,240 customers](https://www.openml.org/search?type=task\&id=363684) | **14% lower** 1 − AUC | | Finance | **Company bankruptcy** | [Polish companies, 5 years](https://www.openml.org/search?type=task\&id=363694) | **87% lower** 1 − AUC | | Finance | **Company bankruptcy** | [Taiwanese companies, 1999 to 2009](https://www.openml.org/search?type=task\&id=363706) | **20% lower** 1 − AUC | | Healthcare | **Maternal health risk** | [Clinical readings, 1,014 patients](https://www.openml.org/search?type=task\&id=363685) | **18% lower** log loss | | Healthcare | **Blood donation** | [Transfusion service centre, 748 donors](https://www.openml.org/search?type=task\&id=363621) | **10% lower** 1 − AUC | | Industrial | **Truck component failure** | [Scania APS system, 76,000 trucks](https://www.openml.org/search?type=task\&id=363616) | **15% lower** 1 − AUC | | Industrial | **Contaminant detection** | [Hazelnut spread production line](https://www.openml.org/search?type=task\&id=363674) | **79% lower** 1 − AUC | | Tech | **Customer churn** | [Telco subscribers, 5,000 accounts](https://www.openml.org/search?type=task\&id=363623) | **15% lower** 1 − AUC | | Transport | **Passenger satisfaction** | [Airline survey, 130,000 passengers](https://www.openml.org/search?type=task\&id=363628) | **19% lower** 1 − AUC | | Research | **Protein structure** | [Physicochemical properties, 45,000 decoys](https://www.openml.org/search?type=task\&id=363693) | **16% lower** RMSE | | Research | **Biodegradability** | [QSAR, 1,055 chemicals](https://www.openml.org/search?type=task\&id=363696) | **14% lower** 1 − AUC | | Research | **Star and galaxy classification** | [Sloan Digital Sky Survey DR17](https://www.openml.org/search?type=task\&id=363699) | **16% lower** log loss | ## Public benchmarks [Section titled “Public benchmarks”](#public-benchmarks) Standings on the independent leaderboards, as their maintainers publish them. [TabArena](https://huggingface.co/spaces/TabArena/leaderboard) (Amazon) **ChakraTab: 3rd among all models.** Elo 1904, verified by the TabArena team on all 51 datasets. As of November 2026. [RamanBench](https://huggingface.co/spaces/HTW-KI-Werkstatt/RamanBench) (HTW Berlin) **ChakraTab: 3rd among all models.** Elo 1512, run by the RamanBench team on all 135 tasks. As of November 2026. [STRABLE](https://soda-inria.github.io/strable) (Inria) **ChakraTab: 3rd by score.** Score 0.833 with TILE-Llama3.1-70B, median R² and AUC. As of November 2026. ## ChakraTab v2 (private preview) [Section titled “ChakraTab v2 (private preview)”](#chakratab-v2-private-preview) ChakraTab v2 is our newer tabular model, strongest on wide tables (hundreds to thousands of columns). It is enabled per organization while in preview: [ask us](/models/docs/resources/support) to turn it on for yours. It takes the same calls and returns the same outputs (probabilities, intervals, prediction sets, importance, saved fits); pass its name as the model: ```python yh.predict(train, "target", test, model="chakra-tab-v2") yh.models() # the models your key can use: chakra-tab-v2 is listed once it is enabled ``` Over the API it is `"model": "chakra-tab-v2"`, and `GET /v1/models` lists it for organizations that have it. ## Limits per call [Section titled “Limits per call”](#limits-per-call) | | | | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Rows | 200,000 per call; a direct call up to 100,000 training rows x 100 columns on `fast`, 25,000 x 100 on `medium` and `pro` (larger tables run as [jobs](/models/docs/api/jobs)) | | Request size | 64 MB inline; larger tables are uploaded once ([Uploads](/models/docs/api/uploads)) | | Presets | `fast` (default; start here), `medium` (more accurate, about 3x the credits and 2-3x the time), `pro` (the most accurate, about 8x the credits and 4-8x the time) | | Stored fits | kept 30 days after their last use by default, 1 to 365 (`ttl_days`) | See [Limits](/models/docs/resources/limits) for rates and credits. # ChakraTS > Forecast any time series without training. What ChakraTS does, what it replaces, and its results on real data and public benchmarks. **Forecast any time series, with no training.** Send the history, get the next steps back, each with a range of likely outcomes. ChakraTS replaces fitting ARIMA, ETS or Prophet series by series, and the feature-engineered machine-learning pipelines built around them. | | | | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | **Benchmarks** | 1st among zero-shot models on [fev-bench, GIFT-Eval and TIME](#public-benchmarks), the open forecasting leaderboards | | **Against classical methods** | better on 98 of 100 fev-bench tasks than seasonal naive, ETS, ARIMA, LightGBM and CatBoost | | **Speed** | seconds per call, for up to 256 series and 2,048 steps ahead | | **Use it as** | model `chakra-ts` in the [Python library](/models/docs/tools/python), the [CLI](/models/docs/tools/cli) or the [API](/models/docs/api/forecast) | | **Model card** | [huggingface.co/yhatlabs/ChakraTS](https://huggingface.co/yhatlabs/ChakraTS) | ## What it replaces [Section titled “What it replaces”](#what-it-replaces) | Today | With ChakraTS | | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | A model fitted per series, refitted as new data arrives | one call forecasts every series; nothing to fit or refit | | Lags, rolling means and calendar features built by hand for a boosting model | the raw history, plus any [covariates](/models/docs/time-series/covariates) you have | | A point forecast, with intervals added afterwards | a range at every step, calibrated on each series’ own past, and [sample paths](/models/docs/time-series/forecasting#sample-paths) for totals and peaks | | A separate model per frequency or domain | one model from minutes to years, for any domain | ## A forecast in one call [Section titled “A forecast in one call”](#a-forecast-in-one-call) * Python ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" df = pd.read_csv(url + "airline-passengers.csv") # columns: Month, Passengers yh = Client() fc = yh.forecast(df, h=24, time_col="Month", target_col="Passengers", level=[80]) print(fc.df.head(3).round(1)) ``` Output | unique_id | Month | q10 | median | q90 | | --------- | ---------- | ----- | ------ | ----- | | series_0 | 1961-01-01 | 430.5 | 448.5 | 468.0 | | series_0 | 1961-02-01 | 408.9 | 430.9 | 452.0 | | series_0 | 1961-03-01 | 449.0 | 486.7 | 508.2 | * CLI ```sh curl -sO https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv yhatlabs forecast airline-passengers.csv --h 24 \ --time-col Month --target-col Passengers --level 80 -o forecast.csv head -4 forecast.csv ``` Output ```text unique_id,Month,q10,median,q90 series_0,1961-01-01,430.53720868618353,448.541455316843,467.97666760754703 series_0,1961-02-01,408.9291654372314,430.8968252966604,451.962356383921 series_0,1961-03-01,449.0440194902994,486.74538766574983,508.24449670833036 ``` * cURL ```sh curl -s https://api.yhatlabs.com/v1/series/forecast \ -H "Authorization: Bearer $YHAT_API_KEY" \ -H "Content-Type: application/json" \ -d '{"freq": "MS", "horizon": 2, "series": [{"id": "passengers", "values": [417, 391, 419, 461, 472, 535, 622, 606, 508, 461, 390, 432]}]}' ``` Output ```text {"id":"3a90dd3d-e737-465e-b1f9-ca3c8941d464","model":"chakra-ts","horizon":2,"quantile_levels":[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9],"forecasts":[{"id":"passengers","quantiles":[[383.0753173828125,402.9498291015625,413.9801025390625,422.4678039550781,434.37628173828125,446.0346374511719,460.8013610839844,478.62322998046875,502.9939880371094],[364.9206237792969,390.9168395996094,410.5889892578125,423.1913757324219,436.617431640625,454.6253662109375,474.06512451171875,497.9351806640625,532.4006958007812]]}],"usage":{"series":1}} ``` Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast) ## What it does [Section titled “What it does”](#what-it-does) | | | | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | [Forecasts](/models/docs/time-series/forecasting) | quantiles at every step, 95% and 99% intervals, the mean, sample paths, the chance of crossing a limit | | [Covariates](/models/docs/time-series/covariates) | values known ahead (prices, weather forecasts, holidays), history-only signals, per-series constants | | [Backtesting](/models/docs/time-series/backtesting) | rolling windows on your own history, scored against seasonal naive, with calibration | | [Scenarios](/models/docs/time-series/scenarios) | one forecast per what-if future of the covariates | | [Hierarchies](/models/docs/time-series/hierarchies) | forecasts of stores, regions and totals that add up | | [Anomalies and gaps](/models/docs/time-series/anomalies-and-gaps) | a score for every recent point, and missing values filled | ## Results on real data [Section titled “Results on real data”](#results-on-real-data) Error against the best classical method on each dataset (seasonal naive, AutoETS, AutoARIMA, a combination of statistical models, LightGBM and CatBoost), on the fev-bench protocol: scaled quantile loss over rolling windows. | Industry | Task | Data | Error vs best classical | | ---------- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------- | | Energy | **Grid load, day ahead** | [ERCOT daily system load](https://huggingface.co/datasets/autogluon/fev_datasets/viewer/ercot_1D) | **24% lower** SQL, 28 steps | | Energy | **Day-ahead power prices** | [German market, EPF](https://huggingface.co/datasets/autogluon/fev_datasets/viewer/epf_de) | **60% lower** SQL, 24 steps | | Energy | **Wind farm output** | [10-minute turbine power, KDD Cup 2022](https://huggingface.co/datasets/autogluon/fev_datasets/viewer/kdd_cup_2022_10T) | **40% lower** SQL, 288 steps | | Retail | **Product demand** | [M5 daily unit sales by item](https://huggingface.co/datasets/autogluon/fev_datasets/viewer/m5_1D) | **15% lower** SQL, 28 steps | | Retail | **Grocery orders** | [Rohlik daily orders by warehouse](https://huggingface.co/datasets/autogluon/fev_datasets/viewer/rohlik_sales_1D) | **31% lower** SQL, 14 steps | | Finance | **Macro indicators** | [FRED-MD, 120 monthly US series](https://huggingface.co/datasets/autogluon/fev_datasets/viewer/fred_md_2025) | **10% lower** SQL, 12 steps | | Healthcare | **COVID cases** | [UK nations, daily new cases](https://huggingface.co/datasets/autogluon/fev_datasets/viewer/uk_covid_nation_1D) | **20% lower** SQL, 28 steps | | Industrial | **Transformer temperature** | [ETT hourly oil temperature](https://huggingface.co/datasets/autogluon/fev_datasets/viewer/ETT_1H) | **19% lower** SQL, 168 steps | | Tech | **Cloud query volume** | [Amazon Redshift, 5-minute](https://huggingface.co/datasets/autogluon/fev_datasets/viewer/redset_5T) | **41% lower** SQL, 288 steps | | Tech | **IT operations metrics** | [BizITObs, 5-minute](https://huggingface.co/datasets/autogluon/fev_datasets/viewer/bizitobs_l2c_5T) | **41% lower** SQL, 288 steps | | Transport | **Highway traffic** | [Seattle loop detectors, 5-minute](https://huggingface.co/datasets/autogluon/fev_datasets/viewer/LOOP_SEATTLE_5T) | **30% lower** SQL, 288 steps | | Transport | **Road speeds** | [Shenzhen taxi GPS, hourly](https://huggingface.co/datasets/autogluon/fev_datasets/viewer/SZ_TAXI_1H) | **40% lower** SQL, 168 steps | ## Public benchmarks [Section titled “Public benchmarks”](#public-benchmarks) Standings on the independent leaderboards, as their maintainers publish them. [fev-bench](https://huggingface.co/spaces/autogluon/fev-leaderboard) (Amazon) **ChakraTS: 1st among all models.** Skill score 51.4, win rate 90.1%. As of November 2026. [GIFT-Eval](https://huggingface.co/spaces/Salesforce/GIFT-Eval) (Salesforce) **ChakraTS: 1st among zero-shot models.** MASE 0.640, CRPS 0.436. As of November 2026. [TIME](https://huggingface.co/spaces/Real-TSF/TIME-leaderboard) (ICML 2026) **ChakraTS: 1st among zero-shot models.** MASE 0.623, CRPS 0.522. As of November 2026. ## Limits per request [Section titled “Limits per request”](#limits-per-request) | | | | ---------------------- | ------------------------------------------------------------------- | | Series | 256 (the Python library splits larger inputs into several requests) | | Points per series | 32,768 (the most recent are kept) | | Points per request | 8,000,000, including covariates | | Horizon | 2,048 steps | | Targets and covariates | 256 columns per series | `GET /v1/limits` returns the current values. See [Limits](/models/docs/resources/limits) for rates and quotas. # Open models > Forecasting models you download and run on your own machine, with the yhatmodels library. Open models are YHat Labs models whose weights you download and run on your own machine, with the `yhatmodels` Python library and command line. There is no API key to manage, and your data never leaves your computer. ![ChakraTS-OS-10M forecasting a week of hourly electricity demand on the Texas Gulf Coast, next to what happened](https://raw.githubusercontent.com/yhatlabs/yhatmodels/main/docs/assets/forecast_light.png)![ChakraTS-OS-10M forecasting a week of hourly electricity demand on the Texas Gulf Coast, next to what happened](https://raw.githubusercontent.com/yhatlabs/yhatmodels/main/docs/assets/forecast_dark.png) A week of hourly electricity demand on the Texas Gulf Coast, forecast from two weeks of history, with no training. Data: [ERCOT](https://www.ercot.com). ## Models [Section titled “Models”](#models) | Model | Task | Parameters | History read | License | | ----------------------------------------------------------- | ----------- | ---------- | ------------------ | -------------------------------------------------- | | [ChakraTS-OS-10M](/models/docs/open-models/chakrats-os-10m) | Forecasting | 10.6M | up to 32,768 steps | [Non-commercial](/models/docs/open-models/license) | ChakraTS-OS-10M is the most accurate open forecasting model under 100M parameters on fev-bench. It uses past and known-future covariates, forecasts several targets of a series together, and runs on a laptop CPU. ## Start here [Section titled “Start here”](#start-here) [Install and license](/models/docs/open-models/install)Install the library and accept the model license once. [Quickstart](/models/docs/open-models/quickstart)A first forecast from NumPy, pandas or the command line. ## Open models or the API? [Section titled “Open models or the API?”](#open-models-or-the-api) | | Open models | The YHat Labs API | | ---------- | ----------------------------------------------------- | -------------------------------------------------------------- | | Model | ChakraTS-OS-10M, open weights | ChakraTS, our most accurate model | | Runs | on your machine | on our servers | | Use it for | research, evaluation, personal projects, competitions | production and commercial use | | Library | `pip install yhatmodels` | `pip install yhatlabs` ([Quickstart](/models/docs/quickstart)) | Both libraries use the same argument names, so code moves from one to the other with few changes. # Backtesting > Score the model on your own history against a seasonal baseline. Before you rely on a forecast, see how it would have done. `evaluate` cuts each series at a few points in its own past, forecasts from each cut, and scores the forecasts against what really happened, next to simple baselines. ```python res = model.evaluate(df, h=7, windows=3) res.summary ``` The summary has one row per model (ChakraTS-OS-10M and each baseline) and one column per metric: `mase`, `sql`, `wql`, `mae`, `rmse` and `coverage@0.8`, then `skill_` for each. A skill says how much better than the seasonal baseline a model is: 0.25 means 25% lower error, and anything above 0 beats it. ![A backtest of four past days and its calibration plot](https://raw.githubusercontent.com/yhatlabs/yhatmodels/main/docs/assets/backtest_light.png)![A backtest of four past days and its calibration plot](https://raw.githubusercontent.com/yhatlabs/yhatmodels/main/docs/assets/backtest_dark.png) Four past days of Gulf Coast demand, each forecast from the history before it. The third was a hot day the history gave no sign of, and the forecast misses it; across all four regions, the quantiles stay close to calibrated. ## Options [Section titled “Options”](#options) * **windows:** how many cuts per series (default 3), `step` apart (default `h`), at the end of each series. * **baselines:** `seasonal_naive` (repeats the last season: a week for daily data, a day for hourly) and `naive` (the last value). The first one is the reference for the skill columns. * **metrics:** `mase`, `sql`, `wql`, `mae`, `rmse` and `coverage@0.8` (the share of actual values inside the 10% to 90% range). All are computed by default. * **season:** the seasonal period in steps, if you want to fix it instead of inferring it from the frequency. * **past, known, preset, cross_series** and the column names work as in `forecast`. Known covariates are read from the data over the history; nothing after a cut reaches that window’s forecast. ## The result [Section titled “The result”](#the-result) ```python res.summary # per model: mean metrics and skill vs the baseline res.scores # per series and window res.forecasts # each window's quantiles next to the actual values res.calibration # share of actual values below each quantile and inside each interval res.plot() # each forecast against what happened (pip install "yhatmodels[plot]") res.plot_calibration() # share below each quantile against its level ``` ## Compare with your current forecast [Section titled “Compare with your current forecast”](#compare-with-your-current-forecast) Score the forecasts you use today on the same windows: ```python res = model.evaluate(df, h=7, compare={"current": mine}) ``` `mine` is a DataFrame with the id and time columns and either quantile columns (`median`, `q10`, …) or a point column named `forecast`. # ChakraTS-OS-10M > Our open forecasting model: size, context, horizon, speed and benchmark results. Our open forecasting model. For its size it is a frontier model: the most accurate open forecasting model under 100M parameters on fev-bench, and more accurate than most open models up to 100 times its size. It is pretrained on synthetic series and public real-world time-series data, so it forecasts your series zero-shot. [Hugging Face](https://huggingface.co/yhatlabs/ChakraTS-OS-10M) · [GitHub](https://github.com/yhatlabs/yhatmodels) · [PyPI](https://pypi.org/project/yhatmodels/) · [Research](/research/chakrats-os-10m) ## At a glance [Section titled “At a glance”](#at-a-glance) | | | | ---------- | --------------------------------------------------------------------------------------------------------- | | Task | time-series forecasting, zero-shot | | Parameters | 10.6M | | Weights | 42 MB (float32, safetensors) | | History | up to 32,768 past values per series | | Horizon | up to 768 steps in one pass; longer horizons continue in blocks | | Output | 21 quantile levels from 0.01 to 0.99; any quantile or interval | | Inputs | one or many series, several targets per series, past and known-future covariates (numeric or categorical) | | Speed | 1,000 series in 2 s on a laptop CPU (`fast`), 36 s (`pro`) ([details](/models/docs/open-models/speed)) | | Runs on | CPU, NVIDIA GPUs (bfloat16), Apple GPUs | | License | [Chakra Non-Commercial Model License](/models/docs/open-models/license) | ## Results [Section titled “Results”](#results) [fev-bench](https://huggingface.co/spaces/autogluon/fev-leaderboard) scores forecasting models on 100 tasks from many domains. Its skill score says how much more accurate a model is than a simple seasonal forecast; higher is better. | Model | Parameters | All 100 tasks | 42 tasks with covariates | | ------------------- | ---------- | ------------- | ------------------------ | | ci-proto | 167M | 51.5 | 53.0 | | TimeH2O-v1 | 109M | 50.8 | 51.4 | | Timestral-209M | 209M | 50.4 | 50.7 | | **ChakraTS-OS-10M** | **10.6M** | **49.9** | **50.1** | | t0-gamma | 256M | 49.4 | 49.3 | | TimesFM-3 | 331M | 49.0 | 49.0 | | Simons-297M | 297M | 48.4 | 47.3 | | Chronos-2 | 119M | 47.3 | 47.0 | | Timestral-5M | 5.2M | 46.2 | 44.5 | | TimeH2O-v1-tiny | 5.8M | 45.5 | 41.5 | | Toto-2.0-2.5B | 2.5B | 44.4 | 38.8 | fev-bench skill score (%), as of November 2026, computed the way the fev-bench leaderboard does from the result files in the [fev repository](https://github.com/autogluon/fev); sizes from the models’ Hugging Face pages. On [GIFT-Eval](https://huggingface.co/spaces/Salesforce/GIFT-Eval) and [TIME](https://huggingface.co/spaces/Real-TSF/TIME-leaderboard), relative to a seasonal forecast (lower is better): | Benchmark | MASE | CRPS | | --------- | ----- | ----- | | GIFT-Eval | 0.674 | 0.461 | | TIME | 0.642 | 0.537 | Every result reproduces from public code: the benchmark notebooks are in the [yhatlabs-cookbook](https://github.com/yhatlabs/yhatlabs-cookbook/tree/main/benchmarks) repository. ## Citation [Section titled “Citation”](#citation) ```bibtex @misc{yhatlabs2026chakratsos, title = {{ChakraTS-OS}: open-weight time-series forecasting models}, author = {{YHat Labs}}, year = {2026}, howpublished = {\url{https://huggingface.co/yhatlabs/ChakraTS-OS-10M}}, url = {https://huggingface.co/yhatlabs/ChakraTS-OS-10M} } ``` # Command line > Forecast, backtest and tune CSV or parquet files from a terminal. Everything in the Python library also works on a CSV or Parquet file, straight from a terminal or a scheduler. ```bash yhatmodels forecast sales.csv --h 7 --known price,promo --level 80,95 -o forecast.csv yhatmodels evaluate sales.csv --h 7 --windows 3 yhatmodels tune sales.csv --h 7 --steps 300 -o my-tuned/ yhatmodels forecast sales.csv --h 7 --model my-tuned/ yhatmodels models yhatmodels accept-license ChakraTS-OS-10M ``` Files are in long format, one row per series and timestamp, with the same column names as a [DataFrame](/models/docs/open-models/data#dataframes). ## Commands [Section titled “Commands”](#commands) | Command | What it does | | ---------------- | ----------------------------------------------------------------------------------------------------- | | `forecast` | forecasts the next `--h` steps of every series; writes CSV to the screen, or to `-o` (CSV or Parquet) | | `evaluate` | backtests against baselines and prints the summary; `-o` saves the per-series, per-window scores | | `tune` | fine-tunes the model and saves it to the folder in `-o`; use it with `--model FOLDER` | | `models` | lists the released models, their tasks and licenses | | `accept-license` | accepts a model’s license before its first download | ## Options [Section titled “Options”](#options) | Option | Meaning | | ------------------------------------------------------------- | ---------------------------------------------------------------------------- | | `--h` | the horizon, in steps | | `--level`, `--quantiles` | intervals (`80,95`) or quantile levels (`0.1,0.5,0.9`, or `all`) | | `--known`, `--past` | covariate columns, comma-separated | | `--future` | a file with the known columns’ values over the next `h` steps | | `--id-col`, `--time-col`, `--target-col` | column names; several target columns are forecast jointly | | `--freq` | a pandas frequency alias, inferred when left out | | `--model` | a released model’s name, a Hugging Face repo id or a local folder | | `--device` | `cuda`, `mps` or `cpu` (default: the best available) | | `--preset` | `pro` or `fast` | | `--cross-series` | read single-target series without covariates 16 at a time (or give a number) | | `--windows`, `--step`, `--baselines`, `--metrics`, `--season` | `evaluate` only, as in [Backtesting](/models/docs/open-models/backtesting) | | `--steps`, `--min-gain`, `--seed` | `tune` only, as in [Fine-tuning](/models/docs/open-models/fine-tuning) | # Covariates > Past and known-future inputs, numeric or categorical. Covariates are other columns that help the forecast. There are two kinds: * **Known:** values you know ahead of time, over the history and the next `h` steps. Planned prices, promotions, holidays, a weather forecast. * **Past:** values you only know up to now. Store visits, yesterday’s temperature, a related market. ![Two days of solar output forecast from history alone and with sunlight and cloud cover](https://raw.githubusercontent.com/yhatlabs/yhatmodels/main/docs/assets/covariates_light.png)![Two days of solar output forecast from history alone and with sunlight and cloud cover](https://raw.githubusercontent.com/yhatlabs/yhatmodels/main/docs/assets/covariates_dark.png) Two days of solar output. From history alone, the model expects another sunny day; with sunlight and cloud cover it sees the cloudy one coming. Data: [Renewable Energy and Weather Conditions](https://www.kaggle.com/datasets/samanemami/renewable-energy-and-weather-conditions) (CC0). ## In a DataFrame [Section titled “In a DataFrame”](#in-a-dataframe) Name the columns with `known` and `past`. Put the known columns’ future values in the rows after your last observation, with the target left empty: ```python # df: one row per hour with ds, y (solar output), sunlight and clouds; # the last 48 rows hold tomorrow's weather forecast, with y empty fc = model.forecast(df, h=48, known=["sunlight", "clouds"]) ``` Or keep the future values in a table of their own, with the id and time columns and the known columns, one row per future step: ```python fc = model.forecast(history, h=48, known=["sunlight", "clouds"], future=future) ``` Past covariates need no future values: ```python fc = model.forecast(df, h=7, past=["visits"], known=["day_type"], future=future) ``` ## With arrays [Section titled “With arrays”](#with-arrays) Pass one dict per series: past values cover the history (length `T`), known values cover the history and the horizon (length `T + h`). ```python fc = model.forecast(history, h=24, past={"visits": visits}, known={"price": price}) ``` For several series, pass a list with one dict per series. ## Categories [Section titled “Categories”](#categories) Text values are treated as categories, so a column like `day_type` with `"workday"` and `"weekend"` works as it is. No one-hot encoding needed. # Your data > Arrays and DataFrames: shapes, columns, missing values and frequency. `forecast` takes your history as arrays or as a pandas DataFrame. Arrays give arrays back; a DataFrame gives a DataFrame back. ## Arrays [Section titled “Arrays”](#arrays) ```python fc = model.forecast(history, h=24) ``` | You pass | You get | | ------------------------------------- | ------------------------------- | | one series, `(T,)` | `(h, Q)` | | N series of the same length, `(N, T)` | `(N, h, Q)` | | a list of series of different lengths | a list, one forecast per series | `Q` runs over the quantile levels in increasing order (by default 0.1, 0.5 and 0.9; see [Ranges](/models/docs/open-models/ranges)). NumPy arrays, torch tensors, pandas Series and plain lists of numbers all work. `NaN` marks a missing value. ## DataFrames [Section titled “DataFrames”](#dataframes) Most data lives in tables. Pass one row per series and timestamp (long format): ```python fc = model.forecast(df, h=7) ``` | unique_id | ds | y | | --------- | ---------- | --- | | store_1 | 2025-07-01 | 112 | | store_1 | 2025-07-02 | 98 | | store_2 | 2025-07-01 | 87 | The columns are found by name: * **Series id:** `unique_id`, `id`, `item_id` or `series_id`. Without one, the whole table is one series. * **Time:** `ds`, `timestamp`, `time`, `date` or `datetime`. * **Target:** `y`, `target` or `value`, else the one numeric column. Other names work too: `model.forecast(df, h=7, id_col="store", time_col="date", target_col="sales")`. The result has the id and time columns, then one column per quantile level: `q10`, `median`, `q90`. ## Frequency and missing values [Section titled “Frequency and missing values”](#frequency-and-missing-values) * The frequency of each series is inferred from its timestamps, or set with `freq=` (a pandas alias such as `"h"`, `"D"`, `"W-SUN"` or `"15min"`). * Missing timestamps are filled in as missing values, so gaps are fine. * Duplicate timestamps in one series are refused with an error that names the series. * A pandas Series with a `DatetimeIndex` is one dated series, and comes back as a DataFrame. ## How much history [Section titled “How much history”](#how-much-history) The model reads up to the last 32,768 values of each series; older values are dropped. More history helps it see long seasonal patterns, but a few weeks of hourly data or a year of daily data is often enough. # Fine-tuning > Tune the model on your series, save it and load it again. If your series follow patterns of their own, such as your promotions or paydays, `tune` adapts the model to your history. It takes seconds to a few minutes on a CPU, and the original model is left unchanged. ```python tuned = model.tune(df, h=7) tuned.report # how the tune did on your held-out history fc = tuned.forecast(df, h=7) ``` ## How it works [Section titled “How it works”](#how-it-works) 1. The last `h` steps of each series are held out. 2. Small adapters are trained on the rest of your history, with the pretrained weights frozen. 3. The tuned model is kept only if it forecasts the held-out steps better than the pretrained model, by 2% by default. Otherwise you get the pretrained model back, with a warning. 4. The tune is then retrained on the whole history and merged into a copy of the weights, so a tuned model forecasts as fast as the original. ## Options [Section titled “Options”](#options) * **h:** the horizon you will forecast; it is also the length of the held-out part. * **steps:** training steps (default 300). * **min_gain:** how much better the tune must be on the held-out steps to be kept (default 0.02). * **preset, cross_series:** the forecast settings the tune is checked with. Use the ones you will forecast with. * **past, known** and the column names work as in `forecast`. ## The report [Section titled “The report”](#the-report) `tuned.report` says whether the tune was kept (`used`), the held-out loss and WAPE of the pretrained and the tuned model, how many steps were kept, and how long it took. ## Save and load [Section titled “Save and load”](#save-and-load) ```python tuned.save("my-tuned/") model = ChakraTS.from_pretrained("my-tuned/") ``` The folder holds the weights, the config and the model’s license files. A tuned model stays under the license of the model it was tuned from, and `save` writes a notice saying it was modified. # Install and license > Install yhatmodels, accept the model license once, and run offline after the first download. ## Install [Section titled “Install”](#install) ```bash pip install yhatmodels ``` Python 3.10 or later. It installs PyTorch, NumPy, pandas, safetensors and the Hugging Face Hub client. For plots, install `pip install "yhatmodels[plot]"`, which adds matplotlib. The model runs on an NVIDIA GPU, an Apple GPU or the CPU, in that order of preference. Pick one with `ChakraTS.from_pretrained("ChakraTS-OS-10M", device="cpu")` (or `"cuda"`, `"mps"`). A laptop CPU is enough; see [Speed and devices](/models/docs/open-models/speed). ## Accept the license once [Section titled “Accept the license once”](#accept-the-license-once) The weights are free for non-commercial use under the [Chakra Non-Commercial Model License](/models/docs/open-models/license). The first download asks you to accept it once, with a free YHat Labs account: * **On your computer:** your browser opens. Sign in or create an account, accept, and the download starts. * **Over SSH:** the terminal shows a link. Open it on any device and paste back the token it shows. * **On a server or in CI:** set `YHAT_MODELS_TOKEN`, copied from [yhatlabs.com/models/license](https://yhatlabs.com/models/license), or run `yhatmodels accept-license ChakraTS-OS-10M` once in a terminal. The token is saved in `~/.cache/yhatmodels/token`, so you do this once per machine. An API key in `YHAT_API_KEY` works too. Set `YHATMODELS_NO_BROWSER=1` to never open a browser. ## Offline and private [Section titled “Offline and private”](#offline-and-private) After the first download the weights stay in the Hugging Face cache, and later runs need no network. The model runs entirely on your machine: the only call to YHat Labs is the license check before the first download, which sends your token and nothing else. ## Commercial use [Section titled “Commercial use”](#commercial-use) For production or commercial use, use ChakraTS through the [YHat Labs API](/models/docs/quickstart), or write to for a commercial license. # License > What the Chakra Non-Commercial Model License allows, and how to get a commercial license. The `yhatmodels` library is open source under [Apache-2.0](https://github.com/yhatlabs/yhatmodels/blob/main/LICENSE). The ChakraTS-OS-10M weights are under the [Chakra Non-Commercial Model License](/model-license). This page is a short summary; the license text is what applies. ## Free for [Section titled “Free for”](#free-for) * **Academic research** at a university or non-profit, when the results are published or made public. * **Personal use** that is not for money or business advantage. * **Evaluation** by an organization on its own data, to decide whether to adopt the model or a YHat Labs product: up to 90 days, not in production, and not to make business decisions. * **Data science competitions,** including ones with prizes. You may publish papers and benchmark results with the model, including comparisons with other models, without asking us. ## Not allowed without a commercial license [Section titled “Not allowed without a commercial license”](#not-allowed-without-a-commercial-license) * Use in production, or in a product, service or process that makes money. * Using the forecasts to make or support business decisions. * Client work, consulting or deliverables for others. * Offering the model or its forecasts as a hosted or API service. * Training another model on its weights or forecasts, except a fine-tune that stays under this license. ## Sharing and fine-tunes [Section titled “Sharing and fine-tunes”](#sharing-and-fine-tunes) * Fine-tuned models stay under the same license. `tuned.save()` writes the license and a notice saying the model was modified. * Share the unmodified model within your organization and with research collaborators, but don’t re-host it publicly; point people to the [official release](https://huggingface.co/yhatlabs/ChakraTS-OS-10M) instead. * Public demos and redistributions say “Built with ChakraTS-OS by YHat Labs” with a link to the license. Papers, posts and benchmark entries cite the model as given on its [model page](/models/docs/open-models/chakrats-os-10m#citation). ## Commercial use [Section titled “Commercial use”](#commercial-use) Use ChakraTS through the [YHat Labs API](/models/docs/quickstart), or write to for a commercial license, which can cover self-hosting and fine-tuning for production. # Limits > How much history the model reads, how far ahead it forecasts well, and when to use ChakraTS. ## What the model reads and returns [Section titled “What the model reads and returns”](#what-the-model-reads-and-returns) * **History:** at most the last 32,768 values of each series; older values are dropped. * **Horizon:** up to 768 steps in one pass. Longer horizons are forecast in blocks, each continuing from the median of the one before, and lose accuracy the further out they go. * **Output:** quantiles and intervals. There are no sample paths, so totals and peaks over the horizon cannot be simulated. * **Inputs:** past and known-future covariates, but no static covariates (per-series attributes such as a store’s size). ## When to use ChakraTS instead [Section titled “When to use ChakraTS instead”](#when-to-use-chakrats-instead) A 10M model has less room than a large one. For the best accuracy, especially on long horizons and minute-level data, use ChakraTS, our most accurate model, through the [YHat Labs API](/models/docs/quickstart). It also adds sample paths, static covariates, calendar features and hosted fine-tuning, and it is licensed for commercial use. # Multivariate series > Several targets of one series, forecast together. When one series has several targets that move together, such as electricity load and price, the model can forecast them jointly, so each target’s forecast reads the others. ## In a DataFrame [Section titled “In a DataFrame”](#in-a-dataframe) Name the targets with `target_col`: ```python fc = model.forecast(grid, h=24, target_col=["load", "price"]) ``` The result gets a `target` column saying which target each row is for: `ds`, `target`, `q10`, `median`, `q90`. ## With arrays [Section titled “With arrays”](#with-arrays) Give each series as a `(V, T)` array of its V targets, inside a list, or stack several such series into `(N, V, T)`: ```python fc = model.forecast([y], h=24)[0] # y: (V, T) -> (V, h, Q) fc = model.forecast(Y, h=24) # Y: (N, V, T) -> (N, V, h, Q) ``` Caution A bare `(V, T)` array, not in a list, is read as V separate series of one target each. Wrap it in a list to forecast the targets jointly. ## Related series [Section titled “Related series”](#related-series) Separate series that are not targets of one series, such as the stores of one chain, can still help each other. With `cross_series=True`, single-target series without covariates are read 16 at a time, so the model sees their neighbours: ```python fc = model.forecast(df, h=7, cross_series=True) # or a group size, e.g. cross_series=32 ``` # Quickstart > A first forecast from NumPy, pandas or the command line. Install the library, then make your first forecast. The first run downloads the model (42 MB) after the one-time [license step](/models/docs/open-models/install#accept-the-license-once). ```bash pip install yhatmodels ``` * NumPy ```python import numpy as np from yhatmodels import ChakraTS model = ChakraTS.from_pretrained("ChakraTS-OS-10M") history = 10 + np.sin(np.arange(500) / 24 * 2 * np.pi) # or your own series fc = model.forecast(history, h=48) ``` `fc` has shape `(48, 3)`: the 10%, 50% and 90% quantiles for each of the next 48 steps. * pandas ```python import numpy as np import pandas as pd from yhatmodels import ChakraTS model = ChakraTS.from_pretrained("ChakraTS-OS-10M") days = pd.date_range("2025-01-01", periods=200, freq="D") df = pd.concat( pd.DataFrame({"unique_id": store, "ds": days, "y": 100 + 10 * np.sin(np.arange(200) / 7 * 2 * np.pi)}) for store in ["store_1", "store_2"] ) fc = model.forecast(df, h=7, level=[80, 95]) ``` `fc` has one row per store and future day, with the columns `unique_id`, `ds`, `q2.5`, `q10`, `median`, `q90` and `q97.5`: the median and the 80% and 95% intervals. * Command line ```bash yhatmodels forecast sales.csv --h 7 --level 80,95 -o forecast.csv ``` `sales.csv` has one row per series and date, with the columns `unique_id`, `ds` and `y`. `forecast.csv` gets one row per series and future date, with the median and the intervals. ## Next [Section titled “Next”](#next) [Your data](/models/docs/open-models/data)Arrays and DataFrames: shapes, columns, missing values and frequency. [Covariates](/models/docs/open-models/covariates)Use what you know about the future: prices, promotions, weather. [Backtesting](/models/docs/open-models/backtesting)See how the model would have done on your own history. [ChakraTS-OS-10M](/models/docs/open-models/chakrats-os-10m)Size, context, horizon, speed and benchmark results. # Ranges > Quantiles and intervals at any level. Every forecast comes with a range of likely values, so you can plan for a bad week as well as a typical one. An 80% interval should contain the actual value about 80% of the time; [backtesting](/models/docs/open-models/backtesting) checks that on your own data. ## Intervals [Section titled “Intervals”](#intervals) Ask for central intervals by width, in percent. The median comes with them: ```python fc = model.forecast(df, h=7, level=[80, 95]) # columns: unique_id, ds, q2.5, q10, median, q90, q97.5 ``` ## Quantiles [Section titled “Quantiles”](#quantiles) Or ask for quantile levels directly, any values between 0 and 1: ```python fc = model.forecast(history, h=24, quantiles=[0.05, 0.5, 0.95]) # (24, 3) fc = model.forecast(history, h=24, quantiles="all") # (24, 21): every level the model produces ``` The default is 0.1, 0.5 and 0.9. The model produces 21 levels from 0.01 to 0.99; other levels are interpolated between them. Pass `quantiles` or `level`, not both. ## Reading the result [Section titled “Reading the result”](#reading-the-result) * **Arrays:** the last axis runs over the levels in increasing order. * **DataFrames:** one column per level, named `q` and the level in percent (`q10`, `q97.5`), with `median` for 0.5. # Python reference > ChakraTS.from_pretrained, forecast, evaluate and tune, and the errors they raise. ```python from yhatmodels import ChakraTS, list_models, accept_license, plot_forecast ``` ## ChakraTS.from_pretrained [Section titled “ChakraTS.from_pretrained”](#chakratsfrom_pretrained) ```python ChakraTS.from_pretrained(model="ChakraTS-OS-10M", device=None, revision=None, token=None) ``` | Argument | Meaning | | ---------- | --------------------------------------------------------------------------------------------------------------------------- | | `model` | a released model’s name (see `list_models()`), a Hugging Face repo id, or a local folder with `config.json` and the weights | | `device` | `"cuda"`, `"mps"` or `"cpu"`; by default an NVIDIA GPU, then an Apple GPU, then the CPU | | `revision` | a Hugging Face revision of the weights | | `token` | a Hugging Face token, for a private repository | `model.info` describes the loaded model: name, license, parameters, longest history, patch sizes, quantile levels and presets. ## forecast [Section titled “forecast”](#forecast) ```python model.forecast(data, h, *, quantiles=None, level=None, preset=None, cross_series=False, past=None, known=None, future=None, id_col=None, time_col=None, target_col=None, freq=None) ``` | Argument | Meaning | | ---------------------------------- | ----------------------------------------------------------------------------------------------- | | `data` | arrays or a long DataFrame ([Your data](/models/docs/open-models/data)) | | `h` | how many steps ahead | | `quantiles` | levels in (0, 1), default 0.1, 0.5, 0.9; or `"all"` ([Ranges](/models/docs/open-models/ranges)) | | `level` | central intervals in percent, e.g. `[80, 95]`, instead of `quantiles` | | `preset` | `"pro"` (default) or `"fast"` ([Speed and devices](/models/docs/open-models/speed)) | | `cross_series` | `True` or a group size: read related single-target series together | | `past`, `known` | covariates ([Covariates](/models/docs/open-models/covariates)) | | `future` | a DataFrame of the known columns’ values over the next `h` steps | | `id_col`, `time_col`, `target_col` | DataFrame column names; a list of targets forecasts them jointly | | `freq` | a pandas frequency alias; inferred when left out | Returns arrays for array input and a DataFrame for DataFrame input. Arguments that only the hosted ChakraTS has (`static`, `calendar`, `samples`, `tune` and others) raise a `TypeError` that points to the API. ## evaluate [Section titled “evaluate”](#evaluate) ```python model.evaluate(data, h, *, windows=3, step=None, baselines=("seasonal_naive",), metrics=("mase", "sql", "wql", "mae", "rmse", "coverage@0.8"), compare=None, season=None, preset=None, cross_series=False, past=None, known=None, id_col=None, time_col=None, target_col=None, freq=None) ``` Returns an `EvaluationResult` with `.summary`, `.scores`, `.forecasts`, `.calibration`, `.plot()` and `.plot_calibration()`. See [Backtesting](/models/docs/open-models/backtesting). ## tune [Section titled “tune”](#tune) ```python model.tune(data, h, *, steps=300, preset=None, cross_series=False, past=None, known=None, id_col=None, time_col=None, target_col=None, freq=None, season=None, seed=0, min_gain=0.02, pick_steps=True, verbose=False) ``` Returns a new `ChakraTS` with `.report`; the original model is unchanged. `tuned.save(folder)` writes a folder that `from_pretrained` loads. See [Fine-tuning](/models/docs/open-models/fine-tuning). ## Other functions [Section titled “Other functions”](#other-functions) | Function | What it does | | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `list_models(task=None)` | the released models, their tasks and licenses | | `accept_license(model)` | accepts a model’s license before its first download | | `plot_forecast(history, fc)` | plots a forecast with its intervals (`pip install "yhatmodels[plot]"`); also takes a forecast DataFrame with `history=df` | ## Errors [Section titled “Errors”](#errors) | Error | When | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `LicenseNotAcceptedError` | the model’s license has not been accepted yet ([Install and license](/models/docs/open-models/install#accept-the-license-once)) | | `ModelLoadError` | a model folder or repository is missing a file, or names an architecture the library does not have | | `ValueError` | bad input, such as `h=0`, levels outside (0, 1), duplicate timestamps or a missing column; the message says what to fix | Both library errors derive from `YHatModelsError`. ## Environment variables [Section titled “Environment variables”](#environment-variables) | Variable | Use | | ------------------------- | ---------------------------------------------------------------------------- | | `YHAT_MODELS_TOKEN` | the model download token, for servers and CI | | `YHAT_API_KEY` | an API key works as a token too | | `YHATMODELS_NO_BROWSER=1` | never open a browser for the license step | | `YHATMODELS_CACHE` | where the token and license records are kept (default `~/.cache/yhatmodels`) | # Speed and devices > Pro and fast settings, CPU and NVIDIA or Apple GPUs, measured speeds. ChakraTS-OS-10M is small enough for a laptop CPU. A GPU helps with large batches and long histories. ## Pro and fast [Section titled “Pro and fast”](#pro-and-fast) | Preset | What it does | When to use it | | --------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------- | | `pro` (default) | reads each series at every patch size the model knows and averages the forecasts | the most accurate setting; our benchmark results use it | | `fast` | reads each series at the model’s own patch size only | many series or long histories, when speed matters more | ```python fc = model.forecast(df, h=48, preset="fast") ``` `pro` averages only for horizons up to 400 steps; longer horizons use the model’s own patch size either way. ## Measured speed [Section titled “Measured speed”](#measured-speed) 48 steps ahead, each the median of several runs after a warm-up, on an Apple M5 Pro laptop: | Job | CPU, pro | CPU, fast | Apple GPU, pro | Apple GPU, fast | | ----------------------------- | -------- | --------- | -------------- | --------------- | | 1 series, 512 past points | 80 ms | 12 ms | | | | 1 series, 2,048 past points | 0.25 s | 25 ms | | | | 1 series, 8,192 past points | 0.46 s | 94 ms | | | | 100 series, 512 past points | 3.1 s | 0.23 s | | | | 1,000 series, 512 past points | 36 s | 2.0 s | 13.5 s | 0.9 s | An older or smaller CPU will be slower. ## Devices [Section titled “Devices”](#devices) The model picks an NVIDIA GPU, then an Apple GPU, then the CPU. Choose one yourself with `device`: ```python model = ChakraTS.from_pretrained("ChakraTS-OS-10M", device="cpu") # or "cuda", "mps" ``` * **NVIDIA GPUs** run in bfloat16, as the model was trained. * **Large batches** are split into passes sized for the device, and a pass that runs out of GPU memory is retried in halves. * The weights are a 42 MB file, so loading takes well under a second once downloaded. # Quickstart > Install the library, set your API key, and make your first forecast and your first tabular prediction. This page takes you from nothing to a forecast and a tabular prediction. Each step says what it does and shows what you should see. 1. **Install the library.** This installs the `yhatlabs` Python package and the `yhatlabs` command (Python 3.9 or later). ```sh pip install yhatlabs ``` 2. **Set your API key.** Every call needs one; [create an account](https://yhatlabs.com/models/signup) and make one on the API keys page if you don’t have one yet. Setting it in your environment lets the library, the command line and agents all find it. ```sh export YHAT_API_KEY="" ``` To check it works, see [API keys](/models/docs/api-keys#check-your-key). 3. **Make a forecast.** This loads 12 years of monthly airline passengers and forecasts the next 24 months. `level=[80]` asks for an 80% interval around each month: the range the actual value should fall in 8 times out of 10. * Python ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" df = pd.read_csv(url + "airline-passengers.csv") # columns: Month, Passengers yh = Client() fc = yh.forecast(df, h=24, time_col="Month", target_col="Passengers", level=[80]) print(fc.df.head(3).round(1)) ``` Output | unique_id | Month | q10 | median | q90 | | --------- | ---------- | ----- | ------ | ----- | | series_0 | 1961-01-01 | 430.5 | 448.5 | 468.0 | | series_0 | 1961-02-01 | 408.9 | 430.9 | 452.0 | | series_0 | 1961-03-01 | 449.0 | 486.7 | 508.2 | * CLI ```sh curl -sO https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv yhatlabs forecast airline-passengers.csv --h 24 \ --time-col Month --target-col Passengers --level 80 -o forecast.csv head -4 forecast.csv ``` Output ```text unique_id,Month,q10,median,q90 series_0,1961-01-01,430.53720868618353,448.541455316843,467.97666760754703 series_0,1961-02-01,408.9291654372314,430.8968252966604,451.962356383921 series_0,1961-03-01,449.0440194902994,486.74538766574983,508.24449670833036 ``` * cURL ```sh curl -s https://api.yhatlabs.com/v1/series/forecast \ -H "Authorization: Bearer $YHAT_API_KEY" \ -H "Content-Type: application/json" \ -d '{"freq": "MS", "horizon": 2, "series": [{"id": "passengers", "values": [417, 391, 419, 461, 472, 535, 622, 606, 508, 461, 390, 432]}]}' ``` Output ```text {"id":"3a90dd3d-e737-465e-b1f9-ca3c8941d464","model":"chakra-ts","horizon":2,"quantile_levels":[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9],"forecasts":[{"id":"passengers","quantiles":[[383.0753173828125,402.9498291015625,413.9801025390625,422.4678039550781,434.37628173828125,446.0346374511719,460.8013610839844,478.62322998046875,502.9939880371094],[364.9206237792969,390.9168395996094,410.5889892578125,423.1913757324219,436.617431640625,454.6253662109375,474.06512451171875,497.9351806640625,532.4006958007812]]}],"usage":{"series":1}} ``` Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast) Each row is one future month: `median` is the most likely value, and `q10` to `q90` is the 80% interval. The cURL tab shows the same call made directly against the API, which takes the values as a plain list. 4. **Make a tabular prediction.** This learns a diagnosis (`0` or `1`) from 426 labeled rows of a public medical dataset, then predicts it for 143 rows it has not seen. * Python ```python from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from yhatlabs import Client X, y = load_breast_cancer(return_X_y=True, as_frame=True) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) yh = Client() model = yh.fit(X_train.assign(diagnosis=y_train), target="diagnosis") res = model.predict(X_test) print(res.df.head(3).round(3)) print("accuracy:", round((res.predictions == y_test).mean(), 3)) model.delete() ``` Output | | prediction | p_0 | p_1 | | --- | ---------- | ----- | ----- | | 512 | 0 | 1.000 | 0.000 | | 457 | 1 | 0.013 | 0.987 | | 439 | 1 | 0.000 | 1.000 | ``` accuracy: 0.979 ``` * cURL ```sh curl -s https://api.yhatlabs.com/v1/table/predict \ -H "Authorization: Bearer $YHAT_API_KEY" \ -H "Content-Type: application/json" \ -d '{"target": "bought", "train": [{"visits": 1, "plan": "free", "bought": 0}, {"visits": 9, "plan": "pro", "bought": 1}, {"visits": 2, "plan": "free", "bought": 0}, {"visits": 7, "plan": "pro", "bought": 1}, {"visits": 3, "plan": "free", "bought": 0}, {"visits": 8, "plan": "pro", "bought": 1}, {"visits": 1, "plan": "pro", "bought": 0}, {"visits": 6, "plan": "free", "bought": 1}, {"visits": 2, "plan": "pro", "bought": 0}, {"visits": 9, "plan": "free", "bought": 1}], "test": [{"visits": 8, "plan": "pro"}, {"visits": 1, "plan": "free"}]}' \ | python3 -c "import sys, json; r = json.load(sys.stdin); print(r['predictions'], r['classes'], r['probabilities'])" ``` Output ```text [1, 0] [0, 1] [[0.000736, 0.999264], [0.999706, 0.000294]] ``` Parameters: [`Client.predict`](/models/docs/reference/python#client-predict) `prediction` is the predicted class, and `p_0`, `p_1` are the probabilities of each class. `yh.fit` stores the fitted model on our side so you can predict from it repeatedly; `model.delete()` removes it. ## Next [Section titled “Next”](#next) * [Forecasting](/models/docs/time-series/forecasting): uncertainty, many series at once, reading the results. * [Predicting on tables](/models/docs/tabular/predicting): fitting once, the options, reading the results. * [Data checks](/models/docs/tools/data-checks): find problems in your data before sending it. # Python reference > Every public class and function of the yhatlabs package, with signatures, generated from the code. 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) ```python 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 . | | `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”](#client-1) 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) ```python 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) -> ForecastResult ``` Forecast 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` [Section titled “tune”](#tune) ```python 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) ```python 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) -> EvaluationResult ``` Rolling-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@\. | | `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) ```python 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.DataFrame ``` What-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) ```python 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.DataFrame ``` How 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) ```python 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.DataFrame ``` Scores 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) ```python 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.AnomalyStream ``` Anomaly 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) ```python 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.DataFrame ``` Fills 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) ```python 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` [Section titled “fit”](#fit) ```python 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) ```python 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) -> Comparison ``` Train 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) ```python 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) -> TableEvaluation ``` Cross-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) ```python 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) ```python impute(df: pd.DataFrame, columns: Cols = None, *, model: str = chakra-tab, preset: Optional[str] = None, mask_columns: Optional[bool] = None) -> pd.DataFrame ``` Fills 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) ```python get_fit(fit_id: str) -> FittedModel ``` Reattach 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` [Section titled “fits”](#fits) ```python 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) ```python get_tune(tune_id: str) -> Tuned ``` Reattach to a tune by id. | Parameter | Type | Required / default | Description | | --------- | ---- | ------------------ | ----------- | | `tune_id` | str | **required** | | []() ### `tunes` [Section titled “tunes”](#tunes) ```python tunes() -> List[Dict[str, Any]] ``` This project’s live tunes, newest first. []() ### `whoami` [Section titled “whoami”](#whoami) ```python 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) ```python models() -> List[Dict[str, Any]] ``` Models this key can use: \[{id, kind, description}]. []() ### `usage` [Section titled “usage”](#usage) ```python 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) ```python 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) ```python with_options(*, timeout: Optional[float] = None, max_retries: Optional[int] = None, max_concurrency: Optional[int] = None, mask_columns: Optional[bool] = None) -> Any ``` A 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”](#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) ```python intervals(levels: Union[float, Sequence[float]] = 80) -> pd.DataFrame ``` Central 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` [Section titled “prob”](#prob) ```python prob(*, above: Any = None, below: Any = None) -> pd.DataFrame ``` Probability 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) ```python to_wide(value: str = median) -> pd.DataFrame ``` One 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) ```python to_long() -> pd.DataFrame ``` Hubverse-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) ```python sample_paths(uid: Any = None) -> Any ``` Sample 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` [Section titled “plot”](#plot) ```python plot(history: Optional[pd.DataFrame] = None, ids: Optional[List[Any]] = None, max_series: int = 4, ax: Any = None) -> Any ``` Median 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) ```python to_polars() -> Any ``` ## EvaluationResult [Section titled “EvaluationResult”](#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”](#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` [Section titled “plot”](#plot-1) ```python plot(ids: Optional[List[Any]] = None, max_series: int = 4, model: Optional[str] = None, ax: Any = None) -> Any ``` Actuals 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) ```python plot_calibration(ax: Any = None) -> Any ``` Reliability 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”](#predictionresult) Tabular predictions aligned to the rows that were scored (`index` matches the input test rows). []() ### `df` [Section titled “df”](#df) Everything per row in one table: prediction, p\_\ or quantile columns, mean, prediction_set, indexed like test. []() ### `prob` [Section titled “prob”](#prob-1) ```python prob(*, above: Any = None, below: Any = None) -> pd.Series ``` Regression: 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”](#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”](#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-1) ```python to_polars() -> Any ``` ## Tuned [Section titled “Tuned”](#tuned) Tuned(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]’ = \, \_client: ‘Any’ = None) []() ### `forecast` [Section titled “forecast”](#forecast-1) ```python forecast(data: Any, h: Optional[int] = None, **kw: Any) -> Any ``` Forecast 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) ```python delete() -> None ``` Deletes the tune on our side. []() ### `info` [Section titled “info”](#info) ```python info() -> Dict[str, Any] ``` The tune as the API shows it now (expiry, last use, report). []() ### `bind` [Section titled “bind”](#bind) ```python bind(client: Any) -> Tuned ``` | Parameter | Type | Required / default | Description | | --------- | ---- | ------------------ | ----------- | | `client` | Any | **required** | | ## FittedModel [Section titled “FittedModel”](#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]’ = \, \_client: ‘Any’ = None, profile: ‘Optional\[Dict\[str, Any]]’ = None, mask: ‘Optional\[Dict\[str, str]]’ = None, usage: ‘Dict\[str, Any]’ = \, deleted: ‘bool’ = False) []() ### `predict` [Section titled “predict”](#predict-1) ```python predict(test: Any, *, quantiles: Any = None, set_coverage: Optional[float] = None) -> PredictionResult ``` Score 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) ```python predict_proba(test: Any) -> pd.DataFrame ``` Classification: 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) ```python importance(data: Any = None, *, subsample_size: int = 1000, num_shuffle_sets: int = 3, time_limit: Optional[float] = None) -> pd.DataFrame ``` Permutation 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) ```python effect(col: str, *, grid: Any = 20, data: Any = None, rows: int = 200, seed: int = 0) -> pd.DataFrame ``` How 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` [Section titled “save”](#save) ```python 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-1) ```python delete() -> None ``` Delete the fit on our side (its stored training request and the fitted model). Expired fits are deleted anyway; a second delete() does nothing. []() ### `info` [Section titled “info”](#info-1) ```python info() -> Dict[str, Any] ``` The fit as the API holds it: model, target, summary, classes, expiry. []() ### `bind` [Section titled “bind”](#bind-1) ```python bind(client: Any) -> FittedModel ``` | Parameter | Type | Required / default | Description | | --------- | ---- | ------------------ | ----------- | | `client` | Any | **required** | | ## FitGroup [Section titled “FitGroup”](#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-2) ```python predict(test: Any, *, quantiles: Any = None) -> GroupPrediction ``` Every 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-1) ```python importance(data: Any = None, **kw: Any) -> pd.DataFrame ``` Permutation 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-1) ```python effect(col: str, **kw: Any) -> pd.DataFrame ``` FittedModel.effect for every target, stacked with a `target` column. | Parameter | Type | Required / default | Description | | ---------- | ---- | ------------------ | ----------- | | `col` | str | **required** | | | `**kwargs` | Any | optional | | []() ### `save` [Section titled “save”](#save-1) ```python 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-2) ```python delete() -> None ``` ## TableEvaluation [Section titled “TableEvaluation”](#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` [Section titled “plot”](#plot-2) ```python plot(ax: Any = None) -> Any ``` Classification: reliability diagram. Regression: predicted against actual, with the widest interval. Needs matplotlib. | Parameter | Type | Required / default | Description | | --------- | ---- | ------------------ | ----------- | | `ax` | Any | optional | | ## Comparison [Section titled “Comparison”](#comparison) Each standard model’s predictions for the test rows (index = the test rows), and the naive baseline’s. []() ### `score` [Section titled “score”](#score) ```python score(actual: Any, **others: Any) -> pd.DataFrame ``` Scores 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 | | ## Job [Section titled “Job”](#job) 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) ```python status() -> str ``` queued, running, succeeded, failed or canceled. []() ### `wait` [Section titled “wait”](#wait) ```python wait(timeout: Optional[float] = 7200.0) -> Any ``` Blocks 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) ```python result(timeout: Optional[float] = 7200.0) -> Any ``` The same as wait(). | Parameter | Type | Required / default | Description | | --------- | ---------------- | ------------------ | ----------- | | `timeout` | Optional\[float] | `7200.0` | | []() ### `cancel` [Section titled “cancel”](#cancel) ```python cancel() -> bool ``` Stops the job if it hasn’t finished; True when it was canceled. ## AnomalyStream [Section titled “AnomalyStream”](#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) ```python update(new: Any) -> pd.DataFrame ``` Scores 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”](#yhatlabs) []() ### `check` [Section titled “check”](#check) ```python 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) -> DataCheck ``` Checks 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) ```python outliers(train: Any, data: Any = None, *, threshold: float = 0.99) -> pd.DataFrame ``` Scores 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` [Section titled “load”](#load) ```python load(source: Union[str, Path, Dict[str, Any]], client: Any = None) -> FittedModel ``` A 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”](#yhatlabshierarchy) []() ### `aggregate` [Section titled “aggregate”](#aggregate) ```python 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) ```python reconcile(fc: Any, tree: Dict[str, List[str]]) -> Any ``` The 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”](#yhatlabsplots) []() ### `forecast` [Section titled “forecast”](#forecast-2) ```python forecast(fc: Any, history: Optional[pd.DataFrame] = None, ids: Optional[List[Any]] = None, max_series: int = 4, ax: Any = None) -> Any ``` Median 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) ```python backtest(ev: Any, ids: Optional[List[Any]] = None, max_series: int = 4, model: Optional[str] = None, ax: Any = None) -> Any ``` Actuals 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) ```python anomalies(flags: pd.DataFrame, ids: Optional[List[Any]] = None, max_series: int = 4, ax: Any = None) -> Any ``` The 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-1) ```python scenarios(frame: pd.DataFrame, history: Optional[pd.DataFrame] = None, ids: Optional[List[Any]] = None, max_series: int = 4, ax: Any = None) -> Any ``` One 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-1) ```python calibration(ev: Any, ax: Any = None) -> Any ``` Forecast 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) ```python reliability(ev: Any, ax: Any = None) -> Any ``` Classification 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) ```python predicted_vs_actual(res: Any, actual: Any, ax: Any = None) -> Any ``` Regression: 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-2) ```python importance(imp: pd.DataFrame, top: int = 20, ax: Any = None) -> Any ``` Permutation 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-2) ```python effect(eff: pd.DataFrame, ax: Any = None) -> Any ``` An 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 | | # Changelog > Releases of the Python library and changes to the API. ## Python library [Section titled “Python library”](#python-library) The full history is in [CHANGELOG.md](https://github.com/yhatlabs/yhatlabs-python/blob/main/CHANGELOG.md). * **0.2.2**: * `yh.tune(...)`: fine-tune ChakraTS on your series ([Tuning on your data](/models/docs/time-series/tuning)); `forecast(..., tune=)`, `yh.tunes()`, `yh.get_tune()`, and `yhatlabs tune` / `forecast --tune` in the CLI; * `forecast(preset="pro")`: slower, slightly sharper; * `yhatlabs --version`; `check()` finds a date column by its values and names `time_col=` when there is none; `check --target-col` in the CLI; * `estimate_table()` prices a regression’s ranges (it guesses regression from the target, and takes `quantiles=`); * a horizon above 2,048 steps says to forecast at a coarser frequency. * **0.2.1** (2026-10-28): * tables too large for a direct call run as background jobs, and the call waits for them; `background=True` returns a `Job` (`status()`, `wait()`, `result()`, `cancel()`); * `compare=True` on `predict` and `yh.compare(...)`: XGBoost, a random forest and a linear model (LightGBM on request) and a naive baseline on the same rows, scored with `comparison.score(actual, ChakraTab=res)`; * `preset="pro"` (the same as `"full"`); `task=` also takes `"regression"` and `"classification"`; * `store=False` on `forecast`, `predict`, `fit` and `compare`: the call isn’t shown in your Logs; * credits as decimals (`usage["credits"] == 0.02`); `estimate_table()` asks the API and returns `tokens` too; forecasts split over several requests add up their credits in `fc.usage`; * fits kept 30 days after their last use by default (`ttl_days=`, 1 to 365); `model.save()` stores a sample of up to 2,000 training rows, `save(path, sample=False)` leaves it out; `model.usage` holds what the fit cost; * `yh.explain_forecast(...)`: how much each covariate moves the forecast; * `yh.anomaly_stream(...)`: anomaly scores for points as they arrive; * `yhatlabs.outliers(train, data)`: rows unlike the training rows, locally, with no key; * Spark, Dask, Ray and polars (lazy too) tables as input; * one table can carry the future of known covariates (rows after the last value, target blank); * `evaluate()`: the seasonal-naive baseline repeats the last week on daily data and the last year on weekly data; * CLI: `--json` before or after the command, `--preset pro`, `predict --compare`, `--no-store`; * clearer errors for levels, presets and `freq=`; `JobFailedError.job_id`; ROC AUC in comparisons. * **0.2.0** (2026-10-15): * a model that is starting up is waited for, up to 5 minutes, instead of failing after the usual retries; * forecasts: `mean=True`, `fc.intervals(80)`, `fc.to_wide()`, `fc.prob(above=...)`; * tables: `evaluate_table` (shuffled, grouped or time-ordered folds, with calibration), `out_of_range` and `novelty` on every prediction, `res.prob(above=...)`, `model.effect(col)`, several targets in one `fit`; * `yhatlabs.plots` for every result; * input checks before sending: irregular timestamps, missing ids, empty tables, too many columns, unusable targets; integer time steps; 2-D arrays as one series per row; * forecasts: `level=[95, 99]` and any quantile level, `samples=` with `fc.sample_paths()`, `history=True`; `yhatlabs.hierarchy` to aggregate and reconcile series that add up; * tables: `groups=` and `time_col=` on `fit`, `predict` and `evaluate_table`; `set_coverage=` for prediction sets; `estimate_table` for the credits of a call; large tables uploaded once automatically; * an `Idempotency-Key` on every POST, gzip for large bodies, and API capability flags; * `mask_columns=True` sends column names as `c0`, `c1`, … and keeps your names in every result; * the new API paths (`/v1/series/...`, `/v1/table/...`); 0.1.1 calls the old ones. * **0.1.1** (2026-10-15): requests work without the optional `orjson` package; CI tests the install without extras. * **0.1.0** (2026-10-15, yanked): first release. Forecasting, backtesting, scenarios, anomalies and gaps; fits, intervals, importance and imputation; data checks; the CLI and the agent skill. ## API [Section titled “API”](#api) * **2026-11-13**: a table request body over 4 MB reads like any other: the model, `async` and `store` in the body count, uploaded tables in it work, and a body that isn’t valid JSON is refused with a `400` before it runs. * **2026-11-12**: * table pricing: feature columns past the first 100 count 5% each (`GET /v1/limits` `tokens.tabular.columns`); * a table request body over 4 MB is stored and queued as it arrives: it can’t time out while a GPU starts, its request is kept with its log entry, and its model, `async` and `store` can be given on the URL (`?model=`, `?async=true`, `?store=false`, or an `X-Store: false` header); a large body asking for another model than its URL answers `400`; * a feature column named `Index` no longer fails the fit; * `/v1/tabular/predict`, the path before the rename, works again as an alias of `/v1/table/predict`. * **2026-10-28**: * direct table calls are sized per preset: `fast` up to 100,000 training rows x 100 columns, `medium` and `pro` up to 25,000 x 100 (`GET /v1/limits` `tabular.direct`). Past that, a direct call answers `413` with error type `async_required` (send it with `"async": true`); past the hard caps (200,000 rows, 2,000 columns, 50,000,000 cells as a job), `request_too_large`; * a direct table call still running after about 20 minutes comes back as a job (`{"object": "job", ...}`) to poll; `DELETE /v1/jobs/{id}` cancels a running job as well as a queued one; * `POST /v1/table/compare`: standard models and a naive baseline on the same rows; * the presets are `fast`, `medium` and `pro` (`full` is still accepted); * forecasts are counted in credits for keys of an organization. * **2026-10-26**: credits are counted to three decimals, at 1 credit per 1M tokens by default (was 1,000 credits per 1M tokens); every credit amount the API returns or accepts (`usage.credits`, balances, caps, estimates) uses the new unit. * **2026-10-15 (paths)**: paths name the input, then the task: `POST /v1/series/forecast`, `POST /v1/table/predict` and `/v1/table/fits/...`. The old paths (`/v1/forecast`, `/v1/tabular/predict`, `/v1/fits`) answer 404 naming the new ones. * **2026-10-15 (later)**: per-row predictive distributions for regression (intervals that vary by row, `mean`, calibrated out-of-sample, wider where a row extrapolates); `groups` and `time_col` validation folds; prediction sets (`set_coverage`); forecast `quantile_levels` beyond 0.1-0.9, `samples`, `seed` and `history`; forecast intervals calibrated on each series’ past windows; tabular calls counted in credits (rates in `GET /v1/limits` `pricing`); per-key rate and concurrency limits (`429 rate_limited` with `Retry-After`); gzip request bodies; table uploads (`/v1/uploads`); `GET /v1/openapi.json`. * **2026-10-15**: horizons up to 2,048 with or without covariates; clear 422 errors with the reason for unusable input (and 502 only for failures on our side); `request_id` in every error; `freq` must be a pandas alias; class labels in their own type (`1`, `true`); intervals on small regression tables; float64 handling of extreme values; `Idempotency-Key` on fits and tabular predict; `capabilities` in `GET /v1/limits`. * **2026-10-14**: stored fits (`/v1/fits`), regression intervals, column importance, `GET /v1/limits`. # Data handling > What happens to the data you send, and how long it is kept. Your inputs are sent to the YHat Labs API over HTTPS to be processed. * **We never use your data to train or improve our models.** * **Calls** are kept with what they sent and got back, so you can open, download or delete them in the account app’s Logs. Send `"store": false` in a call (or `?store=false`; `store=False` in Python, `--no-store` in the CLI) and the call isn’t shown in your Logs. We also keep a copy of every call, whatever `store` says, to look into errors, and use it for nothing else. * **Fits** keep your training table and the trained model while the fit lives: 30 days after its last use by default (`ttl_days`, 1 to 365), or until you delete it. Deleting removes them from your project. * **Saved model files** (`model.save()` in Python) are written on your machine. They include a sample of up to 2,000 training rows, for the out-of-range and novelty checks; `model.save(path, sample=False)` leaves the rows out. * **Playground runs** are kept with their tables and results so you can open them again; deleting a run removes it from the app. * **Uploaded tables** (large tables the Python library sends once, by reference) are kept so later calls can reuse them, and can be deleted with `DELETE /v1/uploads/{id}`. * **Keys** are sent only in the `Authorization` header. The Python library never writes them to disk or to its logs. ## Masking column names [Section titled “Masking column names”](#masking-column-names) Column names often say more than the numbers: `patient_hiv_status`, `supplier_margin`. `mask_columns=True` sends every column name as `c0`, `c1`, … instead, and maps the replies back, so your code and results still use your own names: ```python import pandas as pd from sklearn.model_selection import train_test_split from yhatlabs import Client titanic = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv") titanic = titanic.drop(columns=["PassengerId", "Name", "Ticket", "Cabin"]) train, test = train_test_split(titanic, random_state=0) yh = Client(mask_columns=True) # the API sees c0, c1, ... instead of Sex, Age, Fare, ... model = yh.fit(train, target="Survived") print(model.mask) print(model.importance(test).head(3).round(3).to_string(index=False)) # your column names, not c0, c1, ... model.delete() ``` Output ``` {'Survived': 'c0', 'Pclass': 'c1', 'Sex': 'c2', 'Age': 'c3', 'SibSp': 'c4', 'Parch': 'c5', 'Fare': 'c6', 'Embarked': 'c7'} ``` | feature | importance | stddev | | ------- | ---------- | ------ | | Sex | 0.283 | 0.003 | | Pclass | 0.129 | 0.027 | | Fare | 0.071 | 0.005 | Parameters: [`Client.fit`](/models/docs/reference/python#client-fit), [`FittedModel.importance`](/models/docs/reference/python#fittedmodel-importance) * Set it on the client (`Client(mask_columns=True)`), on a copy (`yh.with_options(mask_columns=True)`), or on one call (`forecast`, `predict`, `fit`, `evaluate_table`, …). It is off by default. * Everything comes back under your names: predictions, importance, effects, `out_of_range`, and the column names in error messages. * A stored fit keeps the mapping on your side: `model.predict(...)` masks the same way, and `model.save()` writes the mapping into the saved record, so a fit loaded with `yhatlabs.load(...)` keeps it. Without that record (for example `yh.get_fit(id)`), a fit only knows the masked names. * Predictions do not change: the models never read column names. * Values, category labels and series ids are sent as they are. Masking hides what the columns are called, not what is in them. Send only data you are allowed to share. For security reports, see the [security policy](https://github.com/yhatlabs/yhatlabs-python/blob/main/SECURITY.md). # Limits > Request sizes, quotas and fit lifetimes. ## Per request [Section titled “Per request”](#per-request) | Time series | | | ------------------------------------ | --------------------------------------------------------------------------- | | Series | 256 | | Points per series | 32,768 | | Points per request (with covariates) | 8,000,000 | | Horizon | 2,048 steps | | Targets and covariates per series | 256 | | Quantile levels | 32 | | Sample paths | 1,000 per series; 2,000,000 values (samples x horizon x series) per request | | Tables | | | ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | Rows | 200,000 per call (a one-shot predict counts training and predicted rows together) | | Columns | 2,000 | | A direct fit or one-shot predict | `fast`: up to 100,000 training rows x 100 columns; `medium` and `pro`: up to 25,000 x 100. Larger tables run as an [async job](/models/docs/api/jobs) | | Cells (training rows x columns) in an async job | 50,000,000 | | A comparison with standard models | up to 100,000 training rows x 100 columns | | Request size | 64 MB (gzip-compressed bodies are accepted and count at their inflated size) | | Uploaded table | 1 GB, 1,000,000 rows, 100,000,000 cells ([uploads](/models/docs/api/uploads)); a call that uses it is held to the limits above | | Quantile levels | 32 | Past its preset’s direct size, a direct table call answers HTTP 413 with error type `async_required`: send it again with `"async": true`. Past the caps above it answers `request_too_large`. The Python library splits large forecasting inputs into several requests, and sends a table past the direct size as a job and waits for it. `GET /v1/limits` (or `yh.server_limits()`) returns the current values; the direct sizes are under `tabular.direct`. ## Tunes [Section titled “Tunes”](#tunes) A [tune](/models/docs/time-series/tuning) takes the series of one request and at most 1,000 steps; every series needs at least `2 x horizon + 64` values. It is kept for `ttl_days` after its last use (30 by default, 365 at most). ## Fits [Section titled “Fits”](#fits) A stored fit is kept for `ttl_days` after its last use: 30 by default, 365 at most; every prediction from it starts the count again. Change it with `PATCH /v1/table/fits/{id}`, or delete the fit earlier with `DELETE /v1/table/fits/{id}` or `model.delete()`. ## Rate and concurrency [Section titled “Rate and concurrency”](#rate-and-concurrency) | Per key | | | ---------------------- | --------------------------------------- | | Requests to the models | 120 a minute | | Calls running at once | 8 forecasts, 2 tabular calls, 4 uploads | | Uploaded tables kept | 200, 10 GB in all | Over a limit, a call gets HTTP 429 with error type `rate_limited` and a `Retry-After` header saying how many seconds to wait. The Python library waits and retries on its own. An uploaded table is deleted after a period without use; the library uploads it again when needed. ## Pricing [Section titled “Pricing”](#pricing) Calls are counted in tokens, as an LLM API counts them, from the work the model does. Your organization pays in credits, at its rate per million tokens (1 credit per 1M tokens by default), and every call pays at least a small minimum. Credits are shown with decimals, to three places, so a small call costs a few hundredths of a credit (`0.02`). | Call | Tokens | | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | Forecast | per item: (history points, at most 2,048, + horizon) x (target columns + covariate columns) | | Feature columns | count in full up to 100; each column past 100 counts 0.05 (a 725-column table is priced as 131.25 columns) | | Fit | training rows x feature columns x preset (`fast` 1, `medium` 3, `pro` 8), plus 100,000 for a regression (its prediction distribution) | | Predict from a fit | the fit’s training cells x 0.5 + predicted rows x feature columns; x2 with ranges (`quantiles`) | | One-shot predict | the fit, plus predicted rows x feature columns (x2 with ranges) | | Importance | the fit’s training cells x 2 | | Compare with standard models | training rows x feature columns x 0.5 + predicted rows x feature columns | | Tune | steps x 8 windows x (1,024 + horizon) x (1 + known covariate columns), plus a forecast of every series | Every reply states `usage.tokens` and `usage.credits`. `POST /v1/estimate` prices a call before you make it, for free: ```sh curl https://api.yhatlabs.com/v1/estimate -H "Authorization: Bearer $YHAT_API_KEY" -H "Content-Type: application/json" \ -d '{"call": "fit", "train_rows": 100000, "features": 50, "preset": "medium"}' # {"tokens": 15000000, "credits": 15, "credits_per_m_tokens": 1, "min_tokens": 20000} ``` `GET /v1/limits` publishes the rules and your organization’s rates under `pricing`. A call that fails on our side costs nothing. Predicting from a saved model is charged on its training table’s size (0.5 x its cells) as well as the predicted cells, so scoring a few rows from a large fit still costs a share of the fit. Forecasts are counted in credits for keys of an organization (`fc.usage` in Python); keys we issued directly (for example for a benchmark) count forecasts in series against their own quota. # Support > How to get help. * **Questions and bugs in the Python library:** [open an issue](https://github.com/yhatlabs/yhatlabs-python/issues). Include the `request_id` from any error, and never your key. * **Access, quotas and anything else:** write to . * **Security issues:** see the [security policy](https://github.com/yhatlabs/yhatlabs-python/blob/main/SECURITY.md). # Checking predictions > See which predictions are extrapolations, and turn intervals into the chance of crossing a limit. A model is only as good as its training data is close to the row in front of it. Every tabular prediction says how close that is, and regression intervals turn into probabilities. ```python from sklearn.datasets import load_diabetes from sklearn.model_selection import train_test_split from yhatlabs import Client X, y = load_diabetes(return_X_y=True, as_frame=True) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) yh = Client() model = yh.fit(X_train.assign(progression=y_train), target="progression", task="regress") new = X_test.head(3).copy() new.iloc[2, new.columns.get_loc("bmi")] = 0.4 # far above any training patient res = model.predict(new, quantiles=[0.05, 0.25, 0.5, 0.75, 0.95]) print(res.df[["prediction", "q5", "q95"]].assign(out_of_range=res.out_of_range, novelty=res.novelty.round(2)).round(1)) print("P(progression > 200):", res.prob(above=200).round(2).tolist()) model.delete() ``` Output | | prediction | q5 | q95 | out_of_range | novelty | | --- | ---------- | ----- | ----- | ------------ | ------- | | 362 | 257.4 | 172.3 | 336.1 | \[] | 0.0 | | 249 | 251.9 | 153.2 | 318.8 | \[] | 0.8 | | 271 | 281.3 | 157.1 | 351.7 | \[bmi] | 1.0 | ``` P(progression > 200): [0.86, 0.8, 0.84] ``` Parameters: [`FittedModel.predict`](/models/docs/reference/python#fittedmodel-predict), [`PredictionResult.prob`](/models/docs/reference/python#predictionresult-prob) The third patient was given a BMI far above anyone in the training data. ## Out of range [Section titled “Out of range”](#out-of-range) `res.out_of_range` lists, per row, the columns whose value lies outside what training saw: a number beyond the training minimum or maximum, or a category training never had. `[]` means none. The third patient is flagged on `bmi`. ## Novelty [Section titled “Novelty”](#novelty) `res.novelty` measures how unlike the training data a row is as a whole, even when every column is within range. It is the distance to the nearest training rows, as a percentile of how far training rows are from each other: | Novelty | Meaning | | ---------- | ------------------------------------------------------------------------------------------------------------------- | | around 0.5 | as close to the training data as a typical training row | | above 0.95 | farther than nearly every training row: the model is extrapolating; treat the prediction and its interval with care | Numbers are standardised and each differing category counts as one unit of distance. Novelty is computed on first access. ## The chance of crossing a limit [Section titled “The chance of crossing a limit”](#the-chance-of-crossing-a-limit) `res.prob(above=x)` (or `below=`) reads each row’s intervals as a distribution: the chance that this patient’s progression exceeds 200 is 0.86, 0.80 and 0.84 above. Predict with several quantiles for a finer answer; beyond the outermost level the tail is extrapolated. ## What is kept [Section titled “What is kept”](#what-is-kept) To compute these, a fit keeps a profile of its training table on your machine: each column’s range and categories, and a sample of at most 2,000 training rows. Nothing about it is sent to us. It is saved with `model.save()`, so a loaded fit flags rows too. `yh.fit(..., profile=False)` drops it, and the flags are then `None`. The one-shot `yh.predict` builds the profile from the `train` you pass. # Tabular data > What a training table needs, which columns to keep or drop, and how to validate rows that arrive over time. Every tabular prediction starts from a table of examples whose answer you know: **one row per example**, and a column holding the answer. ## The training table [Section titled “The training table”](#the-training-table) These are the first passengers of the Titanic, a public dataset several examples here use: | PassengerId | Survived | Pclass | Sex | Age | SibSp | Parch | Fare | Embarked | | ----------- | -------- | ------ | ------ | --- | ----- | ----- | ----- | -------- | | 1 | 0 | 3 | male | 22 | 1 | 0 | 7.25 | S | | 2 | 1 | 1 | female | 38 | 1 | 0 | 71.28 | C | | 3 | 1 | 3 | female | 26 | 0 | 0 | 7.93 | S | | 4 | 1 | 1 | female | 35 | 1 | 0 | 53.10 | S | * Each row is one **example**: here, one passenger. * `Survived` is the **target**: the answer the model learns to predict (1 survived, 0 did not). * The other columns are **features**: what the prediction is made from (ticket class, sex, age, fare, …). `PassengerId` only numbers the rows, so it is dropped before training (see [Column types](#column-types)). ## The rows to predict [Section titled “The rows to predict”](#the-rows-to-predict) New rows have the same feature columns, without the target: | Pclass | Sex | Age | SibSp | Parch | Fare | Embarked | | ------ | ------ | ---- | ----- | ----- | ---- | -------- | | 3 | male | 34.5 | 0 | 0 | 7.83 | Q | | 3 | female | 47 | 1 | 0 | 7.00 | S | ```python res = yh.predict(train, "Survived", test) # learn from train, predict test, in one call model = yh.fit(train, "Survived") # or fit once and predict as often as you like res = model.predict(test) ``` A target with a few distinct values (`Survived`, a churn flag, a product category) is **classification**: each row gets a class and the probability of every class. A numeric target (a price, a strength, a duration) is **regression**: each row gets a number, and with `quantiles=` an interval around it. ## Column types [Section titled “Column types”](#column-types) * **Numbers, categories, booleans and dates** are used as they are. There is nothing to encode or scale. * **Missing values** are fine in features. Training rows with a missing target are dropped, with a warning. * **Free text** with many distinct values is treated as a category, not read as language. Group rare values or drop it. * **Identifiers** (customer ids, names, row numbers) carry no general signal. Drop them. pandas or polars DataFrames, lists of row dicts and 2-D numpy arrays are all accepted. ## Check a table first [Section titled “Check a table first”](#check-a-table-first) This checks the Titanic passenger list, a public dataset with text, categories and missing values, for predicting `Survived`: * Python ```python import pandas as pd import yhatlabs titanic = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv") report = yhatlabs.check(titanic, target="Survived") print(report) print(report.issues[["severity", "code", "where", "detail"]].to_string(index=False)) ``` Output ``` DataCheck(tabular: 12 columns, 2 warnings, 2 notes) ``` | severity | code | where | detail | | -------- | ---------------- | ----------- | -------------------------------------------------- | | warning | id_like | PassengerId | 891 distinct values in 891 rows: looks like an id. | | warning | id_like | Name | 891 distinct values in 891 rows: looks like an id. | | note | high_cardinality | Ticket | 681 distinct text values. | | note | mostly_missing | Cabin | 77% missing. | * CLI ```sh curl -s -o titanic.csv https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv yhatlabs check titanic.csv --target Survived ``` Output ```text DataCheck(tabular: 12 columns, 2 warnings, 2 notes) severity code where detail suggestion warning id_like PassengerId 891 distinct values in 891 rows: looks like an id. Drop identifier columns; they don't generalise. warning id_like Name 891 distinct values in 891 rows: looks like an id. Drop identifier columns; they don't generalise. note high_cardinality Ticket 681 distinct text values. Free text is not modelled; group rare values or drop it. note mostly_missing Cabin 77% missing. Fine to keep; missing values are handled. ``` Parameters: [`yhatlabs.check`](/models/docs/reference/python#yhatlabs-check) * `PassengerId` and `Name` are unique per row, so they look like ids: drop them. * `Ticket` has 681 distinct values: treated as a category, it adds little; drop it or group it. * `Cabin` is 77% empty: fine to keep, missing values are handled. ## Classification or regression [Section titled “Classification or regression”](#classification-or-regression) The task is inferred from the target. Pass `task="classify"` or `task="regress"` when it could be read either way, such as an integer rating from 1 to 5 or a small count. ## Rows that belong together [Section titled “Rows that belong together”](#rows-that-belong-together) When several rows come from one machine, batch, patient or store, pass `groups="machine"`: validation then holds out whole groups, so intervals and scores hold for groups the model has never seen. See [Rows that belong together](/models/docs/tabular/intervals-and-importance#rows-that-belong-together). ## Rows that arrive over time [Section titled “Rows that arrive over time”](#rows-that-arrive-over-time) When rows are ordered in time (signups, applications, transactions), validate on **later** rows than you train on. A random split lets the model learn from the period it is tested on, and the score looks better than it will be in production: ```python cutoff = df["signup"].quantile(0.8) train, test = df[df["signup"] < cutoff], df[df["signup"] >= cutoff] ``` Leave the timestamp itself out of the features: the future has dates the model never saw. `time_col="signup"` on `fit`, `predict` or `evaluate_table` does the same inside the fit: its validation holds out later periods, so its intervals are calibrated for rows that arrive after the training ones. ## Size [Section titled “Size”](#size) Up to 200,000 training rows and 200,000 rows to score per call. With `pyarrow` installed (`pip install "yhatlabs[parquet]"`), large tables are sent as parquet, and tables over 8 MB are uploaded once and then referred to by id, so a table reused across calls is sent only once ([Uploads](/models/docs/api/uploads), [Limits](/models/docs/resources/limits)). # Evaluating on your data > Cross-validate ChakraTab on your own table, and check whether its probabilities and intervals can be trusted. Benchmarks say how a model does on other people’s data. `evaluate_table` says how it does on yours: every row is predicted by a fit that never saw it, then the predictions are scored, for accuracy and for how honest their uncertainty is. ## Classification [Section titled “Classification”](#classification) This scores survival predictions for the Titanic passengers over 5 folds: ```python import pandas as pd from yhatlabs import Client titanic = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv") titanic = titanic.drop(columns=["PassengerId", "Name", "Ticket"]) yh = Client() ev = yh.evaluate_table(titanic, target="Survived", cv=5) print(ev) print({k: round(v, 3) for k, v in ev.summary.items()}) print(ev.reliability[["bin", "predicted", "observed", "count"]].round(2).to_string(index=False)) ev.plot().savefig("reliability.png", dpi=110) ``` Output ``` TableEvaluation(classify, shuffled, 5 folds, {'accuracy': 0.8305, 'log_loss': 0.3848, 'auc': 0.888}) ``` ``` {'accuracy': 0.831, 'log_loss': 0.385, 'brier': 0.238, 'auc': 0.888, 'ece': 0.032} ``` | bin | predicted | observed | count | | ------- | --------- | -------- | ----- | | 0.0-0.1 | 0.07 | 0.10 | 205 | | 0.1-0.2 | 0.14 | 0.10 | 250 | | 0.2-0.3 | 0.26 | 0.18 | 44 | | 0.3-0.4 | 0.35 | 0.43 | 58 | | 0.4-0.5 | 0.45 | 0.53 | 51 | | 0.5-0.6 | 0.54 | 0.48 | 27 | | 0.6-0.7 | 0.66 | 0.65 | 31 | | 0.7-0.8 | 0.75 | 0.73 | 37 | | 0.8-0.9 | 0.86 | 0.90 | 58 | | 0.9-1.0 | 0.96 | 0.96 | 130 | Parameters: [`Client.evaluate_table`](/models/docs/reference/python#client-evaluate_table) | Score | Meaning | | ---------- | ---------------------------------------------------------------------------------------------------- | | `accuracy` | share of rows with the right class | | `log_loss` | penalises confident wrong answers; lower is better | | `brier` | squared error of the probabilities; lower is better | | `auc` | how well the probabilities rank positives above negatives (one-vs-rest averaged for several classes) | | `ece` | calibration error: the average gap between predicted probability and how often it happened | `ev.reliability` is the calibration table: passengers given a 0.85 to 0.9 chance survived 87% of the time; those given 0.4 to 0.5, 47%. Close to the diagonal means the probabilities can be used as probabilities. `ev.plot()` draws it: ![Reliability diagram: predicted probability against observed survival, close to the diagonal](/models/docs/img/tab_evaluate-reliability.png) ## Regression [Section titled “Regression”](#regression) For numbers, the folds also score the prediction intervals (by default the 0.05 to 0.95 quantiles): ```python from sklearn.datasets import load_diabetes from yhatlabs import Client X, y = load_diabetes(return_X_y=True, as_frame=True) patients = X.assign(progression=y) yh = Client() ev = yh.evaluate_table(patients, target="progression", cv=5, task="regress") print({k: round(v, 3) for k, v in ev.summary.items() if k in ("mae", "rmse", "r2", "crps")}) print(ev.coverage.round(3).to_string(index=False)) print("PIT shares:", ev.pit["share"].round(2).tolist()) ev.plot().savefig("predicted_vs_actual.png", dpi=110) ``` Output ``` {'mae': 43.547, 'rmse': 53.742, 'r2': 0.513, 'crps': 23.706} ``` | interval | nominal | observed | width | gap | | -------- | ------- | -------- | ------- | ------ | | 90.0 | 0.9 | 0.903 | 173.148 | 0.003 | | 80.0 | 0.8 | 0.799 | 140.389 | -0.001 | | 50.0 | 0.5 | 0.500 | 76.913 | 0.000 | ``` PIT shares: [0.1, 0.09, 0.12, 0.1, 0.08, 0.11, 0.12, 0.08, 0.1, 0.1] ``` Parameters: [`Client.evaluate_table`](/models/docs/reference/python#client-evaluate_table) * `mae`, `rmse`, `r2`: the usual accuracy scores. * `crps`: the error of the whole predicted distribution, in the target’s units (lower is better). * `ev.coverage`: the share of actual values inside each interval. Here the 90% interval held 90.3% and the 50% interval 50.0%: the intervals are honest. * `ev.pit`: where each actual falls within its own predicted distribution, in ten bins. A flat histogram (about 0.1 per bin, as here) means calibrated; a U shape means intervals too narrow, a hump too wide, a slope a bias. ![Predicted against actual disease progression, with 90% intervals on a sample of rows](/models/docs/img/tab_evaluate_regression-predicted_vs_actual.png) ## Choose the folds [Section titled “Choose the folds”](#choose-the-folds) Random folds are right when every row is independent. When rows come in groups, or in time, they overstate how the model will do on new data: | Your data | Pass | Folds | | ---------------------------------------------- | ------------------ | -------------------------------------------------------------------------------------- | | independent rows | nothing | shuffled k-fold | | rows grouped by machine, batch, patient, store | `groups="machine"` | no group on both sides of a split, so the score is for groups the model has never seen | | rows ordered in time | `time_col="date"` | expanding window: each fold trains on everything before its block, never on the future | ```python import pandas as pd from yhatlabs import Client titanic = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv") titanic = titanic.drop(columns=["PassengerId", "Name", "Ticket"]) titanic["family"] = titanic["SibSp"].astype(str) + "-" + titanic["Parch"].astype(str) + "-" + titanic["Fare"].round(0).astype(str) yh = Client() ev = yh.evaluate_table(titanic, target="Survived", cv=5, groups="family") # no family on both sides of a split print(ev.split, {k: round(v, 3) for k, v in ev.summary.items() if k in ("accuracy", "log_loss", "auc")}) ``` Output ```text grouped {'accuracy': 0.813, 'log_loss': 0.424, 'auc': 0.856} ``` Parameters: [`Client.evaluate_table`](/models/docs/reference/python#client-evaluate_table) Grouping passengers who travelled as one family lowers the scores a little (accuracy 0.813 against 0.831): part of the shuffled score came from seeing relatives in training. The grouped number is the honest one for new families. ## Compare with standard models [Section titled “Compare with standard models”](#compare-with-standard-models) To see what ChakraTab adds over the models you would otherwise use, `compare=True` on `predict` also trains standard models on the same rows: XGBoost, a random forest and a linear model (LightGBM on request), plus a naive baseline. `res.comparison.score(actual, ChakraTab=res)` scores them all the same way, best first: ```python import pandas as pd from yhatlabs import Client titanic = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv") titanic = titanic.drop(columns=["PassengerId", "Name", "Ticket"]) train, test = titanic.iloc[:700], titanic.iloc[700:] yh = Client() res = yh.predict(train, target="Survived", test=test, task="classify", compare=True) # also XGBoost, random forest, linear print(res.comparison.score(test["Survived"], ChakraTab=res).round(3).to_string(index=False)) ``` Output | model | accuracy | balanced_accuracy | log_loss | roc_auc | | ----------------- | -------- | ----------------- | -------- | ------- | | ChakraTab | 0.864 | 0.851 | 0.335 | 0.918 | | XGBoost | 0.853 | 0.840 | 0.367 | 0.906 | | Random forest | 0.827 | 0.816 | 0.553 | 0.892 | | Linear model | 0.817 | 0.797 | 0.414 | 0.868 | | Most common class | 0.628 | 0.500 | NaN | NaN | Parameters: [`Client.predict`](/models/docs/reference/python#client-predict), [`Comparison.score`](/models/docs/reference/python#comparison-score) * `compare=["xgboost", "lightgbm"]` picks the models; `yh.compare(train, target, test)` runs the standard models alone. * Classification is scored by accuracy, balanced accuracy, log loss and, for two classes, ROC AUC; regression by MAE, RMSE and R2. * One split says less than cross-validation: on a small test set, differences of a point or two can be noise. * A comparison takes up to 100,000 training rows x 100 columns, and costs training rows x feature columns x 0.5 plus the predicted cells, in tokens ([Limits](/models/docs/resources/limits#pricing)). * From the CLI, `yhatlabs predict ... --compare` adds a `prediction_` column per standard model to the output. ## Options and cost [Section titled “Options and cost”](#options-and-cost) | Argument | | | --------------------------------------- | -------------------------------------------------------------- | | `cv=5` | number of folds (at least 2) | | `task`, `preset`, `eval_metric`, `seed` | as in `predict`; `task` is fixed up front so every fold agrees | | `quantiles=` | regression interval levels to score | Each fold is one fit-and-predict call, charged as one ([Limits](/models/docs/resources/limits#pricing)); `yh.estimate_table()` gives the cost of one beforehand. `ev.predictions` keeps every row’s out-of-fold prediction and fold number, indexed like your table. # Imputation > Fill the missing cells of a table from its other columns. `impute` fills empty cells with their most likely values, learned from the other columns. This fills the 177 missing ages in the Titanic passenger list: ```python import pandas as pd from yhatlabs import Client titanic = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv") titanic = titanic.drop(columns=["PassengerId", "Name", "Ticket", "Cabin"]) print("missing ages before:", titanic["Age"].isna().sum()) yh = Client() filled = yh.impute(titanic, columns=["Age"]) print("missing ages after:", filled["Age"].isna().sum()) print(filled[filled.attrs["filled"]["Age"]][["Pclass", "Sex", "SibSp", "Age"]].head(3).round(1).to_string(index=False)) ``` Output ``` missing ages before: 177 ``` ``` missing ages after: 0 ``` | Pclass | Sex | SibSp | Age | | ------ | ------ | ----- | ---- | | 3 | male | 0 | 29.4 | | 2 | male | 0 | 33.4 | | 3 | female | 0 | 20.5 | Parameters: [`Client.impute`](/models/docs/reference/python#client-impute) * For each column with gaps, the model learns that column from the other columns on the rows where it is present, and predicts it for the rest: one prediction call per column. * Numeric columns with many distinct values are treated as regression; the rest as classification. * `columns=[...]` limits it to some columns. `filled.attrs["filled"]` marks every filled cell. * A column with fewer than 10 observed values, or a single distinct value, is left as it is, with a warning. For gaps inside a time series, use [`fill_gaps`](/models/docs/time-series/anomalies-and-gaps#fill-gaps) instead: it fills from the series’ own history. # Intervals, importance and effects > Prediction intervals for numbers, which columns drive the predictions, and how each one moves them. ## Prediction intervals [Section titled “Prediction intervals”](#prediction-intervals) For a number, a range is often more useful than a single value: “between 160 and 340, most likely 253”. This predicts a disease-progression score for held-out patients, with a 90% interval around each: ```python from sklearn.datasets import load_diabetes from sklearn.model_selection import train_test_split from yhatlabs import Client X, y = load_diabetes(return_X_y=True, as_frame=True) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) yh = Client() model = yh.fit(X_train.assign(progression=y_train), target="progression", task="regress") res = model.predict(X_test, quantiles=[0.05, 0.5, 0.95]) print(res.df.head(3).round(1)) inside = ((y_test >= res.quantiles["q5"]) & (y_test <= res.quantiles["q95"])).mean() print(f"{inside:.0%} of held-out patients fall inside the 90% interval") model.delete() ``` Output | | prediction | q5 | median | q95 | mean | | --- | ---------- | ----- | ------ | ----- | ----- | | 362 | 257.4 | 172.3 | 272.1 | 336.1 | 266.2 | | 249 | 251.9 | 153.3 | 255.5 | 318.8 | 248.6 | | 271 | 153.7 | 63.8 | 149.5 | 274.4 | 158.0 | ``` 91% of held-out patients fall inside the 90% interval ``` Parameters: [`Client.fit`](/models/docs/reference/python#client-fit), [`FittedModel.predict`](/models/docs/reference/python#fittedmodel-predict) The interval for each row runs from `q5` to `q95`. On these held-out patients, 91% of the actual values fall inside it, close to the 90% asked for. The widths differ from row to row: patients whose outcome is harder to call get wider ranges. How the intervals are built: * For a regression fit, the model gives each row a full **predictive distribution**, not a point with a fixed margin. `mean` is its mean, `median` its middle, and any quantile comes from the same distribution (up to 32 levels at once). `res.interval_method` says `"distribution"`. * The distribution is **calibrated** on rows the model did not train on: a 90% interval held about 90% of those, so it holds about 90% of new rows like them. * Rows unlike the training data (values outside the ranges seen in training) get wider intervals, measured by how much the model’s errors grow when it has to extrapolate. * `res.prob(above=x)` reads the same distribution: the chance each row exceeds `x`. * If the distribution cannot be built for a table, intervals fall back to a single calibrated width for every row, and `res.interval_method` says `"conformal"`. * The same `quantiles=` works on the one-shot `yh.predict(...)`. ## Rows that belong together [Section titled “Rows that belong together”](#rows-that-belong-together) When rows come in groups (readings from one machine, tests of one batch, visits of one patient, mixes of one recipe), validating on random rows lets the model see each group on both sides of the split. Its errors look smaller than they will be on a group it has never seen, and so do its intervals. `groups=` holds out whole groups instead: ```python import pandas as pd from yhatlabs import Client # Concrete strength from mix proportions; rows that share a mix recipe belong together. url = "https://raw.githubusercontent.com/stedy/Machine-Learning-with-R-datasets/master/concrete.csv" concrete = pd.read_csv(url) mix = ["cement", "slag", "ash", "water", "superplastic", "coarseagg", "fineagg"] concrete["recipe"] = concrete[mix].astype(str).agg("-".join, axis=1) recipes = concrete["recipe"].drop_duplicates().sample(frac=0.25, random_state=0) new = concrete["recipe"].isin(recipes) # recipes the model never sees train, test = concrete[~new], concrete[new] yh = Client() for groups in (None, "recipe"): model = yh.fit(train, target="strength", groups=groups) res = model.predict(test.drop(columns="strength"), quantiles=[0.05, 0.95]) inside = ((test["strength"].values >= res.quantiles["q5"].values) & (test["strength"].values <= res.quantiles["q95"].values)).mean() print(f"groups={groups!r:9} 90% interval holds {inside:.0%} of new recipes, median width {(res.quantiles['q95'] - res.quantiles['q5']).median():.1f}") model.delete() ``` Output ```text groups=None 90% interval holds 96% of new recipes, median width 22.7 groups='recipe' 90% interval holds 90% of new recipes, median width 10.9 ``` Parameters: [`Client.fit`](/models/docs/reference/python#client-fit), [`FittedModel.predict`](/models/docs/reference/python#fittedmodel-predict) * With `groups="recipe"` every validation fold holds out whole recipes, so the intervals are calibrated for recipes the model has never seen: 90% of the new recipes’ strengths fall inside the 90% interval. Without it, the 90% interval held 96%. * The groups column is used for validation only, never as a feature. * `time_col=` does the same for rows over time: each fold holds out a contiguous period, and the column stays a feature. * Both work on `fit`, `predict` and `evaluate_table`. Pass one, not both. ## Sets of classes [Section titled “Sets of classes”](#sets-of-classes) For classification, `set_coverage=0.9` returns, for each row, the smallest set of classes that holds the true class 90% of the time: one class when the model is sure, two or more when it is not. This grades white wines as low, mid or high: ```python import pandas as pd from sklearn.model_selection import train_test_split from yhatlabs import Client url = "https://raw.githubusercontent.com/stedy/Machine-Learning-with-R-datasets/master/whitewines.csv" wine = pd.read_csv(url) wine["grade"] = pd.cut(wine["quality"], [0, 5, 6, 10], labels=["low", "mid", "high"]).astype(str) train, test = train_test_split(wine.drop(columns="quality"), random_state=0) yh = Client() res = yh.predict(train, "grade", test.drop(columns="grade"), set_coverage=0.9) sets = pd.Series(res.prediction_sets, index=test.index) print(sets.head(4).to_string()) print(f"sets hold the true grade for {pd.Series([g in s for g, s in zip(test['grade'], sets)]).mean():.0%} of wines") print("set sizes:", sets.map(len).value_counts().sort_index().to_dict()) ``` Output | | prediction_set | | ---- | -------------- | | 2762 | \[low, mid] | | 42 | \[mid] | | 1419 | \[mid] | | 3664 | \[high, mid] | ``` sets hold the true grade for 90% of wines ``` ``` set sizes: {1: 611, 2: 614} ``` Parameters: [`Client.predict`](/models/docs/reference/python#client-predict) * `res.prediction_sets` holds one list per row, `res.set_coverage` the level asked for. * The sets are built from the model’s out-of-sample errors (split-conformal prediction), so the coverage holds on new rows like the training ones, with no assumption about the probabilities being right. * A set of one class is a confident call; a set of two says the row is borderline between them. Sorting rows by set size sends the uncertain ones to a person. * Pass `groups=` here too when new rows come from new groups. ## Column importance [Section titled “Column importance”](#column-importance) Importance answers “which columns does the model rely on?”. This computes it on the held-out patients: ```python from sklearn.datasets import load_diabetes from sklearn.model_selection import train_test_split from yhatlabs import Client X, y = load_diabetes(return_X_y=True, as_frame=True) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) yh = Client() model = yh.fit(X_train.assign(progression=y_train), target="progression", task="regress") imp = model.importance(X_test.assign(progression=y_test)) # labeled rows the model has not seen print(imp.head(5).round(2).to_string(index=False)) print("computed on:", imp.attrs["source"]) model.delete() ``` Output | feature | importance | stddev | | ------- | ---------- | ------ | | s5 | 10.30 | 3.46 | | bmi | 7.50 | 3.17 | | bp | 3.48 | 0.93 | | s3 | 1.44 | 0.44 | | sex | 1.31 | 0.14 | ``` computed on: data ``` Parameters: [`FittedModel.importance`](/models/docs/reference/python#fittedmodel-importance) * `importance` is how much the score drops when that column’s values are shuffled: the larger the drop, the more the model relies on the column. `stddev` is its spread over repeated shuffles. * `computed on: data` means it used the labeled rows you passed. Rows the model has not seen give the most honest numbers. * Without `data`, a `fast` fit uses its own holdout split (`validation`), and a `medium` or `pro` fit falls back to training rows (`train`), which flatters the numbers. * Columns derived internally (date parts, for example) are summed back onto the column you passed. `yhatlabs.plots.importance(imp)` draws it as bars: ![Permutation importance bars: s5 and bmi lead](/models/docs/img/tab_effect-importance.png) ## Effects [Section titled “Effects”](#effects) Importance says a column matters; an effect shows how. `model.effect(col)` takes real rows (from the training sample the fit keeps, or `data=`), sets the column to each value in a grid, and predicts them all: ```python from sklearn.datasets import load_diabetes from yhatlabs import Client, plots X, y = load_diabetes(return_X_y=True, as_frame=True) yh = Client() model = yh.fit(X.assign(progression=y), target="progression", task="regress") eff = model.effect("bmi", grid=8) # 200 rows x 8 values = 1,600 predicted rows print(eff.round(3).to_string(index=False)) plots.effect(eff).savefig("effect.png", dpi=110) plots.importance(model.importance()).savefig("importance.png", dpi=110) model.delete() ``` Output | bmi | average | low | high | | ------ | ------- | ------- | ------- | | -0.081 | 117.032 | 79.357 | 162.199 | | -0.051 | 129.309 | 85.801 | 178.069 | | -0.031 | 138.488 | 91.585 | 189.824 | | -0.018 | 145.468 | 96.557 | 199.882 | | 0.002 | 156.654 | 103.675 | 212.374 | | 0.028 | 169.984 | 112.331 | 227.886 | | 0.060 | 185.554 | 123.355 | 243.905 | | 0.115 | 213.270 | 147.600 | 268.357 | Parameters: [`FittedModel.effect`](/models/docs/reference/python#fittedmodel-effect), [`plots.effect`](/models/docs/reference/python#plots-effect) * `average` is the mean prediction at that value: here progression rises from about 117 to 213 as BMI goes from its lowest to its highest values. * `low` / `high` are the 10th and 90th percentile across the rows. A wide band means the effect depends on the other columns. * For classification there is one curve per class, the average probability, in an `output` column. * `grid=` is a number of points (quantiles of the column, or the most frequent categories) or the values themselves. The cost is `rows x grid` predicted rows: 200 x 8 = 1,600 here. ![Average predicted progression rising with BMI, with the spread across patients](/models/docs/img/tab_effect-effect.png) # Predicting > Fit once and predict as often as you like, or fit and predict in one call, and read the results. There are two ways to predict on a table: **fit once** and predict from the stored fit as often as you like, or **one call** that fits and predicts together and keeps nothing. ## Fit once, predict many times [Section titled “Fit once, predict many times”](#fit-once-predict-many-times) This learns who survived from the first 700 Titanic passengers, then predicts the other 191: ```python import pandas as pd from yhatlabs import Client titanic = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv") titanic = titanic.drop(columns=["PassengerId", "Name", "Ticket"]) # identifiers carry no general signal train, test = titanic.iloc[:700], titanic.iloc[700:] yh = Client() model = yh.fit(train, target="Survived", task="classify") res = model.predict(test) # the Survived column in test is dropped before sending print(res.df.head(3).round(3)) print("accuracy on the last 191 passengers:", round((res.predictions == test["Survived"]).mean(), 3)) print(res.fit["n_rows"], "training rows,", res.fit["n_features"], "features") model.delete() ``` Output | | prediction | p_0 | p_1 | | --- | ---------- | ----- | ----- | | 700 | 1 | 0.019 | 0.981 | | 701 | 1 | 0.417 | 0.583 | | 702 | 0 | 0.852 | 0.148 | ``` accuracy on the last 191 passengers: 0.864 ``` ``` 700 training rows, 8 features ``` Parameters: [`Client.fit`](/models/docs/reference/python#client-fit), [`FittedModel.predict`](/models/docs/reference/python#fittedmodel-predict) `prediction` is the predicted class (`1` survived), and `p_0`, `p_1` are the probabilities. The fit runs once, on our side; each `predict` after it sends only the new rows. | Argument | Meaning | | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `train` | the training table, including the target column | | `target="Survived"` | the column to predict | | `task="classify"` | classification; `"regress"` for numbers (`"classification"` and `"regression"` work too); omit to infer it | | `preset` | `"fast"` (default, seconds on a few thousand rows; start here), `"medium"` (more accurate, about 3x the credits and 2-3x slower), `"pro"` (the most accurate, about 8x the credits and 4-8x slower than `"fast"`) | | `eval_metric` | what tuning optimises: `log_loss` (default), `roc_auc`, `accuracy`, `f1`; `rmse` (default), `mae`, `r2` | | `time_limit` | seconds for the fit | | `seed` | the fit is reproducible by default (seed 0) | | `ttl_days` | days the fit is kept after its last use: default 30, 1 to 365 | | `store=False` | the call isn’t shown in your Logs ([Data handling](/models/docs/resources/data-handling)) | | `background=True` | return a `Job` at once instead of waiting ([Large tables](#large-tables)) | `eval_metric` changes how the model is tuned, not the decision rule: the predicted class is always the most probable one. To flag on another threshold, use the probabilities. ## Keep, reuse and delete a fit [Section titled “Keep, reuse and delete a fit”](#keep-reuse-and-delete-a-fit) A fit lives until it expires (30 days after its last use by default) or you delete it. `save` writes a record of it that you can load in another process or on another machine with the same key. The file includes a sample of up to 2,000 training rows, used for the out-of-range and novelty checks; `model.save(path, sample=False)` leaves them out: ```python from sklearn.datasets import load_breast_cancer import yhatlabs from yhatlabs import Client X, y = load_breast_cancer(return_X_y=True, as_frame=True) yh = Client() model = yh.fit(X.iloc[:400].assign(diagnosis=y.iloc[:400]), target="diagnosis", ttl_days=7) model.save("diagnosis.json") # the fit's id and columns, and up to 2,000 training rows (sample=False: none) # later, in another process or on another machine with the same key: same = yhatlabs.load("diagnosis.json") print(same.id == model.id, same.predict(X.iloc[400:403]).predictions.tolist()) same.delete() ``` Output ```text True [0, 1, 1] ``` Parameters: [`FittedModel.save`](/models/docs/reference/python#fittedmodel-save), [`yhatlabs.load`](/models/docs/reference/python#yhatlabs-load) * `model.delete()` removes the fit and its stored training table. In a `with yh.fit(...) as model:` block it is deleted on exit. * `yh.fits()` lists your live fits; `yh.get_fit(id)` reattaches one by id. A fitted model also pickles. * Each prediction from a saved model is charged on the training table’s size (0.5 x its cells) plus the predicted cells ([Limits](/models/docs/resources/limits#pricing)); `model.usage` holds what the fit itself cost. For a regression, ranges (`quantiles=`) add a fixed cost per call, and about 10-20 seconds the first time on a saved model. ## One call [Section titled “One call”](#one-call) When you only need predictions once, `predict` fits and predicts in a single call and keeps nothing afterwards: * Python ```python import pandas as pd from yhatlabs import Client titanic = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv") titanic = titanic.drop(columns=["PassengerId", "Name", "Ticket"]) yh = Client() res = yh.predict(titanic.iloc[:700], target="Survived", test=titanic.iloc[700:705], task="classify") print(res.df.round(3)) ``` Output | | prediction | p_0 | p_1 | | --- | ---------- | ----- | ----- | | 700 | 1 | 0.019 | 0.981 | | 701 | 1 | 0.417 | 0.583 | | 702 | 0 | 0.852 | 0.148 | | 703 | 0 | 0.871 | 0.129 | | 704 | 0 | 0.820 | 0.180 | * CLI ```sh curl -s -o titanic.csv https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv head -701 titanic.csv > train.csv # header + first 700 passengers (head -1 titanic.csv; tail -n +702 titanic.csv | head -3) > new.csv # header + 3 more yhatlabs predict train.csv --target Survived --test new.csv --task classify 2>/dev/null ``` Output ```text index,prediction,p_0,p_1 0,1,0.029807,0.970193 1,0,0.526746,0.473254 2,0,0.784044,0.215956 ``` Parameters: [`Client.predict`](/models/docs/reference/python#client-predict) The CLI tab does the same from CSV files. Without `test=`, the rows of `train` whose target is empty are the ones predicted. `compare=True` also trains standard models on the same rows ([Evaluating](/models/docs/tabular/evaluating#compare-with-standard-models)). ## Large tables [Section titled “Large tables”](#large-tables) A fit or one-shot predict past its preset’s direct size (`fast` 100,000 training rows x 100 columns, `medium` and `pro` 25,000 x 100) runs as a background job on our side, and the call waits for it, so the result is the same. To get on with other work meanwhile, pass `background=True`: ```python job = yh.fit(train, "target", preset="pro", background=True) job.status() # "queued", "running", "succeeded", ... model = job.wait() # the fitted model (waits up to two hours by default); job.cancel() stops it ``` Spark, Dask, Ray and polars tables (lazy ones too) are accepted wherever a pandas table is. A distributed table larger than the API takes raises `DataError` before it is collected: sample or aggregate it first ([Limits](/models/docs/resources/limits)). ## Several targets [Section titled “Several targets”](#several-targets) A table often has more than one thing to predict. `target=[...]` fits each target on the feature columns alone (the other targets are left out, so one never leaks into another) and returns a `FitGroup` that predicts, explains and deletes them together. This predicts survival (a class) and the fare paid (a number) for the same passengers: ```python import pandas as pd from yhatlabs import Client titanic = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv") titanic = titanic.drop(columns=["PassengerId", "Name", "Ticket"]) train, test = titanic.iloc[:700], titanic.iloc[700:] yh = Client() group = yh.fit(train, target=["Survived", "Fare"], task={"Survived": "classify", "Fare": "regress"}) res = group.predict(test.drop(columns=["Survived", "Fare"]), quantiles=[0.1, 0.9]) print(group) print(res.df.head(3).round(2)) group.delete() ``` Output ``` FitGroup(targets=['Survived', 'Fare']) ``` | | Survived | | | Fare | | | | | --- | ---------- | ---- | ---- | ---------- | ----- | ------ | ----- | | | prediction | p_0 | p_1 | prediction | q10 | q90 | mean | | 700 | 1 | 0.03 | 0.97 | 86.37 | 54.01 | 141.07 | 92.33 | | 701 | 0 | 0.59 | 0.41 | 53.57 | 25.81 | 68.68 | 44.24 | | 702 | 1 | 0.39 | 0.61 | 13.66 | 7.94 | 16.54 | 13.14 | Parameters: [`Client.fit`](/models/docs/reference/python#client-fit), [`FitGroup.predict`](/models/docs/reference/python#fitgroup-predict) * `res.df` has two-level columns, so `res.df["Fare"]` is one target’s table; `res["Fare"]` is its full result. * `task=` can be one value or a dict per target. `quantiles=` applies to the regression targets. * `group.importance()` and `group.effect(col)` stack the targets with a `target` column; `group.save(path)` and `yhatlabs.load(path)` work as for one fit. * Each target is its own fit and is charged as one; predictions are charged per target. ## Everything a result holds [Section titled “Everything a result holds”](#everything-a-result-holds) | | | | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `res.predictions` | the class or number for each row, indexed like the rows you sent | | `res.probabilities` | classification: one column per class | | `res.quantiles` | regression with `quantiles=`: one column per level, with `median` and `mean` of each row’s distribution ([Intervals](/models/docs/tabular/intervals-and-importance)); `prediction` stays the point forecast to use | | `res.df` | all of the above in one table | | `res.out_of_range`, `res.novelty` | where a row lies outside the training data ([Checking predictions](/models/docs/tabular/checking-predictions)) | | `res.prob(above=x)` | regression: the chance each value exceeds a limit | | `res.fit` | the fit summary: rows, features, preset, model version, seconds | | `res.comparison` | with `compare=True`: the standard models’ predictions | | `res.provenance`, `res.timing`, `res.usage` | what produced the result, how long it took, and what it cost | # scikit-learn > Use ChakraTab as a scikit-learn estimator in pipelines, grid searches and cross-validation. ChakraTab is also a scikit-learn estimator, so existing scikit-learn code works with it unchanged. Install the extra first: ```sh pip install "yhatlabs[sklearn]" ``` This scores ChakraTab with 3-fold cross-validation on the breast cancer dataset: ```python from sklearn.datasets import load_breast_cancer from sklearn.model_selection import cross_val_score from yhatlabs.integrations import ChakraTabClassifier X, y = load_breast_cancer(return_X_y=True, as_frame=True) scores = cross_val_score(ChakraTabClassifier(ttl_hours=1), X, y, cv=3) print("accuracy per fold:", scores.round(3), "mean:", round(scores.mean(), 3)) ``` Output ```text accuracy per fold: [0.974 0.984 0.974] mean: 0.977 ``` * `ChakraTabClassifier` and `ChakraTabRegressor` are in `yhatlabs.integrations`. * `fit(X, y)` fits once on our side; `predict` and `predict_proba` send only the rows to score. * `ChakraTabRegressor().predict_quantiles(X, (0.05, 0.5, 0.95))` returns intervals indexed like `X`. * `.importance(X_holdout, y_holdout)` returns column importance. * Arguments: `model`, `preset`, `eval_metric`, `time_limit`, `seed`, `ttl_hours`, `api_key`, `base_url`. * They work in `Pipeline`, `GridSearchCV` and `cross_val_score`, clone cleanly, and pickle with their fit. Each fold or grid point is its own fit: a 3-fold cross-validation uses three fits from your quota. # Anomalies and gaps > Flag recent points the model did not expect, and fill missing values from each series' own history. The model that forecasts can also tell you which recent points it did not expect, and what a missing value most likely was. Both use only the data before the point in question. ## Find anomalies [Section titled “Find anomalies”](#find-anomalies) This plants one faulty reading in the temperatures, 12°C too warm, then scores the last 56 days: * Python ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") temps.loc[temps.index[-10], "Temp"] += 12 # plant one faulty reading, 10 days before the end yh = Client() flags = yh.detect_anomalies(temps, h=28, windows=2, time_col="Date", target_col="Temp") print(flags[flags["anomaly"]][["Date", "y", "median", "q10", "q90", "score"]].round(1).to_string(index=False)) ``` Output | Date | y | median | q10 | q90 | score | | ---------- | ---- | ------ | ---- | ---- | ----- | | 1990-11-07 | 19.2 | 12.5 | 9.9 | 15.6 | 3.0 | | 1990-12-22 | 25.2 | 14.3 | 11.5 | 18.0 | 4.3 | * CLI ```sh curl -sO https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv yhatlabs anomalies daily-min-temperatures.csv --h 28 --windows 2 --time-col Date --target-col Temp --only ``` Output ```text unique_id,Date,y,median,q10,q90,score,anomaly series_0,1990-11-07,19.2,12.501609400889498,9.87606544219341,15.571764253749585,3.014321242374082,True ``` Parameters: [`Client.detect_anomalies`](/models/docs/reference/python#client-detect_anomalies) Each recent point is compared with a forecast made from the data before it: * `score` is how far the actual value is from the median, in units of that forecast’s own spread. A point the model was unsure about needs a larger miss to count. * A point is an anomaly when `|score|` is above `threshold` (default 3). * Here the planted reading (22 December, score 4.3) is caught. One genuinely unusual warm night is flagged as well. | Argument | Meaning | | ----------- | --------------------------------------------------------------------- | | `h=28` | the length of each scored window; default one season of the series | | `windows=2` | how many windows, ending at the last point: 2 x 28 = the last 56 days | | `threshold` | the score above which a point is flagged; raise it for fewer alerts | `yhatlabs.plots.anomalies(flags)` draws the series, its expected range and the flagged points: ```python import pandas as pd from yhatlabs import Client, plots url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") temps["Date"] = pd.to_datetime(temps["Date"]) temps.loc[temps.index[-10], "Temp"] += 12 # one faulty reading yh = Client() flags = yh.detect_anomalies(temps, h=28, windows=2, time_col="Date", target_col="Temp") plots.anomalies(flags).savefig("anomalies.png", dpi=110) print("saved anomalies.png; flagged:", int(flags["anomaly"].sum())) ``` Output ```text saved anomalies.png; flagged: 2 ``` Parameters: [`Client.detect_anomalies`](/models/docs/reference/python#client-detect_anomalies), [`plots.anomalies`](/models/docs/reference/python#plots-anomalies) ![The last two months of temperatures, the q10 to q90 expected range, and two flagged readings](/models/docs/img/ts_plot_anomalies-anomalies.png) ## Score points as they arrive [Section titled “Score points as they arrive”](#score-points-as-they-arrive) For monitoring, `anomaly_stream` keeps the recent history of every series and scores only the points each update brings: ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") temps.loc[temps.index[-3], "Temp"] += 12 # a faulty reading among the newest points yh = Client() stream = yh.anomaly_stream(window=512, time_col="Date", target_col="Temp") stream.update(temps.iloc[:-7]) # the history so far: kept as context (the last 512 days) new = stream.update(temps.iloc[-7:]) # a week arrives: only these 7 points are scored print(new[["Date", "y", "median", "score", "anomaly"]].round(1).to_string(index=False)) ``` Output | Date | y | median | score | anomaly | | ---------- | ---- | ------ | ----- | ------- | | 1990-12-25 | 12.9 | 12.3 | 0.3 | False | | 1990-12-26 | 14.6 | 13.9 | 0.3 | False | | 1990-12-27 | 14.0 | 14.3 | -0.1 | False | | 1990-12-28 | 13.6 | 14.5 | -0.3 | False | | 1990-12-29 | 25.5 | 14.6 | 4.1 | True | | 1990-12-30 | 15.7 | 14.8 | 0.3 | False | | 1990-12-31 | 13.0 | 14.8 | -0.7 | False | Parameters: [`Client.anomaly_stream`](/models/docs/reference/python#client-anomaly_stream), [`AnomalyStream.update`](/models/docs/reference/python#anomalystream-update) * `stream.update(new_points)` returns the scores (`score`, `anomaly`, …) for the new points only, and keeps the last `window` points of every series (512 by default) for the next update. * Each update is one `detect_anomalies` call, however many series it holds. A series is scored once it has enough history before the new points; until then its points are only kept, as with the first update here. * `threshold=`, covariates and the column arguments work as for `detect_anomalies`. ## Fill gaps [Section titled “Fill gaps”](#fill-gaps) This removes five days from the temperatures, then fills every gap from the history before it: ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") truth = temps.iloc[3000:3005]["Temp"].tolist() temps = temps.drop(index=range(3000, 3005)) # remove five days yh = Client() filled = yh.fill_gaps(temps, time_col="Date", target_col="Temp") print(filled[filled["Temp_filled"]][["Date", "Temp"]].round(1).to_string(index=False)) print("actual:", truth) ``` Output | Date | Temp | | ---------- | ---- | | 1984-12-31 | 15.0 | | 1988-12-31 | 14.2 | | 1989-03-22 | 16.2 | | 1989-03-23 | 15.6 | | 1989-03-24 | 15.3 | | 1989-03-25 | 15.0 | | 1989-03-26 | 15.0 | ``` actual: [16.9, 16.5, 13.6, 13.2, 9.4] ``` Parameters: [`Client.fill_gaps`](/models/docs/reference/python#client-fill_gaps) * Every gap inside a series (missing values or missing timestamps) gets the median forecast from the data before it. * `_filled` marks what was filled; here, the five removed days and the two dates already missing from the data. * The filled values follow the level of the series, not every swing: compare them with the actual values printed below them. * A gap at the very start of a series, or longer than `max_gap`, stays empty. Known covariates passed as `known=` are used for the filled steps. # Backtesting > Measure accuracy and calibration on your own history, compare with baselines and with the forecast you use today. A backtest answers “how good would these forecasts have been?” before you rely on them. It cuts each series at several points near its end, forecasts from each cut using only the data before it, and scores the forecasts against what happened. ## Run a backtest [Section titled “Run a backtest”](#run-a-backtest) This replays four 28-day forecasts over the last 112 days of the Melbourne temperatures: * Python ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") yh = Client() ev = yh.evaluate(temps, h=28, windows=4, time_col="Date", target_col="Temp") print(ev.summary[["mase", "wql", "coverage@0.8", "skill_mase", "skill_wql"]].round(3)) ``` Output | model | mase | wql | coverage\@0.8 | skill_mase | skill_wql | | -------------- | ----- | ----- | ------------- | ---------- | --------- | | chakra-ts | 0.971 | 0.141 | 0.786 | 0.309 | 0.486 | | seasonal_naive | 1.535 | 0.275 | 0.955 | 0.000 | 0.000 | * CLI ```sh curl -sO https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv yhatlabs evaluate daily-min-temperatures.csv --h 28 --windows 4 --time-col Date --target-col Temp 2>&1 ``` Output ```text yhatlabs: warning: Filled 2 missing timestamps with gaps (sent as missing values). mase sql wql mae rmse coverage@0.8 skill_mase skill_sql skill_wql skill_mae skill_rmse model chakra-ts 0.9711 0.7899 0.1415 2.0716 2.7788 0.7857 0.3086 0.4858 0.4858 0.3086 0.2341 seasonal_naive 1.5349 1.5499 0.2750 3.2759 3.8653 0.9554 0.0000 0.0000 0.0000 0.0000 0.0000 ``` Parameters: [`Client.evaluate`](/models/docs/reference/python#client-evaluate) Each row is a model. `seasonal_naive` is a simple baseline, computed locally: it repeats the last week on daily data and the last year on weekly data (the last value when the history is shorter than two seasons): | Column | Meaning | | ---------------- | ------------------------------------------------------------------------------ | | `mase` | average error, scaled by how hard the series is (below 1 beats a naive guess) | | `wql` | quantile loss: how good the whole range is, not just the median | | `coverage@0.8` | the share of actuals inside the 80% interval (ideally 0.8) | | `skill_` | improvement over the baseline: 0.33 means a third less error; above 0 beats it | Here ChakraTS has nearly a third less error than the baseline, and half the quantile loss. | Argument | Meaning | | --------------------- | ----------------------------------------------------------------------- | | `windows=4` | how many cutoffs | | `step` | steps between cutoffs; default `h`, so the windows don’t overlap | | `baselines` | `("seasonal_naive",)` by default; `"naive"` (repeat the last value) too | | `known=`, `calendar=` | covariates, read from the table itself | ## Compare with your current forecast [Section titled “Compare with your current forecast”](#compare-with-your-current-forecast) The question that usually matters is “is it better than what we use today?”. `compare=` scores your own forecasts on the same windows. Here the “current” forecast is simply last year’s value on the same day: ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") temps["Date"] = pd.to_datetime(temps["Date"]) # your current forecast for the last 112 days; here, simply "same as a year ago" current = temps.tail(112)[["Date"]].copy() current["forecast"] = temps["Temp"].shift(365).tail(112).to_numpy() yh = Client() ev = yh.evaluate(temps, h=28, windows=4, time_col="Date", target_col="Temp", compare={"current": current}) print(ev.summary[["mase", "mae", "skill_mase"]].round(3)) ``` Output | model | mase | mae | skill_mase | | -------------- | ----- | ----- | ---------- | | chakra-ts | 0.971 | 2.072 | 0.309 | | seasonal_naive | 1.535 | 3.276 | 0.000 | | current | 1.441 | 3.075 | -0.020 | Parameters: [`Client.evaluate`](/models/docs/reference/python#client-evaluate) `compare` takes a table per forecast: the time column (plus the id column for several series), and either quantile columns (`median`, `q10`, …) or a single `forecast` column. Only the windows it covers are scored. ## Check the uncertainty [Section titled “Check the uncertainty”](#check-the-uncertainty) An 80% interval is only useful if it really holds about 80% of the actuals. `ev.calibration` measures that: ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") yh = Client() ev = yh.evaluate(temps, h=28, windows=4, time_col="Date", target_col="Temp") cal = ev.calibration print(cal[cal["kind"] == "interval"].round(3).to_string(index=False)) ``` Output | model | kind | nominal | observed | gap | n | | -------------- | -------- | ------- | -------- | ------ | --- | | chakra-ts | interval | 0.8 | 0.786 | -0.014 | 112 | | chakra-ts | interval | 0.6 | 0.634 | 0.034 | 112 | | chakra-ts | interval | 0.4 | 0.438 | 0.037 | 112 | | chakra-ts | interval | 0.2 | 0.286 | 0.086 | 112 | | seasonal_naive | interval | 0.8 | 0.955 | 0.155 | 112 | | seasonal_naive | interval | 0.6 | 0.902 | 0.302 | 112 | | seasonal_naive | interval | 0.4 | 0.688 | 0.288 | 112 | | seasonal_naive | interval | 0.2 | 0.438 | 0.238 | 112 | Parameters: [`Client.evaluate`](/models/docs/reference/python#client-evaluate), [`EvaluationResult.calibration`](/models/docs/reference/python#evaluationresult-calibration) * `kind="interval"`: the share of actuals inside each central interval. `nominal` is what it should be, `observed` what it was. * `gap` is observed minus nominal. Negative means the intervals were too narrow; positive, too wide. * Here ChakraTS’s 80% interval held 79% of the actuals, close to what it says. The baseline’s held 96% because it is much wider. * `kind="below"` rows (not shown) give the share of actuals below each quantile; `ev.plot_calibration()` draws them (needs `[plot]`). `ev.scores` has one row per model, series and window; `ev.forecasts` has every window’s forecast next to the actual values. ## Plot the backtest [Section titled “Plot the backtest”](#plot-the-backtest) `ev.plot()` draws the actuals across the scored windows, each window’s forecast with its intervals, and a dotted line at each cutoff (needs `[plot]`): ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") temps["Date"] = pd.to_datetime(temps["Date"]) yh = Client() ev = yh.evaluate(temps, h=28, windows=3, time_col="Date", target_col="Temp") ev.plot().savefig("backtest.png", dpi=110) print("saved backtest.png") ``` Output ```text saved backtest.png ``` Parameters: [`Client.evaluate`](/models/docs/reference/python#client-evaluate), [`EvaluationResult.plot`](/models/docs/reference/python#evaluationresult-plot) ![Three 28-day backtest windows: actual temperatures against each window’s median and interval bands](/models/docs/img/ts_plot_backtest-backtest.png) # Covariates > Give the model what you know about the future, what you see only in the past, and what is fixed per series. Forecasts improve when the model knows what drives the series: tomorrow’s temperature for electricity load, a planned promotion for sales. These extra columns are **covariates**. There are three kinds: | Kind | Example | Argument | | --------------------- | ------------------------------------------------------- | -------------------------------------------------- | | Known ahead | prices, planned promotions, holidays, weather forecasts | `known=[...]`, with the future values in `future=` | | Seen only in the past | footfall, a competitor’s price you learn afterwards | `past=[...]` | | Fixed per series | region, store size, product family | `static=[...]` | ## Values you know ahead [Section titled “Values you know ahead”](#values-you-know-ahead) The model needs each known covariate for every step it forecasts. `make_future` builds the table of future timestamps for you to fill in. This example uses a small synthetic electricity load that rises with temperature: ```python import numpy as np import pandas as pd from yhatlabs import Client from yhatlabs.features import make_future # a small synthetic example: hourly electricity load that rises with temperature hours = pd.date_range("2026-06-01", periods=24 * 21, freq="h") temperature = 20 + 6 * np.sin((hours.hour - 9) * np.pi / 12) load = 500 + 12 * temperature + np.random.default_rng(0).normal(0, 5, len(hours)) df = pd.DataFrame({"ds": hours, "y": load, "temperature": temperature}) future = make_future(df, h=24) # the next 24 timestamps future["temperature"] = 20 + 6 * np.sin((future["ds"].dt.hour - 9) * np.pi / 12) # your weather forecast yh = Client() fc = yh.forecast(df, h=24, known=["temperature"], future=future) print(fc.df.head(3).round(1)) ``` Output | unique_id | ds | q10 | median | q90 | | --------- | ------------------- | ----- | ------ | ----- | | series_0 | 2026-06-22 00:00:00 | 684.4 | 690.1 | 695.8 | | series_0 | 2026-06-22 01:00:00 | 672.6 | 679.3 | 686.6 | | series_0 | 2026-06-22 02:00:00 | 665.4 | 671.1 | 678.1 | Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast) * `make_future(df, h=24)` returns the id and timestamp of the next 24 steps of every series. * `future` must have a value for every known covariate at every future step. A missing value is an error, not a silent guess. * Known covariates may be numbers or text categories (`"promo"`, `"none"`). * Instead of a separate `future` table, the same table can carry the future: rows after a series’ last value, with the target blank and the known columns filled, are used as `future=`. ## Calendar effects [Section titled “Calendar effects”](#calendar-effects) Day of week, month and holidays are known for any date, so the client can add them for you, for the history and the horizon, with no future table needed. This adds day of week and month to the temperature forecast: ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") yh = Client() fc = yh.forecast(temps, h=28, time_col="Date", target_col="Temp", calendar=["dayofweek", "month"]) print(fc.provenance["settings"]["known"]) print(fc.df.head(2).round(1)) ``` Output ``` ['dayofweek', 'month'] ``` | unique_id | Date | q10 | median | q90 | | --------- | ---------- | ---- | ------ | ---- | | series_0 | 1991-01-01 | 11.5 | 13.8 | 15.9 | | series_0 | 1991-01-02 | 11.8 | 14.4 | 17.2 | Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast) * `calendar=True` adds hour, day of week, month and weekend. * A list (`calendar=["dayofweek", "month"]`) chooses which. * `calendar={"holidays": "US"}` also adds a holiday flag for that country (needs `pip install holidays`; `"subdiv": "TX"` for a state). * `yhatlabs.features.add_calendar(df)` adds the same columns to any table. ## How much each covariate matters [Section titled “How much each covariate matters”](#how-much-each-covariate-matters) `explain_forecast` shows how much each covariate moves the forecast. It forecasts once with every covariate, then once per covariate with that one set to a neutral value (numbers: the series’ mean over the history and the future; categories and flags: their most common value), and compares the medians step by step. Here load follows temperature, a hot day is coming, and a promotion flag does nothing: ```python import numpy as np import pandas as pd from yhatlabs import Client from yhatlabs.features import make_future # hourly electricity load that rises with temperature (which varies day to day), and a promotion flag that does nothing rng = np.random.default_rng(0) hours = pd.date_range("2026-06-01", periods=24 * 28, freq="h") day = rng.normal(0, 3, 28).repeat(24) # warmer and cooler days temperature = 20 + day + 6 * np.sin((hours.hour - 9) * np.pi / 12) load = 500 + 12 * temperature + rng.normal(0, 5, len(hours)) df = pd.DataFrame({"ds": hours, "y": load, "temperature": temperature, "promo": rng.integers(0, 2, len(hours))}) future = make_future(df, h=24) future["temperature"] = 26 + 6 * np.sin((future["ds"].dt.hour - 9) * np.pi / 12) # a hot day ahead future["promo"] = 0 yh = Client() ex = yh.explain_forecast(df, h=24, known=["temperature", "promo"], future=future) # 3 forecasts: all, and one per covariate print(ex.attrs["summary"].round(1)) print(ex[ex["covariate"] == "temperature"].iloc[12:15].round(1).to_string(index=False)) ``` Output | covariate | mean_abs_effect | | ----------- | --------------- | | temperature | 93.0 | | promo | 2.3 | | unique_id | ds | covariate | median | median_without | effect | | --------- | ------------------- | ----------- | ------ | -------------- | ------ | | series_0 | 2026-06-29 12:00:00 | temperature | 857.9 | 769.0 | 88.9 | | series_0 | 2026-06-29 13:00:00 | temperature | 871.4 | 780.0 | 91.3 | | series_0 | 2026-06-29 14:00:00 | temperature | 877.1 | 788.2 | 88.9 | Parameters: [`Client.explain_forecast`](/models/docs/reference/python#client-explain_forecast) * `.attrs["summary"]` is the average absolute effect per covariate, largest first, in the target’s units: temperature moves the forecast by about 90 here; the promotion flag hardly at all. * The table has one row per covariate and step: `median` (every covariate), `median_without` (this one neutral) and `effect`. * It costs one forecast plus one more per covariate in `known=` and `past=`. Calendar and `static=` columns are used in every forecast but not explained. # Time-series data > The table shape forecasts expect, how columns are found, and what the client fixes before sending. Every forecast starts from a table of the past: **one row per time**, holding the value you want to forecast. ## One series [Section titled “One series”](#one-series) This is Melbourne’s daily minimum temperature, the public dataset most examples on these pages use: | Date | Temp | | ---------- | ---- | | 1981-01-01 | 20.7 | | 1981-01-02 | 17.9 | | 1981-01-03 | 18.8 | | … | … | | 1990-12-31 | 13.0 | * `Date` is the **time** column: when each value was measured. The times are regular (one per day here; hourly, weekly or monthly work the same way). A missing day is fine. * `Temp` is the **target**: the quantity the forecast continues. ```python fc = yh.forecast(temps, h=28, time_col="Date", target_col="Temp") # the next 28 days ``` ## Many series [Section titled “Many series”](#many-series) To forecast several series in one call (every country, store, meter or product), stack them in one table and add an **id** column saying which series each row belongs to. This is yearly population for India and the United States: ```python import pandas as pd from yhatlabs import Client pop = pd.read_csv("https://raw.githubusercontent.com/datasets/population/main/data/population.csv") pop = pop[pop["Country Code"].isin(["IND", "USA"])][["Country Code", "Year", "Value"]] # two series, one long table print(pop.groupby("Country Code").tail(2).to_string(index=False)) yh = Client() fc = yh.forecast(pop, h=3, id_col="Country Code", time_col="Year", target_col="Value", freq="YS") print((fc.df.set_index(["Country Code", "Year"]) / 1e6).round(1)) # millions ``` Output | Country Code | Year | Value | | ------------ | ---- | ---------- | | IND | 2024 | 1450935791 | | IND | 2025 | 1463865525 | | USA | 2024 | 340003797 | | USA | 2025 | 341784857 | | Country Code | Year | q10 | median | q90 | | ------------ | ---- | ------ | ------ | ------ | | IND | 2026 | 1475.9 | 1476.6 | 1477.2 | | IND | 2027 | 1487.7 | 1489.1 | 1490.4 | | IND | 2028 | 1499.2 | 1501.4 | 1503.4 | | USA | 2026 | 342.4 | 343.7 | 344.8 | | USA | 2027 | 343.6 | 345.7 | 347.4 | | USA | 2028 | 345.2 | 347.9 | 350.1 | Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast) * `Country Code` is the **id**, `Year` the time and `Value` the target. One row per series and time is called the **long format**. * Each series is forecast on its own, from its own last time; series may start and end at different times. * Quota counts series, not rows: this call uses 2. ## Columns that help the forecast [Section titled “Columns that help the forecast”](#columns-that-help-the-forecast) Any other column you name is a **covariate**: something that moves the target, such as the temperature for electricity load or a promotion for sales. A covariate whose future you know (a calendar, a planned price) goes in `known=` with its future values; one known only up to now (yesterday’s load) goes in `past=`. See [Covariates](/models/docs/time-series/covariates). ## Column names [Section titled “Column names”](#column-names) The column roles are found by name, so with standard names you pass nothing: | Role | Found automatically | Otherwise | | ------ | -------------------------------------------------- | ------------------------------------------------------------------------- | | time | `ds`, `timestamp`, `time`, `date`, `datetime` | `time_col=` | | target | `y`, `target`, `value`, or the only numeric column | `target_col=` | | id | `unique_id`, `id`, `item_id`, `series_id` | `id_col=`; without one, the table is a single series, labelled `series_0` | Other columns are ignored, with a warning, unless you name them as covariates. A pandas Series with a date index, a polars DataFrame, or plain arrays with `freq=` work too. Integer time columns (1, 2, 3, …) are read as steps; pass `freq=` to say what one step is, as `freq="YS"` above says the years are yearly. ## What the client fixes before sending [Section titled “What the client fixes before sending”](#what-the-client-fixes-before-sending) * Parses the timestamps and sorts the rows. * Infers each series’ frequency (hourly, daily, monthly, …). A mix of frequencies is an error: forecast them separately, or pass `freq=`. * Adds missing timestamps as empty rows, so each series is on a regular grid. Missing values are sent as gaps; the model handles them. * Keeps the most recent 32,768 points of a very long series. * Splits large inputs into several requests and sends them in parallel. It warns whenever it changes something. Two rows with the same id and timestamp are an error: aggregate them first. ## What is refused, and what is read differently [Section titled “What is refused, and what is read differently”](#what-is-refused-and-what-is-read-differently) Some inputs cannot be forecast as they are, and a few are easy to misread. The client stops before sending, with a message that says what to change: ```python import numpy as np import pandas as pd from yhatlabs import Client, DataError yh = Client() # 50 readings at random times over seven months: no regular grid to forecast on rng = np.random.default_rng(0) when = pd.Timestamp("2026-01-01") + pd.to_timedelta(np.sort(rng.choice(5000, 50, replace=False)), unit="h") try: yh.forecast(pd.DataFrame({"ds": when, "y": rng.normal(size=50)}), h=3) except DataError as e: print("irregular:", str(e)[:150], "...") # integer time steps: kept as steps; freq= says what one step is steps = pd.DataFrame({"step": range(100, 160), "y": np.sin(np.arange(60) / 4)}) print(yh.forecast(steps, h=3, time_col="step", freq="h").df[["step", "median"]].round(2).to_string(index=False)) # a 2-D array: one series per row print(yh.forecast(np.arange(40.0).reshape(2, 20), h=2, freq="D").df[["unique_id", "ds", "median"]].round(1).to_string(index=False)) ``` Output ``` irregular: Series 'series_0' has 50 rows, but on a regular grid at frequency '13h' 320 of 370 timestamps would be missing. The timestamps look irregular: pass fr ... ``` | step | median | | ---- | ------ | | 160 | 0.65 | | 161 | 0.44 | | 162 | 0.20 | | unique_id | ds | median | | --------- | -- | ------ | | series_0 | 20 | 20.0 | | series_0 | 21 | 21.0 | | series_1 | 20 | 40.0 | | series_1 | 21 | 41.0 | Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast) | Input | What happens | | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | | timestamps so irregular that more than half the regular grid would be empty | refused: pass `freq=` for the spacing you want, or resample first | | rows without a series id | refused, naming the rows | | more targets or covariates than the API takes (256 of each) | refused before sending | | an empty table | refused | | integers in the time column (`1, 2, 3` or years) | read as steps; the forecast continues them, and `freq=` says what one step is | | a 2-D array or a list of lists | one series per row (`series_0`, `series_1`, …) | | infinite values | sent as missing, with a warning | ## Check the data first [Section titled “Check the data first”](#check-the-data-first) This checks the Melbourne temperatures locally, without a key, before anything is sent: * Python ```python import pandas as pd import yhatlabs url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") report = yhatlabs.check(temps, h=28, time_col="Date", target="Temp") print(report) print(report.issues[["severity", "code", "detail"]].to_string(index=False)) ``` Output ``` DataCheck(timeseries: 1 series, 1 note) ``` | severity | code | detail | | -------- | ------------------ | -------------------------------------- | | note | missing_timestamps | 2 missing timestamps (0% of the grid). | * CLI ```sh curl -sO https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv yhatlabs check daily-min-temperatures.csv --h 28 --time-col Date --target Temp ``` Output ```text DataCheck(timeseries: 1 series, 1 note) severity code where detail suggestion note missing_timestamps series_0 2 missing timestamps (0% of the grid). They are sent as gaps; yh.fill_gaps() fills them from the history before each gap. ``` Parameters: [`yhatlabs.check`](/models/docs/reference/python#yhatlabs-check) The one finding is a note: two dates are missing from the ten years (the last day of two leap years). They are sent as gaps, so nothing needs fixing. See [Data checks](/models/docs/tools/data-checks) for everything `check` looks for. # Forecasting > Forecast one series or many, choose the uncertainty you need, and read the results. `forecast` predicts the next values of every series in a table, with a range of likely outcomes around each one. ## A first forecast [Section titled “A first forecast”](#a-first-forecast) This forecasts the next 28 days of Melbourne’s daily minimum temperature from ten years of history: * Python ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") # 10 years of daily data: Date, Temp yh = Client() fc = yh.forecast(temps, h=28, time_col="Date", target_col="Temp") print(fc.df.head(3).round(1)) print(fc.quantile_levels, fc.usage) ``` Output | unique_id | Date | q10 | median | q90 | | --------- | ---------- | ---- | ------ | ---- | | series_0 | 1991-01-01 | 11.6 | 13.7 | 16.5 | | series_0 | 1991-01-02 | 11.7 | 14.3 | 17.5 | | series_0 | 1991-01-03 | 11.9 | 14.5 | 17.9 | ``` [0.1, 0.5, 0.9] {'series': 1, 'requests': 1} ``` * CLI ```sh curl -sO https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv yhatlabs forecast daily-min-temperatures.csv --h 28 --time-col Date --target-col Temp | head -4 ``` Output ```text unique_id,Date,q10,median,q90 series_0,1991-01-01,11.577219009399414,13.704099655151367,16.45543670654297 series_0,1991-01-02,11.744003295898438,14.314477920532227,17.50626564025879 series_0,1991-01-03,11.87166976928711,14.514473915100098,17.941247940063477 ``` Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast) Each row is one future day: `median` is the most likely value, and `q10` to `q90` is an 80% interval (the actual should fall inside it 8 days out of 10). `usage` shows what the call used: credits for keys of an organization, series for keys without one (as here). | Argument | Meaning | | ------------------- | --------------------------------------------------------------------- | | `temps` | the table: one row per date | | `h=28` | how many steps to forecast, at the series’ own frequency (here, days) | | `time_col="Date"` | the timestamp column, needed because it is not called `ds` | | `target_col="Temp"` | the column to forecast, needed because it is not called `y` | ## Choose the uncertainty [Section titled “Choose the uncertainty”](#choose-the-uncertainty) Every forecast is a set of **quantiles**: the 0.1 quantile is a value the actual falls below 10% of the time. Ask for the ones your decision needs: ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") yh = Client() fc = yh.forecast(temps, h=28, time_col="Date", target_col="Temp", quantiles=[0.1, 0.25, 0.5, 0.75, 0.9]) print(fc.df.head(2).round(1)) print("interpolated:", fc.derived) ``` Output | unique_id | Date | q10 | q25 | median | q75 | q90 | | --------- | ---------- | ---- | ---- | ------ | ---- | ---- | | series_0 | 1991-01-01 | 11.5 | 12.6 | 13.6 | 14.6 | 15.8 | | series_0 | 1991-01-02 | 11.8 | 13.0 | 14.2 | 15.6 | 17.1 | ``` interpolated: ['q25', 'q75'] ``` Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast) | You pass | You get | | ---------------------------- | ------------------------------------------------ | | nothing | `q10`, `median`, `q90`: an 80% interval | | `level=[50, 80, 95]` | central intervals by width in percent, under 100 | | `quantiles=[0.1, 0.25, ...]` | any levels strictly between 0 and 1 | | `quantiles="all"` | every level the model produces: 0.1, 0.2, …, 0.9 | The model produces the levels 0.1, 0.2, …, 0.9 directly. Levels in between (like 0.25 above) are interpolated, and `fc.derived` lists them, so an interpolated value is never presented as a model output. Levels outside 0.1 to 0.9 are computed by the API (next section). ## Intervals by width [Section titled “Intervals by width”](#intervals-by-width) `level=[50, 80]` asks for central intervals by their width in percent, and `fc.intervals()` returns them as `lower_` and `upper_` columns next to the median. `mean=True` adds the mean as well: ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") yh = Client() fc = yh.forecast(temps, h=28, time_col="Date", target_col="Temp", level=[50, 80], mean=True) print(fc.intervals([50, 80]).head(3).round(1).to_string(index=False)) print("mean next to the median:", fc.df[["median", "mean"]].iloc[0].round(2).tolist()) print("derived (not direct model outputs):", fc.derived) ``` Output | unique_id | Date | median | lower_50 | upper_50 | lower_80 | upper_80 | | --------- | ---------- | ------ | -------- | -------- | -------- | -------- | | series_0 | 1991-01-01 | 13.6 | 12.6 | 14.6 | 11.5 | 15.8 | | series_0 | 1991-01-02 | 14.2 | 13.0 | 15.6 | 11.8 | 17.1 | | series_0 | 1991-01-03 | 14.4 | 13.2 | 16.0 | 12.0 | 17.5 | ``` mean next to the median: [13.61, 13.61] ``` ``` derived (not direct model outputs): ['q25', 'q75', 'mean'] ``` Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast), [`ForecastResult.intervals`](/models/docs/reference/python#forecastresult-intervals) * `lower_80` / `upper_80` come from `q10` / `q90`; `lower_50` / `upper_50` from `q25` / `q75`. * `fc.intervals(w)` needs the quantiles of width `w` in the forecast; ask for them with `level=[w]`. * `q25`, `q75` and `mean` are listed in `fc.derived`: they are computed from the model’s quantiles, not produced by it. ## 95% and 99% intervals [Section titled “95% and 99% intervals”](#95-and-99-intervals) For decisions about rare outcomes (a reserve margin, a safety stock), ask for wider intervals: `level=[95, 99]`, or quantiles like 0.01 and 0.99: ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") yh = Client() fc = yh.forecast(temps, h=14, time_col="Date", target_col="Temp", level=[80, 95, 99]) print(fc.intervals(95).head(3).round(1).to_string(index=False)) print(fc.intervals(99).head(3).round(1).to_string(index=False)) print("interpolated:", fc.derived) ``` Output | unique_id | Date | median | lower_95 | upper_95 | | --------- | ---------- | ------ | -------- | -------- | | series_0 | 1991-01-01 | 13.6 | 9.9 | 17.4 | | series_0 | 1991-01-02 | 14.1 | 10.1 | 19.2 | | series_0 | 1991-01-03 | 14.3 | 10.1 | 19.7 | | unique_id | Date | median | lower_99 | upper_99 | | --------- | ---------- | ------ | -------- | -------- | | series_0 | 1991-01-01 | 13.6 | 8.3 | 19.0 | | series_0 | 1991-01-02 | 14.1 | 8.3 | 21.3 | | series_0 | 1991-01-03 | 14.3 | 8.3 | 21.9 | ``` interpolated: [] ``` Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast), [`ForecastResult.intervals`](/models/docs/reference/python#forecastresult-intervals) * The API computes these levels from the model’s quantiles, with tails fitted to the outer levels, and calibrates them on the series’ own past: earlier windows of the history are forecast, and every level is adjusted so it held as often as it says there. With little history the adjustment is shrunk toward none. * They are not interpolated, so `fc.derived` stays empty. * A 99% interval is only as reliable as the history behind it: a year of daily data has a few dozen days beyond the 1% tails. Check it with [`evaluate`](/models/docs/time-series/backtesting) before relying on it. ## Median or mean [Section titled “Median or mean”](#median-or-mean) The **median** is the point forecast: half the outcomes fall below it, and it is what the benchmarks score. The **mean** is what you want when forecasts are added up, over days or over products: medians of skewed quantities do not sum to the median of the total, and the sum of means is the mean of the sum. `mean=True` computes it from the model’s quantiles (integrating the quantile curve, with exponential tails beyond the outermost levels). On a symmetric forecast the two match, as above. ## Chance of crossing a limit [Section titled “Chance of crossing a limit”](#chance-of-crossing-a-limit) `fc.prob(above=x)` or `fc.prob(below=x)` turns the forecast into the probability of crossing a limit at each step: a capacity, a stock level, a temperature threshold. This asks, night by night, how likely the minimum stays above 15 degrees: ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") yh = Client() fc = yh.forecast(temps, h=14, time_col="Date", target_col="Temp", quantiles="all") warm = fc.prob(above=15) # chance the night stays above 15 degrees, per day print(warm.head(5).round(2).to_string(index=False)) print("expected nights above 15 degrees in the next 14:", round(warm["prob"].sum(), 1)) ``` Output | unique_id | Date | prob | | --------- | ---------- | ---- | | series_0 | 1991-01-01 | 0.18 | | series_0 | 1991-01-02 | 0.33 | | series_0 | 1991-01-03 | 0.38 | | series_0 | 1991-01-04 | 0.41 | | series_0 | 1991-01-05 | 0.42 | ``` expected nights above 15 degrees in the next 14: 5.8 ``` Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast), [`ForecastResult.prob`](/models/docs/reference/python#forecastresult-prob) * The limit is one number, or one per row. * Summing the probabilities gives the expected number of steps over the limit: about 6 of the next 14 nights here. * `quantiles="all"` gives the finest answer, since every level the model produces is used. Beyond its outermost levels the tail is extrapolated, so probabilities under 10% or over 90% are estimates. ## Sample paths [Section titled “Sample paths”](#sample-paths) Quantiles describe each step on its own. Questions about the whole horizon (the total over a fortnight, the peak, how many days cross a limit, whether three days in a row do) need **sample paths**: possible futures, each a full trajectory. `samples=1000` returns 1000 of them: ```python import numpy as np import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") yh = Client() fc = yh.forecast(temps, h=14, time_col="Date", target_col="Temp", samples=1000, seed=0) paths = fc.sample_paths() # one row per sample, one column per day print(paths.shape) warm = (paths > 15).sum(axis=1) # warm nights in each simulated fortnight print("warm nights, 90% range:", np.quantile(warm, [0.05, 0.95]).tolist(), " mean:", round(warm.mean(), 1)) print("chance of 3 warm nights in a row:", round(np.mean([(np.convolve(p > 15, np.ones(3), "valid") == 3).any() for p in paths]), 2)) ``` Output ```text (1000, 14) warm nights, 90% range: [0.0, 12.0] mean: 5.8 chance of 3 warm nights in a row: 0.66 ``` Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast), [`ForecastResult.sample_paths`](/models/docs/reference/python#forecastresult-sample_paths) * `fc.sample_paths()` is an array with one row per path and one column per step (pass a series id for the others); `fc.samples` holds them all as a long table: id, time, sample, value. * Each step’s values follow the forecast’s quantiles; neighbouring steps move together, with a correlation estimated from the series’ own past forecasts (0.8 when the history is too short to tell), so a warm night makes the next one likelier to be warm too. * `seed=` makes the paths reproducible. Up to 1000 paths per series, and 2 million values per request in all. * The probability of any event comes from counting paths: here, three warm nights in a row in two fortnights out of three, which no single-step quantile can tell you. ## Past-window forecasts [Section titled “Past-window forecasts”](#past-window-forecasts) `history=True` also returns what the model would have forecast from earlier points in the history, on the same settings. Put them next to what happened to see how forecasts behave on this series, without running a full backtest: ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") yh = Client() fc = yh.forecast(temps, h=14, time_col="Date", target_col="Temp", history=True) past = fc.history # what the model forecast from earlier cutoffs, next to what happened print(past.columns.tolist()) print(past.head(3).round(1).to_string(index=False)) ``` Output ``` ['unique_id', 'cutoff', 'Date', 'q10', 'q20', 'q30', 'q40', 'median', 'q60', 'q70', 'q80', 'q90'] ``` | unique_id | cutoff | Date | q10 | q20 | q30 | q40 | median | q60 | q70 | q80 | q90 | | --------- | ---------- | ---------- | ---- | ---- | ---- | ---- | ------ | ---- | ---- | ---- | ---- | | series_0 | 1990-11-19 | 1990-11-20 | 9.2 | 9.9 | 10.5 | 10.9 | 11.2 | 11.7 | 12.3 | 12.9 | 13.9 | | series_0 | 1990-11-19 | 1990-11-21 | 9.8 | 10.7 | 11.2 | 11.8 | 12.1 | 12.7 | 13.4 | 13.9 | 15.1 | | series_0 | 1990-11-19 | 1990-11-22 | 10.1 | 10.9 | 11.4 | 12.1 | 12.4 | 13.0 | 13.7 | 14.4 | 15.7 | Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast) `fc.history` has one block per earlier cutoff: the forecasts made with data up to `cutoff`, for the steps after it. For a scored backtest with baselines, use [`evaluate`](/models/docs/time-series/backtesting). ## One column per series [Section titled “One column per series”](#one-column-per-series) `fc.to_wide()` puts every series in its own column, one row per timestamp, the shape a spreadsheet or a dashboard expects. This forecasts the population of three countries five years ahead, from yearly figures: ```python import pandas as pd from yhatlabs import Client pop = pd.read_csv("https://raw.githubusercontent.com/datasets/population/main/data/population.csv") pop = pop[pop["Country Code"].isin(["IND", "CHN", "USA"])] # one row per country and year yh = Client() fc = yh.forecast(pop, h=5, id_col="Country Code", time_col="Year", target_col="Value", freq="YS") print((fc.to_wide() / 1e6).round(1)) # millions; one column per country ``` Output | Year | CHN | IND | USA | | ---- | ------ | ------ | ----- | | 2026 | 1403.5 | 1476.5 | 343.6 | | 2027 | 1400.3 | 1489.0 | 345.5 | | 2028 | 1396.9 | 1501.2 | 347.7 | | 2029 | 1393.4 | 1512.8 | 349.8 | | 2030 | 1390.0 | 1525.0 | 352.1 | Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast), [`ForecastResult.to_wide`](/models/docs/reference/python#forecastresult-to_wide) `to_wide(value="q90")` (or `"mean"`, …) spreads another column. Here `Year` holds plain integers: they are read as steps of the series and the forecast continues them, with `freq="YS"` telling the model the data is yearly. ## Plot [Section titled “Plot”](#plot) `fc.plot(history=df)` draws the median and every interval in the forecast as nested bands, after the end of the history (needs `pip install "yhatlabs[plot]"`): ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") temps["Date"] = pd.to_datetime(temps["Date"]) yh = Client() fc = yh.forecast(temps, h=60, time_col="Date", target_col="Temp", level=[50, 80]) fig = fc.plot(history=temps.tail(180)) fig.savefig("forecast.png", dpi=110) print("saved forecast.png") ``` Output ```text saved forecast.png ``` Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast), [`ForecastResult.plot`](/models/docs/reference/python#forecastresult-plot) ![60-day forecast of Melbourne minimum temperature with 50% and 80% bands after six months of history](/models/docs/img/ts_plot_forecast-forecast.png) ## Several targets per series [Section titled “Several targets per series”](#several-targets-per-series) `target_col=["load", "price"]` forecasts both columns of each series together. The results gain a `target` column. ## Fast or pro [Section titled “Fast or pro”](#fast-or-pro) `preset="pro"` (yhatlabs 0.2.2 and later) asks for a slower forecast that is slightly sharper on benchmarks; `"fast"` is the default. Start on fast: pro is worth it when a small gain in accuracy matters more than seconds. For a larger gain on your own data, see [Tuning on your data](/models/docs/time-series/tuning). ## Horizon and resolution [Section titled “Horizon and resolution”](#horizon-and-resolution) A forecast goes up to 2,048 steps ahead. Forecast at the resolution you make decisions at: resample very fine data first (5-second readings to 1-minute averages, then `h=180` for three hours). Raw high-frequency data forecasts worse and gives over-confident intervals, and a horizon in the thousands of steps is usually a sign the data is finer than the decision. `fc.df` keeps your own id and time column names (`unique_id` / `ds` stay `unique_id` / `ds`, `store` / `timestamp` stay `store` / `timestamp`), followed by the quantile columns. ## Large inputs [Section titled “Large inputs”](#large-inputs) Inputs too large for one request are split and sent in parallel (`max_concurrency=` on the client, default 4). If some requests fail, `on_error="warn"` still returns the series that succeeded and lists the rest in `fc.errors`; the default, `"raise"`, raises the first error. Spark, Dask, Ray and polars tables are accepted as well as pandas. `store=False` on a call and it isn’t shown in your Logs ([Data handling](/models/docs/resources/data-handling)). ## Everything a result holds [Section titled “Everything a result holds”](#everything-a-result-holds) | | | | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `fc.df` | the forecast table | | `fc.to_long()` | one row per series, time and quantile (and the mean, when asked for) | | `fc.to_wide(value="median")` | one column per series | | `fc.intervals(80)` | `lower_80` / `upper_80` next to the median | | `fc.samples`, `fc.sample_paths(id)` | sample paths, with `samples=N` | | `fc.history` | forecasts from earlier cutoffs, with `history=True` | | `fc.prob(above=x)`, `fc.prob(below=x)` | the chance of crossing a limit at each step | | `fc.plot(history=df)` | the median and nested interval bands after the history (needs `pip install "yhatlabs[plot]"`) | | `fc.quantile_levels`, `fc.derived` | the levels returned, and which were interpolated | | `fc.provenance` | model, settings, request ids and a fingerprint of the input | | `fc.timing`, `fc.usage` | seconds taken, and what the call used (credits, or series for keys without an organization; added up over split requests) | | `fc.to_polars()` | the table as polars | # Hierarchies > Forecast series that add up (stores into regions into a total) so the forecasts add up too. Many series come in a hierarchy: stores sum into regions and regions into a total, products into categories, meters into feeders. Forecast each level on its own and the forecasts rarely add up: the regions’ medians will not sum to the total’s. `yhatlabs.hierarchy` builds every level from the bottom rows and adjusts the forecasts so that every parent equals the sum of its children. ## Build, forecast, reconcile [Section titled “Build, forecast, reconcile”](#build-forecast-reconcile) This forecasts the population of seven countries, the two regions they form and the total, five years ahead: ```python import pandas as pd from yhatlabs import Client, hierarchy pop = pd.read_csv("https://raw.githubusercontent.com/datasets/population/main/data/population.csv") region = {"SWE": "Nordic", "NOR": "Nordic", "DNK": "Nordic", "FIN": "Nordic", "EST": "Baltic", "LVA": "Baltic", "LTU": "Baltic"} pop = pop[pop["Country Code"].isin(region)].assign(region=lambda d: d["Country Code"].map(region)) data, tree = hierarchy.aggregate(pop, levels=[["region"], ["region", "Country Code"]], time_col="Year", target_col="Value") print(tree["total"], tree["region=Baltic"]) yh = Client() fc = hierarchy.reconcile(yh.forecast(data, h=5, time_col="Year", target_col="Value", freq="YS"), tree) last = fc.df[fc.df["Year"] == fc.df["Year"].max()].set_index("unique_id")["median"] / 1e6 print(last.round(2).to_string()) print("Baltic = sum of its countries:", round(last["region=Baltic"], 3) == round(sum(last[c] for c in tree["region=Baltic"]), 3)) ``` Output ``` ['region=Baltic', 'region=Nordic'] ['region=Baltic/Country Code=EST', 'region=Baltic/Country Code=LTU', 'region=Baltic/Country Code=LVA'] ``` | unique_id | median | | ------------------------------ | ------ | | region=Baltic | 6.07 | | region=Baltic/Country Code=EST | 1.36 | | region=Baltic/Country Code=LTU | 2.91 | | region=Baltic/Country Code=LVA | 1.80 | | region=Nordic | 28.43 | | region=Nordic/Country Code=DNK | 6.17 | | region=Nordic/Country Code=FIN | 5.74 | | region=Nordic/Country Code=NOR | 5.79 | | region=Nordic/Country Code=SWE | 10.74 | | total | 34.50 | ``` Baltic = sum of its countries: True ``` Parameters: [`hierarchy.aggregate`](/models/docs/reference/python#hierarchy-aggregate), [`hierarchy.reconcile`](/models/docs/reference/python#hierarchy-reconcile), [`Client.forecast`](/models/docs/reference/python#client-forecast) * `hierarchy.aggregate(rows, levels=...)` takes the bottom-level rows and the columns that define each level, from the top down; the last level is the bottom. It returns a long table with one series per node (`region=Baltic`, `region=Baltic/Country Code=EST`, …, `total`) and the tree saying which children sum into each parent. * `yh.forecast(...)` forecasts every node, as for any set of series. * `hierarchy.reconcile(fc, tree)` adjusts every value column (median, mean and each quantile) so that each parent equals the sum of its children: here the Baltic forecast equals the sum of Estonia, Latvia and Lithuania. ## How it reconciles [Section titled “How it reconciles”](#how-it-reconciles) Each node’s own forecast counts in proportion to how few bottom series it sums: a country’s forecast is trusted for the country, the total’s for the total. This uses the structure alone and needs no backtest, so it works from the first forecast. * The median and mean add up exactly. * Interval edges are adjusted the same way, but a sum of 90% quantiles is not the 90% quantile of the sum. When the uncertainty of a total matters (a regional reserve, say), forecast with `samples=` and sum the paths. * `total=None` in `aggregate` leaves out the overall total; `fc.provenance["reconciled"]` records what was done. # Scenarios > Ask what-if questions by changing the values you know ahead and comparing the forecasts. A scenario is a version of the future you want to compare: a heatwave, a price change, a promotion. `scenarios` runs one forecast per version of the [known covariates](/models/docs/time-series/covariates) and stacks the results, so you can compare them side by side. This compares tomorrow’s electricity load under the weather forecast and under a heatwave 6°C warmer (synthetic data where load rises with temperature): ```python import numpy as np import pandas as pd from yhatlabs import Client from yhatlabs.features import make_future # the same synthetic hourly load as in Covariates: load rises with temperature hours = pd.date_range("2026-06-01", periods=24 * 21, freq="h") temperature = 20 + 6 * np.sin((hours.hour - 9) * np.pi / 12) load = 500 + 12 * temperature + np.random.default_rng(0).normal(0, 5, len(hours)) df = pd.DataFrame({"ds": hours, "y": load, "temperature": temperature}) base = make_future(df, h=24) base["temperature"] = 20 + 6 * np.sin((base["ds"].dt.hour - 9) * np.pi / 12) heatwave = base.assign(temperature=base["temperature"] + 6) yh = Client() out = yh.scenarios(df, 24, {"forecast weather": base, "heatwave +6C": heatwave}, known=["temperature"]) print(out.groupby("scenario")["median"].agg(["mean", "max"]).round(1)) ``` Output | scenario | mean | max | | ---------------- | ----- | ----- | | forecast weather | 739.6 | 809.7 | | heatwave +6C | 745.8 | 815.2 | Parameters: [`Client.scenarios`](/models/docs/reference/python#client-scenarios) | Argument | Meaning | | --------------------------------- | ----------------------------------------------------------------------------------- | | `df` | the history, with the known covariate columns | | `24` | the horizon | | `{"forecast weather": base, ...}` | one future table per scenario, each with the known covariates for every future step | | `known=["temperature"]` | which columns are known ahead | The result is a forecast table with a `scenario` column. Any other `forecast` argument (`level=`, `calendar=`, `static=`) applies to every scenario. # Tuning on your data > Fine-tune ChakraTS on your own series, check whether it helped, and forecast with it. ChakraTS forecasts series it has never seen. **Tuning** adapts it to yours: it trains on your history for a few minutes, then your forecasts use what it learned (how your paydays or promotions move demand, your own seasonality). This tunes on two stores’ daily orders, which jump on paydays and promotion days, and scores the forecast on 28 days held back: ```python import numpy as np import pandas as pd from yhatlabs import Client # a synthetic example: daily orders at two stores, which jump on paydays (the 1st and the 15th) and on promotion days days = pd.date_range("2023-01-01", periods=3 * 365, freq="D") rng = np.random.default_rng(0) stores = [] for store, base in (("north", 200), ("south", 120)): payday = days.day.isin([1, 15]).astype(float) promo = (rng.random(len(days)) < 0.08).astype(float) orders = base * (1 + 0.6 * payday + 0.4 * promo + 0.1 * np.sin(2 * np.pi * days.dayofweek / 7)) + rng.normal(0, 8, len(days)) stores.append(pd.DataFrame({"unique_id": store, "ds": days, "y": orders.round(1), "payday": payday, "promo": promo})) data = pd.concat(stores) history, actual = data[data.ds < days[-28]], data[data.ds >= days[-28]] # hold the last 28 days back to score on future = actual.drop(columns="y") yh = Client() tuned = yh.tune(history, h=28, known=["payday", "promo"], future=future) print(tuned) zero_shot = yh.forecast(history, h=28, known=["payday", "promo"], future=future) with_tune = tuned.forecast(history, known=["payday", "promo"], future=future) wape = lambda fc: (fc.df["median"].to_numpy() - actual["y"].to_numpy()).__abs__().sum() / actual["y"].abs().sum() print(f"error on the 28 days held back (WAPE): zero-shot {wape(zero_shot):.3f}, tuned {wape(with_tune):.3f}") tuned.delete() ``` Output ```text Tuned(id='tune_4c80b41cdceb795eb858c9b1', model='chakra-ts', used=True, series=2, horizon=28, holdout WAPE 0.0492 -> 0.0408) error on the 28 days held back (WAPE): zero-shot 0.042, tuned 0.039 ``` Parameters: [`Client.tune`](/models/docs/reference/python#client-tune), [`tuned.forecast`](/models/docs/reference/python#tuned-forecast) ## What a tune does [Section titled “What a tune does”](#what-a-tune-does) 1. It holds back the last `h` steps of every series and trains on the rest. 2. It forecasts the held-back steps with and without the tuning, and keeps the tuning only where it was better. 3. It trains again on the whole history, so the latest data is in it. `tuned.used` says whether the tune beat the model as it is on your held-back steps, and `tuned.holdout` has both scores (`wape`: the error as a share of the actuals; `loss`: the scaled quantile loss, lower is better). **A tune that did not win forecasts exactly like the model as it is**, so using one never makes a forecast worse than not tuning on that test. ## Forecast with it [Section titled “Forecast with it”](#forecast-with-it) ```python fc = tuned.forecast(df, known=["payday", "promo"], future=future) # h defaults to the tune's fc = yh.forecast(df, h=28, tune=tuned) # the same; tune= also takes the id ("tune_...") ``` A tune is kept 30 days after its last use (`ttl_days=`, up to 365) or until `tuned.delete()`. `yh.tunes()` lists your project’s tunes and `yh.get_tune(id)` reattaches to one; the handle can be pickled. The first forecast with a tune after a quiet spell takes 20 to 30 seconds while it loads; the next ones take about as long as any forecast. ## When it helps [Section titled “When it helps”](#when-it-helps) * **Drivers the model can’t read from the history alone:** paydays, promotions, price changes, holidays specific to you. Pass them as known covariates (`known=` with their future values in `future=`); they are part of the tuning. * **A few long series, or many alike:** the tune learns from all the series of the request together. * **Not for short history:** every series needs at least `2 x h + 64` values. Shorter ones are refused with a message. ## Options [Section titled “Options”](#options) | Argument | Meaning | | ------------------- | ---------------------------------------------------------------------------- | | `h` | the horizon you will forecast, and the steps the tune is scored on | | `steps=300` | training steps, 50 to 1,000; the best count is picked on the held-back steps | | `known=`, `future=` | known covariates and their next `h` values, as in `forecast` | | `name=` | a label, shown in `yh.tunes()` | | `ttl_days=30` | how long the tune is kept after its last use | | `background=True` | returns the `Job` at once; `job.wait()` gives the tune | A tune takes the series of one request (at most 256 series and 2,000,000 points with covariates): for more, tune on a representative subset, then forecast every series with it. It runs a few minutes as a background job, and its price is in [GET /v1/limits](/models/docs/resources/limits) (`pricing.tokens.tune`). From the command line: ```bash yhatlabs tune orders.csv --h 28 --known payday,promo --future future.csv # prints the tune and its id yhatlabs forecast orders.csv --h 28 --known payday,promo --future future.csv --tune tune_... ``` # Command line > Forecast, backtest, score anomalies and predict on CSV or parquet files from a terminal or a scheduler. The `yhatlabs` command comes with the Python library (`yhat` works as a short alias). It runs on CSV, parquet or JSON files, which suits shell scripts, schedulers and coding agents. ## A forecast from a file [Section titled “A forecast from a file”](#a-forecast-from-a-file) This downloads the temperatures and forecasts 28 days ahead. The forecast table goes to standard output as CSV: * Python ```python import pandas as pd from yhatlabs import Client url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") # 10 years of daily data: Date, Temp yh = Client() fc = yh.forecast(temps, h=28, time_col="Date", target_col="Temp") print(fc.df.head(3).round(1)) print(fc.quantile_levels, fc.usage) ``` Output | unique_id | Date | q10 | median | q90 | | --------- | ---------- | ---- | ------ | ---- | | series_0 | 1991-01-01 | 11.6 | 13.7 | 16.5 | | series_0 | 1991-01-02 | 11.7 | 14.3 | 17.5 | | series_0 | 1991-01-03 | 11.9 | 14.5 | 17.9 | ``` [0.1, 0.5, 0.9] {'series': 1, 'requests': 1} ``` * CLI ```sh curl -sO https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv yhatlabs forecast daily-min-temperatures.csv --h 28 --time-col Date --target-col Temp | head -4 ``` Output ```text unique_id,Date,q10,median,q90 series_0,1991-01-01,11.577219009399414,13.704099655151367,16.45543670654297 series_0,1991-01-02,11.744003295898438,14.314477920532227,17.50626564025879 series_0,1991-01-03,11.87166976928711,14.514473915100098,17.941247940063477 ``` Parameters: [`Client.forecast`](/models/docs/reference/python#client-forecast) Pick the CLI tab above. Add `-o forecast.csv` (or `.parquet`) to write a file instead. ## Commands [Section titled “Commands”](#commands) | Command | What it does | Main options | | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `check FILE` | checks the data locally, no key needed; exit code 2 on an error | `--h`, `--target` (or `--target-col`), `--id-col`, `--time-col` | | `forecast FILE --h N` | forecasts every series | `--level`, `--quantiles`, `--known` with `--future FILE`, `--past`, `--static`, `--preset pro` and `--tune ID` (0.2.2), `--no-store` | | `tune FILE --h N` (0.2.2) | [tunes](/models/docs/time-series/tuning) the model on your series (a few minutes); prints the tune and its id | `--steps`, `--name`, `--known` with `--future FILE` | | `evaluate FILE --h N` | backtests; prints the summary | `--windows`, `--step`, `-o` for per-window scores | | `anomalies FILE` | scores recent points | `--h`, `--windows`, `--threshold`, `--only` (flagged points only) | | `fill-gaps FILE` | fills gaps inside series | `--max-gap` | | `predict TRAIN --target COL` | tabular prediction | `--test FILE`, `--task`, `--preset fast\|medium\|pro`, `--quantiles`, `--groups`, `--time-col`, `--set-coverage`, `--compare` (adds a `prediction_` column per standard model), `--no-store` | | `evaluate-table FILE --target COL` | cross-validates on your table; prints accuracy and calibration | `--cv`, `--groups`, `--time-col`, `--task`, `--preset`, `-o` for every row’s out-of-fold prediction | | `whoami`, `models`, `usage`, `limits`, `fits`, `tunes` | account information, as JSON | | | `--version` | prints the installed version | | | `skills install` | installs the [agent skill](/models/docs/agents/skills) | `--dir` | Time-series commands take `--id-col`, `--time-col`, `--target-col` and `--freq` when the columns are not found by name. Every command takes `--base-url`. With `--no-store`, a `forecast` or `predict` call isn’t shown in your Logs ([Data handling](/models/docs/resources/data-handling)). ## For scripts and agents [Section titled “For scripts and agents”](#for-scripts-and-agents) * `--json` prints JSON records on standard output instead of CSV or text. It goes before or after the command (`yhatlabs --json whoami` or `yhatlabs whoami --json`). * Warnings go to standard error as one line each (`yhatlabs: warning: ...`). * The exit code is 0 on success, 1 on an error from the API or the input, and 2 when `check` finds an error. # Data checks > Find what will hurt a forecast or a prediction before anything is sent, locally and without a key. `check` looks at your data on your own machine, before anything is sent, and says what it found and how to fix it. It needs no key and makes no request. ## Time series [Section titled “Time series”](#time-series) With a time column, the data is checked as time series. Passing `h=` also checks there is enough history for that horizon: * Python ```python import pandas as pd import yhatlabs url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/" temps = pd.read_csv(url + "daily-min-temperatures.csv") report = yhatlabs.check(temps, h=28, time_col="Date", target="Temp") print(report) print(report.issues[["severity", "code", "detail"]].to_string(index=False)) ``` Output ``` DataCheck(timeseries: 1 series, 1 note) ``` | severity | code | detail | | -------- | ------------------ | -------------------------------------- | | note | missing_timestamps | 2 missing timestamps (0% of the grid). | * CLI ```sh curl -sO https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv yhatlabs check daily-min-temperatures.csv --h 28 --time-col Date --target Temp ``` Output ```text DataCheck(timeseries: 1 series, 1 note) severity code where detail suggestion note missing_timestamps series_0 2 missing timestamps (0% of the grid). They are sent as gaps; yh.fill_gaps() fills them from the history before each gap. ``` Parameters: [`yhatlabs.check`](/models/docs/reference/python#yhatlabs-check) ## Tables [Section titled “Tables”](#tables) With `target=` and no time column, the data is checked as a table to predict `target` from: * Python ```python import pandas as pd import yhatlabs titanic = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv") report = yhatlabs.check(titanic, target="Survived") print(report) print(report.issues[["severity", "code", "where", "detail"]].to_string(index=False)) ``` Output ``` DataCheck(tabular: 12 columns, 2 warnings, 2 notes) ``` | severity | code | where | detail | | -------- | ---------------- | ----------- | -------------------------------------------------- | | warning | id_like | PassengerId | 891 distinct values in 891 rows: looks like an id. | | warning | id_like | Name | 891 distinct values in 891 rows: looks like an id. | | note | high_cardinality | Ticket | 681 distinct text values. | | note | mostly_missing | Cabin | 77% missing. | * CLI ```sh curl -s -o titanic.csv https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv yhatlabs check titanic.csv --target Survived ``` Output ```text DataCheck(tabular: 12 columns, 2 warnings, 2 notes) severity code where detail suggestion warning id_like PassengerId 891 distinct values in 891 rows: looks like an id. Drop identifier columns; they don't generalise. warning id_like Name 891 distinct values in 891 rows: looks like an id. Drop identifier columns; they don't generalise. note high_cardinality Ticket 681 distinct text values. Free text is not modelled; group rare values or drop it. note mostly_missing Cabin 77% missing. Fine to keep; missing values are handled. ``` Parameters: [`yhatlabs.check`](/models/docs/reference/python#yhatlabs-check) ## What you get [Section titled “What you get”](#what-you-get) * `.issues`: one row per finding, with `severity` (`error`, `warning` or `note`), `code`, `where`, `detail` and `suggestion`. * `.profile`: one row per series (start, end, points, frequency, missing values) or per column (type, missing share, distinct values). * `.ok`: `False` when something would make the call fail. * `.repaired()`, for series: the data after the clean-up `forecast` applies (sorted, duplicates dropped, missing timestamps added), so you can see it before sending. From the terminal, `yhatlabs check` exits with code 2 when it finds an error, so it can stop a pipeline. ## Everything it looks for [Section titled “Everything it looks for”](#everything-it-looks-for) | Time series | Tables | | ------------------------------------------------------ | ------------------------------------------------ | | duplicate rows, or timestamps repeated within a series | a target with a single value | | mixed or unknown frequencies | columns that copy, or nearly copy, the target | | missing timestamps and values | id-like columns | | too little history for the horizon | imbalanced classes | | extreme values, rare negatives | integer targets that could be classes or a count | | series that end before the others | constant, mostly empty or free-text columns | # Plots > One chart for every result, from forecasts to calibration. `yhatlabs.plots` draws every result with matplotlib (`pip install "yhatlabs[plot]"`). Each function returns the Figure, so `.savefig(...)` or further styling works as usual. ```python from yhatlabs import plots ``` | Function | Draws | Also as | | ----------------------------------- | ----------------------------------------------------------------------- | -------------------------------------- | | `plots.forecast(fc, history=df)` | the median and every interval as nested bands, after the history | `fc.plot(...)` | | `plots.backtest(ev)` | actuals across the windows, each window’s forecast, the cutoffs | `ev.plot()` | | `plots.calibration(ev)` | forecast quantiles: nominal level against the share of actuals below it | `ev.plot_calibration()` | | `plots.anomalies(flags)` | the series, its expected range and the flagged points | | | `plots.scenarios(sc, history=df)` | one line and band per scenario | | | `plots.reliability(ev)` | classification: predicted probability against observed frequency | `ev.plot()` on a table evaluation | | `plots.predicted_vs_actual(res, y)` | regression: predictions against true values, with interval bars | `ev.plot()` on a regression evaluation | | `plots.importance(imp)` | permutation importance bars with their spread | | | `plots.effect(eff)` | an effect curve: the average prediction and the spread across rows | | The forecast plots take `ids=[...]` or `max_series=` (default 4) to choose which series to draw, and `ax=` to draw into your own axes. ## Forecasts [Section titled “Forecasts”](#forecasts) ![Forecast with nested 50% and 80% bands after the history](/models/docs/img/ts_plot_forecast-forecast.png) **`fc.plot(history=df)`**: the history in grey, then the median forecast with its 50% and 80% intervals as nested bands; the darker band is where the actual is more likely to land. ![Backtest windows with cutoffs](/models/docs/img/ts_plot_backtest-backtest.png) **`ev.plot()`**: a backtest. The dark line is what happened; each blue block is a forecast made at the dotted cutoff, without seeing anything after it. Actuals outside the bands are misses. ![Anomalies: expected range and flagged points](/models/docs/img/ts_plot_anomalies-anomalies.png) **`plots.anomalies(flags)`**: the shaded band is the range the model expected each point in (q10 to q90 of a forecast made just before it); red points are the readings flagged as anomalies. ## Tables [Section titled “Tables”](#tables) ![Reliability diagram](/models/docs/img/tab_evaluate-reliability.png) **`plots.reliability(ev)`**: are the probabilities honest? Each point groups the rows given a similar probability and plots how often the event happened. On the dashed diagonal, a 70% means 70%. ![Predicted against actual with intervals](/models/docs/img/tab_evaluate_regression-predicted_vs_actual.png) **`plots.predicted_vs_actual(res, y)`**: each dot is a row, predicted against true; the bars are its 90% interval. Close to the dashed diagonal is accurate, and a bar crossing it means the interval held the true value. ![Importance bars](/models/docs/img/tab_effect-importance.png) **`plots.importance(imp)`**: how much the score drops when a column’s values are shuffled. Longer bars are columns the model relies on more; the black line is the spread over repeats. ![Effect curve](/models/docs/img/tab_effect-effect.png) **`plots.effect(eff)`**: how the prediction moves as one column changes, everything else as in real rows. The line is the average; the band shows how much that differs between rows. The code for each is on the page of the feature: [Forecasting](/models/docs/time-series/forecasting#plot), [Backtesting](/models/docs/time-series/backtesting#plot-the-backtest), [Anomalies](/models/docs/time-series/anomalies-and-gaps), [Evaluating on your data](/models/docs/tabular/evaluating), [Effects](/models/docs/tabular/intervals-and-importance#effects). # Python library > Install yhatlabs, configure the client, handle errors, use async, and see what each call did. `yhatlabs` is the official Python library. It takes pandas, polars (lazy too), Spark, Dask or Ray tables, handles batching, retries, background jobs and data checks, and returns pandas results. A distributed table larger than the API takes raises `DataError` before it is collected. ## Install [Section titled “Install”](#install) ```sh pip install yhatlabs ``` Python 3.9 or later; it depends on httpx, numpy and pandas. Extras add optional features: | Extra | Adds | | ----------- | ------------------------------------------------------- | | `[sklearn]` | the scikit-learn estimators | | `[plot]` | `yhatlabs.plots` and the `.plot()` methods (matplotlib) | | `[parquet]` | smaller uploads of large tables (pyarrow) | | `[fast]` | faster encoding of large requests (orjson, pyarrow) | | `[all]` | all of the above, plus polars and holidays | ## The client [Section titled “The client”](#the-client) `Client()` is the entry point; every call goes through it. | Argument | Default | | ----------------- | ----------------------------------------------------------------------------------------------------------------------- | | `api_key` | `YHAT_API_KEY` | | `base_url` | `YHAT_BASE_URL`, else `https://api.yhatlabs.com` | | `timeout` | 300 seconds per request | | `max_retries` | 3 | | `max_concurrency` | 4 parallel requests when an input is split | | `mask_columns` | `False`: column names are sent as they are ([Data handling](/models/docs/resources/data-handling#masking-column-names)) | * `yh.with_options(timeout=1800)` returns a copy with other settings for one call, sharing the connection. * `with Client() as yh:` closes the connection when the block ends. | Time series | Tables | Account | | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------- | | `forecast`, `evaluate`, `scenarios`, `explain_forecast`, `detect_anomalies`, `anomaly_stream`, `fill_gaps` | `fit`, `predict`, `compare`, `evaluate_table`, `estimate_table`, `impute`, `get_fit`, `fits` | `whoami`, `models`, `usage`, `server_limits` | Module functions: `yhatlabs.check`, `yhatlabs.outliers` (rows unlike the training rows; local, no key) and `yhatlabs.load`. Helpers in `yhatlabs.features`: `add_calendar` and `make_future`. Charts in `yhatlabs.plots` ([Plots](/models/docs/tools/plots)). `yh.limits` holds the API’s request caps, read from `GET /v1/limits` on first need, and the features the API has switched on: `yh.limits.supports("gzip_requests")`. The library uses a feature only once the API lists it, so features added to the API later reach this version too. ## Async [Section titled “Async”](#async) `AsyncClient` has the same calls as coroutines, for services and notebooks that already run an event loop: ```python from yhatlabs import AsyncClient async with AsyncClient() as yh: fc = await yh.forecast(df, h=24) model = await yh.fit(train, target="churn") res = await model.predict(test) ``` ## Background jobs [Section titled “Background jobs”](#background-jobs) A table past the direct size runs as a background job, and `fit` or `predict` waits for it, so the result is the same. `background=True` returns a `Job` at once instead: `job.status()`, `job.wait(timeout=)` (two hours by default), `job.result()` and `job.cancel()` ([Async jobs](/models/docs/api/jobs#in-python)). ## Errors [Section titled “Errors”](#errors) | Raised | When | | ----------------------------- | -------------------------------------------------------------------------------- | | `DataError` | before anything is sent: the input can’t be used; the message says how to fix it | | `UnsupportedError` | the model can’t do what was asked | | `ConfigurationError` | no key, or a missing optional package (the message names the package) | | `APIError` and its subclasses | the API returned an error; they carry `.status`, `.type` and `.request_id` | | `JobFailedError` | a background job failed or was canceled; `.job_id` names it | `APIError` subclasses: `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404), `RequestTooLargeError` (413), `BadRequestError` (400, 422), `RateLimitError` (429), `InternalServerError` (5xx), `ServiceUnavailableError` (503). Network problems raise `APIConnectionError` or `APITimeoutError`. Timeouts, connection errors, and 408, 409, 429 and 5xx responses are retried with backoff, honouring `Retry-After`. A used-up quota is not retried. Quote the `request_id` to us and we can trace the call. Every POST carries an `Idempotency-Key` that stays the same across its retries. If a connection drops after a fit was made, the retry gets the first reply back instead of fitting, and paying, twice ([API overview](/models/docs/api/overview#conventions)). Request bodies over 1 MB are sent gzip-compressed once the API lists the `gzip_requests` capability. ## See what each call did [Section titled “See what each call did”](#see-what-each-call-did) * `YHAT_LOG=info` logs every request: method, path, status, time, request id and retries. Data and keys are never logged. * In a terminal, a one-line activity indicator appears once a call runs for more than two seconds. `YHAT_PROGRESS=0` turns it off; scripts and notebooks stay silent. * Every result carries `.provenance` (model, settings, request ids, library version, a fingerprint of the input) and `.timing`.