> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.ovalbee.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.ovalbee.com/_mcp/server.

# Kfold split

> Split a dataset into K folds and hand one fold at a time to the train and predict nodes wired after it, so every labelled image is predicted by a model that never saw it. After the last fold it saves those held-out predictions as the report Kfold label check reads.

## Overview

Splits a dataset into K folds and hands one fold at a time to the train and predict nodes wired after it, in a loop, so every labelled image is predicted by a model that never saw it. After the last fold it saves those held-out predictions as a report that [Kfold label check](/node-library/nodes/models-clip-kfold-label-check) reads to find labels worth a second look.

It works with any detector whose train node has the inputs Train dataset, Validation dataset, Model and Destination model and whose predict node has Dataset, Destination dataset and Model, such as [Train YOLO](/node-library/nodes/models-yolo-train-yolo) and [Predict YOLO](/node-library/nodes/models-yolo-predict-yolo). Copies of one image always sit in the same fold, so a model is never tested on a copy of an image it trained on.

```mermaid
flowchart LR
  n1["Kfold split"] --> n2["Condition: folds left?"] --> n3["Train"] --> n4["Predict"] --> n1
  n2 -- otherwise --> n5["Kfold label check"]
```

## Prerequisites

| Requirement                   | What you need                                                                                                                                                          |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Detector nodes**            | One train node and one predict node of the same detector family, wired as in the loop below.                                                                           |
| **Condition**                 | A [Condition](/node-library/nodes/flow-control-condition) that checks Done is false, between this node and the train node.                                             |
| **Copies reports** (optional) | Reports of [Find copies](/node-library/nodes/dataset-ops-find-copies) and [Similar pairs](/node-library/nodes/models-clip-similar-pairs), when the dataset has copies. |

## How it works

Checks the wiring of the loop and refuses to run when a held-out image could reach training, naming the node and the setting to change. It also refuses while the train or predict node has a run in progress.

Starts a new K-fold run when there is none, the last one finished and this node itself is started (started by the predict node after a finished run, it returns that run and Done stays yes), or the dataset, folds, validation share, seed or copies reports changed. Otherwise it continues the current run: the fold handed out last counts as done once the predict node has a completed run on it with the model the train node made from that fold.

On a new run, reads every image with its labels and tags, groups copies, and assigns every image of a labelled split to a fold, spreading splits and tag values over the folds. The folds are saved in the report.

Hands out the next fold as new versions of the train, validation and held-out datasets. The validation images come from the training folds, in whole copy groups, so the held-out fold never picks a checkpoint. With the first fold it also copies the train node's starting model into a scratch model, the Fold models output, which the train node files every fold's model under.

After the last fold, reads the held-out predictions dataset and saves every box with its fold, class and score as `oof.parquet` in the report, then sets Done to yes so the Condition ends the loop. The scratch model is deleted with the fold models; the model the train node fine-tunes is never changed.

## Inputs

**`Dataset`** `dataset` — required

Dataset to split, with its labels. Every image of a split that holds at least one object is held out by exactly one fold, an image's split tag only keeps the folds balanced. The dataset is read when a run starts, so images added later join the next run. Key: `SRC_DATASET`.

---

**`Copies reports`** `report`

Reports of Find copies and Similar pairs. Images they put in one group stay in the same fold, so a model is never tested on a copy of an image it trained on. Leave empty to group by nothing, which makes the held-out predictions look better than they are when the dataset has copies. Values come from `SRC_DATASET`. Key: `COPY_REPORT_IDS`.

---

**`Folds`** `integer` — required, default: 4

Number of folds. Each model trains on the other K-1 folds, so a larger K gives models closer to one trained on everything, at the cost of K trainings. Minimum: `3`. Maximum: `10`. Step: `1`. Key: `K`.

---

**`Validation share (%)`** `integer` — required, default: 10

Share of each fold's training images set aside as its validation dataset, taken from the K-1 training folds in whole copy groups. The held-out fold is never the validation dataset, so it cannot influence which checkpoint a train node keeps. Minimum: `1`. Maximum: `50`. Step: `1`. Key: `VAL_SHARE`.

---

**`Max training images`** `integer`

