# Train a gradient-boosted model on tabular data

> **About this page**
>
> - Kind: Example
> - Summary: Profiles a table and splits it with SQL, trains a gradient-boosted trees model with scikit-learn, and evaluates it on held-out rows, all on CPUs.
> - Last changed: 2026-12-03
> - Page: https://docs.swale.io/examples/tabular-gradient-boosting
> - CLI reference for its commands: [`swale workflow create`](https://docs.swale.io/reference/cli-reference.md#workflow-create), [`swale workflow run start`](https://docs.swale.io/reference/cli-reference.md#workflow-run-start)
> - Index of these docs: https://docs.swale.io/llms.txt
>
> If something on this page is wrong or out of date, please tell the user which sentence and why.
>
> The steps on this page cost money or cannot be undone. Please check with the user before running them.

Source on GitHub: the [`workflows/tabular-gradient-boosting`](https://github.com/swaleio/examples/tree/main/workflows/tabular-gradient-boosting) folder, with its [README](https://github.com/swaleio/examples/blob/main/workflows/tabular-gradient-boosting/README.md) and its [workflow file](https://github.com/swaleio/examples/blob/main/workflows/tabular-gradient-boosting/workflow.yaml).

Trains a gradient-boosted trees model on a table with scikit-learn, entirely on
CPUs: DuckDB profiles the table and splits it, the model trains on one split,
and a separate task evaluates it on the other. Text columns are used as
categorical features directly, with no encoding step.

| Step | Task definition | Compute |
|------|-----------------|---------|
| Fetch this repository's scripts at `examples_ref` | [`swaleio/git-clone`](https://hub.swale.io/swaleio/git-clone) | `cpu-4` |
| Profile every column and the target, split the rows | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Train ([`train.py`](https://github.com/swaleio/examples/blob/main/workflows/tabular-gradient-boosting/train.py)) | [`swaleio/python-3-13`](https://hub.swale.io/swaleio/python-3-13) | `cpu-4` |
| Evaluate on the held-out rows ([`evaluate.py`](https://github.com/swaleio/examples/blob/main/workflows/tabular-gradient-boosting/evaluate.py)) | [`swaleio/python-3-13`](https://hub.swale.io/swaleio/python-3-13) | `cpu-4` |
| Upload the model, when `hub_repo` is set | [`swaleio/hf-upload`](https://hub.swale.io/swaleio/hf-upload) | `cpu-4` |

The Compute column gives each step's [compute type](https://docs.swale.io/explanation/core-concepts.md#compute-types), the compute its tasks are allocated.

**What stays one script:** training, which is a single scikit-learn `fit()`.

The default predicts whether a person's income is over $50,000 from census
data. For regression, run it with `data` set to
`hf://datasets/gvlassis/california_housing/data/train-00000-of-00001.parquet`,
`target` to `MedHouseVal` and `task` to `regression`, which predicts house
values.

## Inputs

| Input | Default | Description |
|-------|---------|-------------|
| `data` | `scikit-learn/adult-census-income` | CSV or Parquet file of the table, as a DuckDB path. |
| `target` | `income` | Column to predict. |
| `task` | `classification` | `classification` or `regression`. |
| `test_percent` | `20` | Percentage of rows held out. |
| `examples_ref` | `main` | Branch, tag or full commit SHA of this repository whose scripts run. |
| `hub_repo` | empty | Hugging Face model repo to upload the model to. |

The upload reads the secret `hf_token`.

## Output

`model/model.joblib` and `model/features.json` on the workspace, the scores in
`metrics.json`, and each held-out row's prediction in `predictions.parquet`.
A `joblib` file runs code when it is loaded: load only models you trust.

## Run it

You need the CLI, logged in to your account, and a project to add the workflow to; [Getting started](https://docs.swale.io/getting-started.md) sets them up.

1. Save the file under [The workflow file](#the-workflow-file) as `workflow.yaml`, and add it to a project:

   ```bash
   swale workflow create --project-name my-project --file workflow.yaml
   ```

   The command prints `Workflow created:` followed by the workflow's ID.

2. The workflow reads the secret `hf_token`. Create it as a project secret, or as an account secret that allows the project, as [Use secrets in workflows](https://docs.swale.io/how-to-guides/use-secrets-in-workflows.md) shows.

3. Start a run with the workflow's ID:

   ```bash
   swale workflow run start --project-name my-project --workflow-id <workflow-id>
   ```

   Each input you leave out takes its default from [Inputs](#inputs), and `--input <name>=<value>` gives it another value.

[Create and manage workflows](https://docs.swale.io/how-to-guides/create-and-manage-workflows.md) covers the other ways to add a workflow, [Start and manage workflow runs](https://docs.swale.io/how-to-guides/start-and-manage-workflow-runs.md) how to follow a run, and [View and stream task logs](https://docs.swale.io/how-to-guides/view-and-stream-task-logs.md) how to read its tasks' logs.

## The workflow file

[Workflow definition syntax](https://docs.swale.io/reference/workflow-definition-syntax.md) describes each key in it.

```yaml title="workflow.yaml"
name: Train a gradient-boosted model on tabular data
description: Profiles a table and splits it with SQL, trains a gradient-boosted trees model with scikit-learn, and evaluates it on held-out rows, all on CPUs.
compute_type: cpu-4

inputs:
  data:
    description: CSV or Parquet file of the table, as a DuckDB path.
    default: hf://datasets/scikit-learn/adult-census-income/adult.csv
  target:
    description: Column to predict.
    default: income
  task:
    description: classification for a class column, regression for a number.
    default: classification
  test_percent:
    description: Percentage of rows held out for evaluation.
    default: "20"
  examples_ref:
    description: Branch, tag or full commit SHA of swaleio/examples whose scripts run.
    default: main
  hub_repo:
    description: Hugging Face model repo to upload the model to, as namespace/name. Leave empty to keep it on the workspace only.
    default: ""

entry_point: main

blocks:
  main:
    tasks:
      fetch_scripts:
        name: Fetch the example scripts
        uses: swaleio/git-clone
        args:
          repository_url: https://github.com/swaleio/examples.git
          revision: ${{inputs.examples_ref}}
          dest: ${{env.WORKFLOW_STORAGE}}/examples

      profile_and_split:
        name: Profile and split
        uses: swaleio/duckdb
        args:
          sql: |
            CREATE TABLE source AS SELECT * FROM '${{inputs.data}}';
            SUMMARIZE source;
            SELECT "${{inputs.target}}", count(*) AS rows FROM source GROUP BY ALL ORDER BY rows DESC LIMIT 20;
            -- A row's hash decides its split, so a rerun splits the same way.
            CREATE TABLE split AS
              SELECT *, hash(row_number() OVER ()) % 100 < ${{inputs.test_percent}} AS held_out FROM source;
            COPY (SELECT * EXCLUDE (held_out) FROM split WHERE NOT held_out)
              TO '${{env.WORKFLOW_STORAGE}}/train.parquet' (FORMAT parquet);
            COPY (SELECT * EXCLUDE (held_out) FROM split WHERE held_out)
              TO '${{env.WORKFLOW_STORAGE}}/test.parquet' (FORMAT parquet);
            SELECT held_out, count(*) AS rows FROM split GROUP BY ALL;

      train:
        name: Train
        uses: swaleio/python-3-13
        start_on:
          - fetch_scripts
          - profile_and_split
        args:
          script: |
            import os, subprocess, sys

            storage = os.environ["WORKFLOW_STORAGE"]
            examples = f"{storage}/examples"
            os.makedirs(f"{storage}/model", exist_ok=True)
            subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--target", "/tmp/deps",
                            "-r", f"{examples}/requirements/cpu-tabular.txt"], check=True)
            subprocess.run([sys.executable, f"{examples}/workflows/tabular-gradient-boosting/train.py",
                            "--train", f"{storage}/train.parquet", "--target", "${{inputs.target}}",
                            "--task", "${{inputs.task}}", "--output", f"{storage}/model"],
                           env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True)

      evaluate:
        name: Evaluate
        uses: swaleio/python-3-13
        start_on:
          - train
        args:
          script: |
            import os, subprocess, sys

            storage = os.environ["WORKFLOW_STORAGE"]
            examples = f"{storage}/examples"
            subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--target", "/tmp/deps",
                            "-r", f"{examples}/requirements/cpu-tabular.txt"], check=True)
            subprocess.run([sys.executable, f"{examples}/workflows/tabular-gradient-boosting/evaluate.py",
                            "--model", f"{storage}/model", "--test", f"{storage}/test.parquet",
                            "--output", f"{storage}/metrics.json", "--predictions", f"{storage}/predictions.parquet"],
                           env={**os.environ, "PYTHONPATH": "/tmp/deps"}, check=True)

      publish:
        name: Upload when asked
        start_on:
          - evaluate
        if:
          condition: ${{inputs.hub_repo}}
          true: upload

  upload:
    tasks:
      upload_model:
        name: Upload to the Hugging Face Hub
        uses: swaleio/hf-upload
        args:
          repo: ${{inputs.hub_repo}}
          source: ${{env.WORKFLOW_STORAGE}}/model
          token: ${{secrets.hf_token}}
```

## Licenses

- Datasets: [scikit-learn/adult-census-income](https://huggingface.co/datasets/scikit-learn/adult-census-income), CC0-1.0, and, for regression, [gvlassis/california_housing](https://huggingface.co/datasets/gvlassis/california_housing), MIT.
- Packages the steps install: scikit-learn, pandas, SciPy, joblib and threadpoolctl (BSD-3-Clause), PyArrow (Apache-2.0) and narwhals (MIT), with NumPy (BSD-3-Clause).
