# 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

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

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

- **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

This checks the Titanic passenger list, a public dataset with text, categories and missing values, for predicting `Survived`:

```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.
```

```bash
curl -s -o titanic.csv https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv
yhatlabs check titanic.csv --target Survived
```

Output:

```
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.
```

- `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

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

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](https://yhatlabs.com/models/docs/tabular/intervals-and-importance#rows-that-belong-together).

## 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

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](https://yhatlabs.com/models/docs/api/uploads), [Limits](https://yhatlabs.com/models/docs/resources/limits)).
