Skip to main content
Open in Kaggle  Open in Colab  Download Notebook
This documentation page is also available as an interactive notebook. You can launch the notebook in Kaggle or Colab, or download it for use with an IDE or local Jupyter installation, by clicking one of the above links.
Create training, validation, and test splits with random or stratified sampling.

Problem

You have a large dataset and need to create subsets for ML training—random samples for quick experiments, stratified samples for balanced classes, or reproducible splits for benchmarking.

Solution

What’s in this recipe:
  • Random sampling with sample(n=...)
  • Percentage-based sampling with sample(fraction=...)
  • Stratified sampling with stratify_by=
You use query.sample() to create random subsets, with optional stratification for balanced class distribution.

Setup

Connected to Pixeltable database at: postgresql+psycopg://postgres:@/pixeltable?host=/Users/pjlb/.pixeltable/pgdata
Created directory ‘sampling_demo’.
<pixeltable.catalog.dir.Dir at 0x1471b08e0>

Create sample dataset

Created table ‘data’.Inserting rows into `data`: 0 rows [00:00, ? rows/s]
Inserting rows into `data`: 10 rows [00:00, 857.13 rows/s]
Inserted 10 rows with 0 errors.
10 rows inserted, 20 values computed.

Random sampling

Stratified sampling

Sampling from filtered data

Persist samples as tables

Created table ‘train’.Inserting rows into `train`: 0 rows [00:00, ? rows/s]
Inserting rows into `train`: 9 rows [00:00, 3080.27 rows/s]
Created table ‘test’.Inserting rows into `test`: 0 rows [00:00, ? rows/s]
Inserting rows into `test`: 3 rows [00:00, 1333.92 rows/s]

Explanation

Sampling methods:
Stratification options:
Tips:
  • Always set seed for reproducible experiments
  • Use stratified sampling for imbalanced datasets
  • Combine with .where() to sample from subsets

See also

Last modified on June 24, 2026