<!-- https://predictabl.tech/docs/build-a-model/ -->
# Build a model

Building has three steps: **data**, **plan**, **train**. `data.predict(question)`
runs all three. This page shows each one, so you can review and adjust before
training.

## 1. Data

```python
import predictabl as pb

data = pb.connect("postgresql://readonly:pw@db.acme.com/sales")  # a database
data = pb.connect("orders.csv")                                   # one file
data = pb.connect(["customers.csv", "orders.csv", "tickets.csv"]) # several related tables
data = pb.connect(df, name="Orders")                              # a pandas DataFrame
```

Several tables are fine: Predictabl finds how they link (`customer_id` in
orders to `customer_id` in customers) and can join them. You do **not** need to
pre-join or clean the data, or build a training table.

`connect()` returns once Predictabl has read the tables.

### A database

Predictabl reads the database **where it is, read-only**: it only runs
`SELECT` queries and never writes to it. Postgres is supported.

- **Use a read-only user.** Create one that can only `SELECT` from the tables
  Predictabl should see.
- **Let Predictabl reach it.** The database must accept connections from the
  internet from Predictabl's server (`app.predictabl.tech`); allow its address
  in your firewall.
- **The password is stored encrypted** on the server, and is never shown in
  progress, errors or the web app.

### Files

CSV, Excel (`.xlsx`, `.xls`) and Parquet files, or a pandas DataFrame, up to
200 MB per call. Files are **uploaded** to Predictabl, and the progress shows
`Uploading`.

### Data you added before

To reuse data connected earlier, in code or in the web app:

```python
for d in pb.datasets():
    print(d.id, d.name, d.table_count)

data = pb.data("<dataset id>")
```

## 2. Plan

A plan is what Predictabl will train: the exact target, the features, and the
columns it excluded and why.

```python
plan = data.plan("Which customers will stop buying in the next 30 days?")
print(plan)
```

For example:

```text
Predicting: 1 if the customer places no order in the 30 days after the cutoff, else 0
Task: binary_classification
Features (28): orders_90d, revenue_90d, days_since_last_order, avg_basket_value, …
Excluded refund_issued_at: dated after the outcome, so it would leak the answer
```

### Ask a good question

- **Name the outcome and the time window:** "stop buying in the next 30 days",
  not "churn".
- **Say who it is about:** "for each store", "for customers active this year".
- **Say what counts:** "a delivery is late if it arrives after the promised date".
- **Forecasts:** "daily sales for each store for the next 6 weeks".

### Review the plan

| | |
|---|---|
| `plan.target` | The outcome in words, as Predictabl defined it |
| `plan.task` | `binary_classification`, `multiclass` or `regression` |
| `plan.features` | The features it will use |
| `plan.excluded` | Columns left out, each with a reason |
| `plan.spec` | The full plan, including the SQL that builds the training data |

Check the exclusions most carefully. A column that is only known *after* the
outcome (a refund date, a cancellation reason) would make the model look great
in testing and useless in production. Predictabl excludes those; make sure it
caught all of them.

### Change it in plain words

```python
plan = plan.refine("Don't use the support_tier column")
plan = plan.refine("Only include customers with at least two past orders")
```

Each refinement returns a new version; the old one is unchanged.

## 3. Train

```python
model = plan.train()
```

`train()` builds the training data from the plan, trains, tests the model on
data it did not learn from, then retrains on everything for the final model.
For a quick sanity check on a sample first:

```python
preview = plan.train(preset="fast_preview")   # about 15 seconds
```

Training runs on Predictabl's servers. Closing your script does not stop it;
`model.wait()` picks it up again, and `model.cancel()` stops it.

### Progress

Each step is printed as it happens (on one updating line in a terminal, one line
per step in notebooks and logs). To silence it or handle it yourself:

```python
model = plan.train(quiet=True)

def show(update):          # update.step, update.status, update.detail
    print(update.step, update.status, update.detail)

model = plan.train(on_progress=show)
```

### If something fails

A failed step raises `predictabl.BuildFailed` with the reason and, when the server
has them, suggested fixes:

```python
try:
    model = plan.train()
except pb.BuildFailed as e:
    print(e.code, e.message, e.suggestions)
```

## Retrain later

To train a plan again, for example with newer data, without planning again:

```python
plan = pb.plan("<question id>")    # the id is in the web app address of the question
model = plan.train()
```

## Credits and limits

Planning a new question and changing a plan use credits on Predictabl's AI key;
training and retraining never do. With your own OpenAI or Anthropic key
(**Settings → AI provider**), building uses no credits. Check what is left:

```python
pb.account()["credits"]
```

See [Errors and limits](https://predictabl.tech/docs/errors-and-limits/).