Most images each fold's model trains on, empty or 0 means no limit. It bounds training time on big datasets. The training images are drawn from the K-1 training folds in whole copy groups, keeping the split shares, and the draw depends on the seed. Images left out of training are not wasted - every image is still predicted by a model that did not see it. The held-out fold is never cut, and the validation share is taken of this number, so validation stays small too. Minimum: `0`. Maximum: `100000000`. Step: `1`. Key: `MAX_TRAIN_IMAGES`.

---

**`Seed`** `integer` — required, default: 0

Seed of the fold assignment, of the validation pick and of the training cap. The same dataset, settings and seed give the same folds. Change it to start a new run with the same settings. Minimum: `0`. Maximum: `1000000`. Step: `1`. Key: `SEED`.

---

## Outputs

**`Train dataset`** `dataset`

Training images of the current fold - the other K-1 folds without the validation share - with their labels. Wire it into the Train dataset of the train node. Key: `TRAIN_DATASET`.

---

**`Validation dataset`** `dataset`

Validation images of the current fold, taken from the training folds. Wire it into the Validation dataset of the train node. Key: `VAL_DATASET`.

---

**`Held-out dataset`** `dataset`

Images of the current fold, which its model never trains or validates on. Wire it into the Dataset of the predict node. Key: `HOLDOUT_DATASET`.

---

**`Held-out predictions`** `dataset`

Dataset every fold's predict node writes into, so after the last fold every image holds the prediction of the model that never saw it. Wire it into the Destination dataset of the predict node. Shown as an artifact. Key: `OOF_DATASET`.

---

**`Fold models`** `model`

Model the train node registers each fold's model under, instead of the model it fine-tunes. It is created with the run, starts with a copy of the train node's starting version, and is deleted with all fold models once the held-out predictions are saved. Wire it into the Destination model of the train node. Key: `FOLD_MODEL`.

---

**`Report`** `report`

The folds of every image (folds.parquet), kfold_meta.json and progress from the first fold on, and after the last fold the held-out predictions (oof.parquet) that Kfold label check reads. Shown as an artifact. Key: `REPORT_ID`.

---

**`Fold`** `string`

The fold handed to the train node, for example "Fold 2 of 4", or "4 of 4 folds done". Shown on the node as a badge. Key: `FOLD`.

---

**`Done`** `string`

`no` while folds remain, `yes` after the last one. Wire it into the Condition that decides whether the train node runs again. Key: `DONE`.

---

**`Run state`** `object`

Internal state of the current K-fold run. Hidden from the flow editor. Key: `RUN`.

---

## Models and configuration

Wire the loop as in the flow below. The train and predict nodes must run only after the Condition and the train node respectively, which `detach: true` with `after` sets; the node checks this and says what to change.

![The Kfold split loop in the flow editor: Kfold split, Folds left?, Train fold and Predict held-out fold in one column, the back-edge from Predict held-out fold running up the left side to Kfold split, and Kfold label check to the right on the No branch](/_fern-files/_img/b26fedb88d9717d42e0c1c43fb4c6abb9da25ab0ff60e2133fd2bcc9b00e861f.webp)

```yaml
nodes:
  - id: kfold
    use: sample/kfold_split
    name: Kfold split
    after: [predict]
    inputs:
      SRC_DATASET: <dataset>
      K: 3
      VAL_SHARE: 1
  - id: next_fold
    use: flow_control/condition
    name: Folds left?
    inputs:
      ITEM_TO_CHECK: ${kfold.outputs.DONE}
      RULE:
        type: boolean
        rules:
          - id: rule_1
            operator: is_false
            value: null
  - id: train
    use: models/yolo/train_yolo
    name: Train fold
    detach: true
    after: [next_fold]
    inputs:
      TRAIN_DATASET: ${kfold.outputs.TRAIN_DATASET}
      VAL_DATASET: ${kfold.outputs.VAL_DATASET}
      MODEL: YOLO26s@pre-trained
      DESTINATION_MODEL: ${kfold.outputs.FOLD_MODEL}
      ESTIMATE_DATA_USEFULNESS: false
      CONFIG: |
        epochs: 12
        imgsz: 1024
        batch: 4
        patience: 20
        workers: 8
        plots: false
        save: true
        val: true
  - id: predict
    use: models/yolo/predict_yolo
    name: Predict held-out fold
    detach: true
    after: [train]
    inputs:
      DATASET: ${kfold.outputs.HOLDOUT_DATASET}
      DST_DATASET: ${kfold.outputs.OOF_DATASET}
      MODEL: ${train.outputs.MODEL}
      CONFIG: |
        batch: 4
        imgsz: 1024
        conf: 0.01
        iou: 0.7
        max_det: 300
        verbose: false
  - id: label_check
    use: models/clip/kfold_label_check
    name: Kfold label check
    detach: true
    otherwise: [next_fold]
    inputs:
      DATASET: ${kfold.inputs.SRC_DATASET}
      KFOLD_REPORT: ${kfold.outputs.REPORT_ID}
```

