# Train/Test Split with Stratification

Class-stratified train/validation/test split or stratified k-fold for CSV/JSON datasets — seeded, reproducible, with distribution reports, leakage checks, SMOTE preview and CSV export.

> Canonical page: https://elysiatools.com/en/tools/train-test-split-with-stratification

- **Category:** Data Analysis

- **Keywords:** stratified split, train validation test, k-fold cross validation, smote, class distribution, reproducible seed

## Overview

Implements sklearn-style semantics in pure TypeScript: per-class seeded shuffle (mulberry32 + Fisher–Yates) with largest-remainder allocation across splits (or StratifiedKFold round-robin for k-fold), per-split class-share tables with deviation bars, cross-split duplicate-leakage checks, rare-class guards (classes with fewer than 2 members cannot stratify — sklearn raises the same error; k > smallest class is rejected like sklearn's n_splits error), and a SMOTE preview (Chawla et al. 2002: x_new = x_i + λ·(x_neighbor − x_i) with one λ per synthetic sample, over the 5 nearest minority neighbors, numeric columns only) applied to the training split only. Exports train/validation/test (or per-fold) CSVs plus a split_report.json manifest in a ZIP.

## Inputs

- **Dataset file (CSV or JSON)** (file): CSV with a header row, or a JSON array of objects
- **Or paste CSV (with header)** (textarea): age,income,label 23,42000,A 41,71000,B …
- **Target column (class label)** (text): label
- **Split mode** (select)
- **Training percent** (number)
- **Validation percent** (number)
- **Number of folds (k)** (number)
- **Random seed** (number)
- **Stratify by target column** (checkbox)
- **Shuffle rows before splitting** (checkbox)
- **SMOTE oversampling preview (train split)** (checkbox)
- **Export split CSVs as ZIP** (checkbox)

## When to use

- When preparing imbalanced classification datasets where random splitting might underrepresent or omit minority classes in validation or test subsets.
- When setting up reproducible, seeded k-fold cross-validation folds that require proportional class representations across every fold.
- When auditing dataset splits for data leakage, cross-split duplicate rows, and class-share distribution deviations before model training.

## How it works

- Upload a CSV or JSON file (or paste raw CSV text) and specify the target column name containing your class labels.
- Choose between a standard train/validation/test percentage split or stratified k-fold cross-validation, then configure your random seed, shuffle options, and split ratios.
- The tool performs seeded Mulberry32 shuffling per class, calculates largest-remainder or round-robin allocations, checks for rare-class constraints, and screens for duplicate row leakage.
- Review the interactive class distribution reports with deviation bars, inspect the optional SMOTE training oversampling preview, and download the split CSV files with a summary manifest in a ZIP archive.

## Use cases

- Machine learning engineers partitioning tabular churn or fraud data into stratified 70/15/15 train, validation, and test splits.
- Data scientists generating 5-fold or 10-fold cross-validation datasets with preserved class balance and zero duplicate row leakage.
- Researchers balancing imbalanced classification benchmarks using training-split SMOTE oversampling previews and distribution reports.

## Frequently asked questions

### How does stratified splitting handle imbalanced class labels?

It groups rows by the target column, shuffles each class independently using the random seed, and distributes members across splits using largest-remainder allocation so each split matches the original class distribution.

### What is the difference between standard split and k-fold cross-validation mode?

Standard split divides data into fixed train, validation, and test sets based on percentage ratios, whereas k-fold splits data into k non-overlapping validation folds with round-robin stratified assignment.

### How does the SMOTE preview work?

SMOTE creates synthetic samples exclusively for minority classes in the training split by interpolating between nearest minority neighbors across numeric feature columns.

### What happens if a class has fewer samples than the number of splits or folds?

Classes with fewer than two samples trigger rare-class guards, and requesting more folds (k) than the sample count of the smallest class is rejected to prevent invalid cross-validation partitions.

### What files are included in the downloaded ZIP archive?

The ZIP export contains partitioned CSV files (e.g., train.csv, validation.csv, test.csv, or fold-specific CSVs) along with a split_report.json manifest detailing distribution stats and configurations.

## Related tools

- [Time Series Forecast & Seasonality Analyzer](https://elysiatools.com/en/tools/time-series-forecast-seasonality-analyzer): Forecast future periods from CSV or JSON time-series data and inspect trend, seasonal, and residual decomposition in one report
- [CSV to Database Migration Planner](https://elysiatools.com/en/tools/csv-to-database-migration-planner): Infer a relational schema from CSV data and generate create-table plus ALTER migration plans for PostgreSQL, MySQL, SQLite, or SQL Server
- [CSV/JSON Data Watermarker](https://elysiatools.com/en/tools/csv-json-data-watermarker): Inject visible or signature-style watermark fields into CSV or JSON exports so shared datasets can be traced later
- [Dataset Imbalance Detector & Resampler](https://elysiatools.com/en/tools/dataset-imbalance-detector-resampler): Detect class imbalance in CSV or JSON datasets, compare resampling strategies, and preview a balanced output dataset
- [Dataset Quality Profiler](https://elysiatools.com/en/tools/dataset-quality-profiler): Profile CSV or JSON datasets for missing values, duplicate rows, format drift, type inference, and numeric outliers
- [Fitness Workout PDF Generator](https://elysiatools.com/en/tools/fitness-workout-pdf-generator): Generate a printable workout-plan PDF from JSON or CSV data with exercise tables, progress boxes, and optional QR video links
- [JSON-LD Generator from CSV](https://elysiatools.com/en/tools/json-ld-generator-from-csv): Turn CSV or Excel rows into Schema.org JSON-LD for articles, products, or events, with validation-ready output for SEO workflows
- [Podcast Chapter Marker Builder](https://elysiatools.com/en/tools/podcast-chapter-marker-builder): Build every podcast chapter format from one timecoded list: Podcasting 2.0 JSON + RSS tag, ID3v2.4 CHAP+CTOC burned into an MP3, Vorbis comments, mp4chaps, YouTube timestamps and SRT, with a per-player support matrix.

## Samples

- [CSV Samples](https://elysiatools.com/en/samples/csv-samples): Sample CSV files with various data types, sizes, and complexity levels
- [Python Samples](https://elysiatools.com/en/samples/python): Essential Python code examples and Hello World demonstrations
- [WebRTC Real-Time Communication Samples](https://elysiatools.com/en/samples/webrtc-samples): Comprehensive WebRTC samples for peer-to-peer audio/video communication, data channels, screen sharing, and signaling server implementation
- [Distributed Tracing Samples](https://elysiatools.com/en/samples/distributed-tracing-samples): Comprehensive distributed tracing examples using Jaeger, OpenTelemetry, and other modern observability tools for microservices architecture

## Related content

- [JSON Interchange and Format Translation Tools](https://elysiatools.com/en/hubs/json-convert): Compare JSON conversion tools for CSV, YAML, TOML, GraphQL, XML, Markdown, Excel, BSON, EDN, and related structured formats in one hub.
- [Text Case, Encoding, and Normalization Conversion Tools](https://elysiatools.com/en/hubs/text-convert): Compare text case conversion, character-width conversion, encoding conversion, quoted-printable handling, and inline text normalization tools in one hub.
- [CSV Export and Table Conversion Tools](https://elysiatools.com/en/hubs/csv-convert): Compare CSV to Excel, JSON, HTML, Markdown, XML, and text conversion tools in one hub for tabular export and interchange workflows.
- [JSON Inspection, Diff, and Transformation Tools](https://elysiatools.com/en/hubs/json-utility): Compare JSON formatting, diffing, path inspection, schema validation, merging, transformation, and export tools in one hub for API and data workflows.
