#!/usr/bin/env python3
"""
Synthetic Dataset Generator
============================
A flexible Python script to generate synthetic tabular datasets for testing
data pipelines, ML models, or analytics tools. Supports numerical, categorical,
datetime, and text features with optional missing values, outliers, and correlations.
Usage:
python synthetic_dataset.py --rows 10000 --cols 20 --output test_data.csv --seed 42 --missing-prob 0.05 --outlier-prob 0.02
Key Features:
- Mixed data types (numerical, categorical, datetime, text).
- Configurable noise, missing values, outliers.
- Reproducible via seed.
- Outputs to CSV.
Dependencies:
pip install pandas numpy faker scikit-learn
"""
import argparse
import random
from datetime import datetime, timedelta
from typing import List, Dict
import numpy as np
import pandas as pd
from faker import Faker
from sklearn.datasets import make_classification, make_regression
def generate_synthetic_dataset(
num_rows: int,
num_cols: int,
seed: int,
missing_prob: float = 0.05,
outlier_prob: float = 0.02,
include_target: bool = True,
target_type: str = 'classification' # 'classification' or 'regression'
) -> pd.DataFrame:
"""
Generate a synthetic dataset with mixed features and optional target.
Args:
num_rows: Number of rows.
num_cols: Number of feature columns (target is extra if included).
seed: Random seed for reproducibility.
missing_prob: Probability of missing values per cell.
outlier_prob: Probability of outliers in numerical columns.
include_target: Whether to include a target column.
target_type: Type of target ('classification' or 'regression').
Returns:
pd.DataFrame: Synthetic dataset.
"""
np.random.seed(seed)
random.seed(seed)
fake = Faker(seed=seed)
# Decide column types: ~40% numerical, 25% categorical, 20% datetime, 15% text
col_types = ['numerical'] * int(0.4 * num_cols) + \
['categorical'] * int(0.25 * num_cols) + \
['datetime'] * int(0.20 * num_cols) + \
['text'] * (num_cols - int(0.85 * num_cols))
random.shuffle(col_types) # Randomize order
col_types = col_types[:num_cols] # Ensure exact count
data = {}
for i, col_type in enumerate(col_types):
col_name = f'feature_{i+1}'
if col_type == 'numerical':
# Base data: mix of normal and uniform
if np.random.rand() > 0.5:
vals = np.random.normal(50, 15, num_rows)
else:
vals = np.random.uniform(0, 100, num_rows)
# Add correlations (simple linear trend in some cols)
if i % 3 == 0:
trend = np.linspace(0, 10, num_rows)
vals += trend * 2
# Outliers
outlier_mask = np.random.rand(num_rows) < outlier_prob
vals[outlier_mask] *= np.random.choice([5, -5], size=sum(outlier_mask))
data[col_name] = vals
elif col_type == 'categorical':
# 5-10 categories
n_cats = np.random.randint(5, 11)
categories = [f'cat_{j}' for j in range(n_cats)]
data[col_name] = np.random.choice(categories, num_rows)
elif col_type == 'datetime':
start_date = datetime(2020, 1, 1)
data[col_name] = [start_date + timedelta(days=np.random.randint(0, 1825)) for _ in range(num_rows)]
elif col_type == 'text':
text_types = ['name', 'email', 'sentence', 'address']
text_type = np.random.choice(text_types)
data[col_name] = [getattr(fake, text_type)() for _ in range(num_rows)]
df = pd.DataFrame(data)
# Introduce missing values
for col in df.columns:
if col_type != 'datetime': # Avoid missing datetimes for simplicity
mask = np.random.rand(num_rows) < missing_prob
df.loc[mask, col] = np.nan
# Add target column if requested
if include_target:
if target_type == 'classification':
X_temp = df.select_dtypes(include=[np.number]).fillna(0).values
if X_temp.shape[1] == 0:
X_temp = np.random.rand(num_rows, 5)
y, _ = make_classification(n_samples=num_rows, n_features=min(20, X_temp.shape[1]),
n_informative=5, n_redundant=2, n_classes=3, random_state=seed)
df['target'] = y
else: # regression
X_temp = df.select_dtypes(include=[np.number]).fillna(0).values
if X_temp.shape[1] == 0:
X_temp = np.random.rand(num_rows, 5)
y, _ = make_regression(n_samples=num_rows, n_features=min(20, X_temp.shape[1]),
n_informative=5, noise=0.1, random_state=seed)
df['target'] = y
return df
def main():
parser = argparse.ArgumentParser(description='Generate synthetic datasets for testing.')
parser.add_argument('--rows', type=int, default=1000, help='Number of rows (default: 1000)')
parser.add_argument('--cols', type=int, default=10, help='Number of feature columns (default: 10)')
parser.add_argument('--output', default='synthetic_data.csv', help='Output CSV file (default: synthetic_data.csv)')
parser.add_argument('--seed', type=int, default=42, help='Random seed (default: 42)')
parser.add_argument('--missing-prob', type=float, default=0.05, help='Missing value probability (default: 0.05)')
parser.add_argument('--outlier-prob', type=float, default=0.02, help='Outlier probability in numerical cols (default: 0.02)')
parser.add_argument('--no-target', action='store_true', help='Exclude target column')
parser.add_argument('--target-type', choices=['classification', 'regression'], default='classification',
help='Target type (default: classification)')
args = parser.parse_args()
print(f"Generating dataset: {args.rows:,} rows, {args.cols} cols, seed={args.seed}")
df = generate_synthetic_dataset(
num_rows=args.rows,
num_cols=args.cols,
seed=args.seed,
missing_prob=args.missing_prob,
outlier_prob=args.outlier_prob,
include_target=not args.no_target,
target_type=args.target_type
)
df.to_csv(args.output, index=False)
print(f"Dataset saved to {args.output}")
print("\nDataset info:")
print(df.info())
print("\nFirst few rows:")
print(df.head())
if __name__ == '__main__':
main()
Quick Start Examples
-
Basic usage (1000 rows, 10 cols, with target):
python synthetic_dataset.py --rows 1000 --output basic_data.csv
-
Large dataset with missing values and outliers:
python synthetic_dataset.py --rows 50000 --cols 25 --missing-prob 0.1 --outlier-prob 0.05 --output large_test.csv
-
Regression dataset, no target:
python synthetic_dataset.py --rows 2000 --target-type regression --no-target --output features_only.csv
-
Reproducible small dataset:
python synthetic_dataset.py --rows 100 --cols 5 --seed 123 --output reproducible.csv
This script produces realistic, varied datasets perfect for unit tests, integration tests, or benchmarking. Customize via CLI args! 🚀