### Recommended settings

These settings were chosen on a dense dataset (8,629 images, 457,000 boxes, 10 classes) by checking how many deliberately damaged labels the held-out predictions bring to the top of the Kfold label check lists, and for a run that fits a 12 GB GPU.

| Setting            | Value                                                 | Why                                                                                                                                                                                                                                                                                |
| ------------------ | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Detector           | [YOLO26s](/node-library/nodes/models-yolo-train-yolo) | About twice as fast per fold as RF-DETR Small and fits a 12 GB GPU at batch 4 and 1024 px.                                                                                                                                                                                         |
| Folds              | 3                                                     | Three trainings instead of four.                                                                                                                                                                                                                                                   |
| Epochs             | 12                                                    | A short training found about the same share of damaged labels as one trained until early stopping, in a fraction of the time.                                                                                                                                                      |
| Image size         | 1024                                                  | The train and predict nodes use the same size. Photos of several thousand pixels shrink small defects below what the detector sees: on Insulator-Defect Detection (3,000-6,000 px wide) 640 leaves a quarter of the objects under 16 px on their shorter side, 1024 under a tenth. |
| Batch size         | 4                                                     | At 896 and batch 6 on a dense dataset it peaked at about 6 GB allocated and 11 GB reserved of a 12 GB GPU; 1024 takes batch 4 to stay within it.                                                                                                                                   |
| Validation share   | 1%                                                    | With a fixed number of epochs the validation dataset only picks the checkpoint, and the last one is usually as good; a small share leaves more images for training.                                                                                                                |
| Predict confidence | 0.01                                                  | Missing labels are found from low-scoring boxes.                                                                                                                                                                                                                                   |

[Train RF-DETR](/node-library/nodes/models-rfdetr-train-rf-detr) with RF-DETR Small brings more wrong-class and spurious-box findings to the top of the lists and keeps a shorter "Box badly placed" list, at about twice the training time. At 896 use batch 4 to stay within 12 GB. Replace the train and predict nodes with:

```yaml
  - id: train
    use: models/rfdetr/train_rf_detr
    name: Train fold
    detach: true
    after: [next_fold]
    inputs:
      TRAIN_DATASET: ${kfold.outputs.TRAIN_DATASET}
      VAL_DATASET: ${kfold.outputs.VAL_DATASET}
      MODEL: RF-DETR Small@pre-trained
      DESTINATION_MODEL: ${kfold.outputs.FOLD_MODEL}
      ESTIMATE_DATA_USEFULNESS: false
      CONFIG: |
        epochs: 12
        batch_size: 6
        grad_accum_steps: 3
        resolution: 640
        lr: 0.0001
        lr_encoder: 0.00015
        weight_decay: 0.0001
        early_stopping: true
        early_stopping_patience: 20
        max_dets: 300
        num_workers: 8
  - id: predict
    use: models/rfdetr/predict_rf_detr
    name: Predict held-out fold
    detach: true
    after: [train]
    inputs:
      DATASET: ${kfold.outputs.HOLDOUT_DATASET}
      DST_DATASET: ${kfold.outputs.OOF_DATASET}
      MODEL: ${train.outputs.MODEL}
      CONFIG: |
        conf_threshold: 0.01
        batch_size: 4
```

Any detector family can replace the YOLO pair. The train node must start every fold from the same weights. Any pick works, Latest included: the version it names at the first fold is recorded, and a later fold refuses to start if it names another. Its Destination model must be this node's Fold models output, so the fold models land in a scratch model that is deleted after the last fold, not in the model you fine-tune. Set the predict node's confidence threshold low, 0.01, because Kfold label check finds missing labels from low-scoring boxes.

