# Intervals, importance and effects

> Prediction intervals for numbers, which columns drive the predictions, and how each one moves them.

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

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

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:

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

- 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

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:

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

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

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

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

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

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