# 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

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

| 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](https://yhatlabs.com/models/docs/img/tab_evaluate-reliability.png)

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

- `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](https://yhatlabs.com/models/docs/img/tab_evaluate_regression-predicted_vs_actual.png)

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

```
grouped {'accuracy': 0.813, 'log_loss': 0.424, 'auc': 0.856}
```

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

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

- `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](https://yhatlabs.com/models/docs/resources/limits#pricing)).
- From the CLI, `yhatlabs predict ... --compare` adds a `prediction_<model>` column per standard model to the output.

## 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](https://yhatlabs.com/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.