The Condition is [Condition](/node-library/nodes/flow-control-condition) with the check set to a yes/no value that is false.

## Limitations and troubleshooting

#### What does the node check before it hands out a fold?

* One train node reads this node's Train dataset, and its Validation dataset is this node's Validation dataset.
* One predict node reads the Held-out dataset, writes into the Held-out predictions dataset, uses the model of that train node, runs after the train node only, and leads back to this node.
* A Condition after this node checks Done is false, and the train node runs after it only.
* The train node starts every fold from the same weights, from a model you picked, and its Destination model is this node's Fold models output.

#### A fold failed. How do I continue?

Run the train node or this node again with the same settings; when only the predict node failed, run the predict node again. The loop continues with the same fold; the folds already predicted are kept. A prediction counts only when its model was trained on the fold's training images: predicting after the fold's training failed uses the previous fold's model, so this node hands the same fold out again. To start over with unchanged settings, change the Seed.

#### Can I run the train or predict node again after the run finished?

Yes. Started on their own they lead back to this node, which returns the finished run (Done is yes) and the Condition takes its `otherwise` branch, so Kfold label check runs again on the same report. Starting this node itself, or a node before it that makes its dataset, begins a new K-fold run.

#### What happens when I change a setting during a run?

Changing the dataset, folds, validation share, seed or copies reports starts a new run. The unfinished run is left as it is.

#### Why does the dataset need images in a labelled split?

A split with no object at all is left out, and an image of a split that has objects is held out by exactly one fold. Videos are not folded.

#### Why is there one dataset per fold version?

The train, validation and held-out datasets are hidden helpers that get a new version for every fold. Only the latest version is referenced; the report holds the plan that rebuilds the others.

## JSON config

Machine-readable node interface for automation and advanced usage.

#### Show JSON

