# 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

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

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

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:

```
True [0, 1, 1]
```

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

When you only need predictions once, `predict` fits and predicts in a single call and keeps nothing afterwards:

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

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

```
index,prediction,p_0,p_1
0,1,0.029807,0.970193
1,0,0.526746,0.473254
2,0,0.784044,0.215956
```

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](https://yhatlabs.com/models/docs/tabular/evaluating#compare-with-standard-models)).

## 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](https://yhatlabs.com/models/docs/resources/limits)).

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

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

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