```json
{
  "name": "Kfold split",
  "description": "Split a dataset into K folds and hand one fold at a time to the train and predict nodes wired after it, so every labelled image is predicted by a model that never saw it. After the last fold it saves those held-out predictions as the report Kfold label check reads.",
  "category": "Sample",
  "namespace": "ovalbee",
  "templateKey": "sample/kfold_split",
  "version": "v1",
  "inputs": [
    {
      "key": "SRC_DATASET",
      "label": "Dataset",
      "type": "dataset",
      "description": "Dataset to split, with its labels. Every image of a split that holds at least one object is held out by exactly one fold; an image's split tag only keeps the folds balanced. The dataset is read when a run starts, so images added later join the next run.",
      "required": true,
      "default": null,
      "visibleWhen": null,
      "options": {
        "creatable": false
      }
    },
    {
      "key": "COPY_REPORT_IDS",
      "label": "Copies reports",
      "type": "report",
      "kind": "dataset_intelligence_findings_v1",
      "description": "Reports of Find copies and Similar pairs. Images they put in one group stay in the same fold, so a model is never tested on a copy of an image it trained on. Leave empty to group by nothing, which makes the held-out predictions look better than they are when the dataset has copies.",
      "required": false,
      "default": null,
      "visibleWhen": null,
      "options": {
        "minItems": 0,
        "ref": "SRC_DATASET"
      }
    },
    {
      "key": "K",
      "label": "Folds",
      "type": "number",
      "description": "Number of folds. Each model trains on the other K-1 folds, so a larger K gives models closer to one trained on everything, at the cost of K trainings.",
      "required": true,
      "default": 4,
      "visibleWhen": null,
      "options": {
        "type": "integer",
        "min": 3,
        "max": 10,
        "step": 1,
        "slider": false
      }
    },
    {
      "key": "VAL_SHARE",
      "label": "Validation share (%)",
      "type": "number",
      "description": "Share of each fold's training images set aside as its validation dataset, taken from the K-1 training folds in whole copy groups. The held-out fold is never the validation dataset, so it cannot influence which checkpoint a train node keeps.",
      "required": true,
      "default": 10,
      "visibleWhen": null,
      "options": {
        "type": "integer",
        "min": 1,
        "max": 50,
        "step": 1,
        "slider": false
      }
    },
    {
      "key": "MAX_TRAIN_IMAGES",
      "label": "Max training images",
      "type": "number",
      "description": "Most images each fold's model trains on; empty or 0 means no limit. It bounds training time on big datasets. The training images are drawn from the K-1 training folds in whole copy groups, keeping the split shares, and the draw depends on the seed. Images left out of training are not wasted - every image is still predicted by a model that did not see it. The held-out fold is never cut, and the validation share is taken of this number, so validation stays small too.",
      "required": false,
      "default": null,
      "visibleWhen": null,
      "options": {
        "type": "integer",
        "min": 0,
        "max": 100000000,
        "step": 1,
        "slider": false
      }
    },
    {
      "key": "SEED",
      "label": "Seed",
      "type": "number",
      "description": "Seed of the fold assignment, of the validation pick and of the training cap. The same dataset, settings and seed give the same folds. Change it to start a new run with the same settings.",
      "required": true,
      "default": 0,
      "visibleWhen": null,
      "options": {
        "type": "integer",
        "min": 0,
        "max": 1000000,
        "step": 1,
        "slider": false
      }
    }
  ],
  "outputs": [
    {
      "key": "TRAIN_DATASET",
      "label": "Train dataset",
      "type": "dataset",
      "description": "Training images of the current fold - the other K-1 folds without the validation share - with their labels. Wire it into the Train dataset of the train node.",
      "artifact": false,
      "badge": false,
      "badgeOpens": null,
      "hidden": false
    },
    {
      "key": "VAL_DATASET",
      "label": "Validation dataset",
      "type": "dataset",
      "description": "Validation images of the current fold, taken from the training folds. Wire it into the Validation dataset of the train node.",
      "artifact": false,
      "badge": false,
      "badgeOpens": null,
      "hidden": false
    },
    {
      "key": "HOLDOUT_DATASET",
      "label": "Held-out dataset",
      "type": "dataset",
      "description": "Images of the current fold, which its model never trains or validates on. Wire it into the Dataset of the predict node.",
      "artifact": false,
      "badge": false,
      "badgeOpens": null,
      "hidden": false
    },
    {
      "key": "OOF_DATASET",
      "label": "Held-out predictions",
      "type": "dataset",
      "description": "Dataset every fold's predict node writes into, so after the last fold every image holds the prediction of the model that never saw it. Wire it into the Destination dataset of the predict node.",
      "artifact": true,
      "badge": false,
      "badgeOpens": null,
      "hidden": false
    },
    {
      "key": "FOLD_MODEL",
      "label": "Fold models",
      "type": "model",
      "description": "Model the train node registers each fold's model under, instead of the model it fine-tunes. It is created with the run, starts with a copy of the train node's starting version, and is deleted with all fold models once the held-out predictions are saved. Wire it into the Destination model of the train node.",
      "artifact": false,
      "badge": false,
      "badgeOpens": null,
      "hidden": false
    },
    {
      "key": "REPORT_ID",
      "label": "Report",
      "type": "report",
      "kind": [
        "kfold_oof_v1"
      ],
      "description": "The folds of every image (folds.parquet), kfold_meta.json and progress from the first fold on, and after the last fold the held-out predictions (oof.parquet) that Kfold label check reads.",
      "artifact": true,
      "badge": false,
      "badgeOpens": null,
      "hidden": false
    },
    {
      "key": "FOLD",
      "label": "Fold",
      "type": "string",
      "description": "The fold handed to the train node, for example \"Fold 2 of 4\", or \"4 of 4 folds done\".",
      "artifact": false,
      "badge": true,
      "badgeOpens": null,
      "hidden": false
    },
    {
      "key": "DONE",
      "label": "Done",
      "type": "string",
      "description": "`no` while folds remain, `yes` after the last one. Wire it into the Condition that decides whether the train node runs again.",
      "artifact": false,
      "badge": false,
      "badgeOpens": null,
      "hidden": false
    },
    {
      "key": "RUN",
      "label": "Run state",
      "type": "object",
      "description": "Internal state of the current K-fold run.",
      "artifact": false,
      "badge": false,
      "badgeOpens": null,
      "hidden": true
    }
  ],
  "automation": {
    "requires_configuration": true,
    "discard_history": "never"
  },
  "widgets": {
    "secondaryWidget": {
      "id": "report-preview",
      "settings": {
        "reportAsset": {
          "type": "variable",
          "value": "self.outputs.REPORT_ID"
        },
        "name": {
          "type": "input",
          "value": "Open report"
        }
      }
    }
  }
}
```