DecisionTree / Classifier Layer
Decision Tree Classification - A versatile tree-based learning algorithm: The goal is to create a model that predicts the value of a target variable by learning simple decision rules inferred from the data features.
Mathematical form: Tree T partitions feature space X into regions R_j: where:
- c_j is the prediction for region R_j
- I() is the indicator function
Key characteristics:
- Non-parametric modeling
- Hierarchical decisions
- Automatic feature selection
- Handles non-linear patterns
- Interpretable results
Common applications:
- Medical diagnosis
- Risk assessment
- Customer segmentation
- Fault detection
- Species identification
Computational notes:
- Time complexity: O(n_samples * n_features * depth)
- Space complexity: O(n_nodes)
- Scales well with data size
- No feature scaling needed
Outputs:
- Predicted Table: Input data with predictions
- Validation Results: Cross-validation metrics
- Test Metric: Test set performance
- ROC Curve Data: ROC analysis information
- Confusion Matrix: Classification breakdown
- Feature Importances: Variable importance scores
Note: Consider ensemble methods (RandomForest, XGBoost) for better generalization
SelectFeatures
[column, ...]Feature columns for Decision Tree Classification:
Data requirements:
-
Supported types:
- Numeric (int, float)
- Boolean
- Encoded categoricals
- Binary indicators
-
Preprocessing needs:
- No missing values
- No infinite values
- Encoded categories
- Clean data
-
Scaling properties:
- Scale-invariant (no scaling needed)
- Preserves original units
- Handles varied ranges
- Maintains interpretability
-
Feature considerations:
- Remove redundant features
- Check correlations
- Ensure relevance
- Consider interactions
Note: If empty, uses all numeric columns except target
SelectTarget
columnTarget column for Decision Tree Classification:
Requirements:
-
Data format:
- Categorical labels
- Distinct classes
- No missing values
- Valid encodings
-
Class properties:
- Minimum 2 classes
- Unique labels
- Clear definitions
- Consistent coding
-
Distribution aspects:
- Class balance/imbalance
- Sample sizes per class
- Class importance
- Rare categories
-
Quality checks:
- Label consistency
- Proper encoding
- No duplicates
- Domain validity
Note: Must contain at least two unique classes for classification
Params
oneofDefault configuration for Decision Tree Classification:
Default settings:
-
Split criteria:
- Criterion: Gini impurity
- Splitter: Best split
- Min impurity decrease: 0.0
-
Tree structure:
- Max depth: None (unlimited)
- Max leaf nodes: None
- Max features: All
-
Sample thresholds:
- Min samples split: 2
- Min samples leaf: 1
- Min weight fraction leaf: 0.0
-
Other controls:
- Class weight: None
- CCP alpha: 0.0
- Random state: 98
Best suited for:
- Initial modeling
- Small to medium datasets
- Balanced classes
- Proof of concept
Note: Provides maximum tree growth with no regularization
Fine-tuned configuration for Decision Tree Classification:
Parameter categories:
-
Split quality:
- Splitting criteria
- Feature selection
- Impurity thresholds
-
Tree growth:
- Depth control
- Node constraints
- Leaf restrictions
-
Regularization:
- Sample constraints
- Cost complexity
- Class balancing
-
Randomization:
- Split randomization
- Feature sampling
- Reproducibility
Note: Parameter interactions significantly impact tree structure
Criterion
enumSplit quality measurement criteria:
Purpose:
- Evaluates potential splits
- Guides tree construction
- Measures node purity
- Optimizes classification
Selection impact:
- Tree structure
- Learning bias
- Computational cost
- Model performance
Gini impurity:
Properties:
- Range: [0, 1-1/K]
- Quadratic measure
- Computationally efficient
- Default choice
Best for:
- General classification
- Balanced datasets
- Quick training
- Most applications
Information gain:
Properties:
- Range: [0, log(K)]
- Information theoretic
- More computations
- Slightly different splits
Best for:
- Multi-class problems
- Unbalanced datasets
- When maximizing information
- Theoretical analysis
Logarithmic loss:
Properties:
- Probabilistic measure
- Sensitive to uncertainty
- Penalizes confident mistakes
- Probability-focused
Best for:
- Probability estimation
- Risk-sensitive applications
- When confidence matters
- Calibrated predictions
Splitter
enumThe strategy used to choose the split at each node.
Impact:
- Tree construction speed
- Split optimality
- Model randomization
- Computation time
Trade-offs:
- Speed vs accuracy
- Deterministic vs random
- Memory usage
- Search complexity
Exhaustive best split search:
Properties:
- Evaluates all possible splits
- Optimal local decisions
- Deterministic results
- More computations
Best for:
- Small to medium datasets
- When optimality matters
- Reproducible results
- Default choice
Random split selection:
Properties:
- Evaluates random subset
- Faster computation
- Introduces randomness
- Sub-optimal splits
Best for:
- Large datasets
- Random forest base learners
- When speed matters
- Ensemble methods
MaxDepth
u32The maximum depth of the tree. If 0, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples.
Values:
- 0: Unlimited depth
- >0: Maximum levels from root
Effects:
- Controls model complexity
- Prevents overfitting
- Impacts memory usage
- Affects prediction speed
Guidelines:
- Small (1-3): Simple rules
- Medium (4-10): Balanced models
- Large (>10): Complex patterns
The minimum number of samples required to split an internal node:
Constraint: where N is node samples
Purpose:
- Prevents excessive splitting
- Controls overfitting
- Ensures statistical significance
- Manages leaf size
Typical values:
- 2: Maximum splitting (default)
- 5-10: Moderate regularization
- >20: Strong regularization
The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least min_samples_leaf training samples in each of the left and right branches.
Constraint: where L is leaf samples
Effects:
- Ensures leaf node significance
- Prevents class isolation
- Smooths predictions
- Reduces variance
Guidelines:
- 1: Maximum detail (default)
- 5-10: Balanced smoothing
- >20: Strong smoothing
The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node:
Constraint: where L is leaf samples
Properties:
- Range: [0.0, 0.5]
- Weighted sample control
- Alternative to min_samples_leaf
- Handles imbalanced weights
Use cases:
- Weighted samples
- Cost-sensitive learning
- Imbalanced problems
MaxFeatures
enumFeature subset selection strategy for splits:
Purpose:
- Controls feature randomization
- Manages computational complexity
- Reduces overfitting
- Influences tree diversity
Impact:
- Training speed
- Model variance
- Feature exploration
- Memory usage
Note: Critical parameter for high-dimensional datasets
Uses all available features:
Formula: where F is total features
Properties:
- No feature subsampling
- Deterministic splits
- Complete feature evaluation
- Maximum information use
Best for:
- Low-dimensional data
- Important feature interactions
- When all features matter
- Smaller datasets
Note: Can be computationally intensive for high-dimensional data
Square root of total features:
Formula: where F is total features
Properties:
- Common in Random Forests
- Balanced exploration
- Reduced computation
- Tree decorrelation
Best for:
- Medium to high dimensions
- Ensemble methods
- General classification
- Most applications
Note: Default choice for many tree-based ensembles
Logarithmic scaling of features:
Formula: where F is total features
Properties:
- More aggressive reduction
- Faster computation
- Higher randomization
- Memory efficient
Best for:
- High-dimensional data
- Feature-rich datasets
- Quick training needs
- Memory constraints
Note: Useful for very high-dimensional problems
User-specified feature count:
Properties:
- Full control over feature sampling
- Flexible optimization
- Problem-specific tuning
- Manual optimization
Best for:
- Expert users
- Specific requirements
- Performance optimization
- Research purposes
Note: Requires domain knowledge for optimal setting
MaxFeaturesF
u32Custom feature subset size:
Requirements:
- Value >= 1
- <= total features
Usage:
- Active when max_features=Custom
- Direct control over feature sampling
- Problem-specific optimization
- Manual tuning capability
MaxLeafNodes
u32Maximum number of leaf nodes:
Values:
- 0: Unlimited leaves
- >0: Maximum leaf count
Effects:
- Controls tree size
- Alternative to max_depth
- Affects memory usage
- Impacts model complexity
Trade-offs:
- Model size vs accuracy
- Memory vs precision
- Speed vs detail
A node will be split if this split induces a decrease of the impurity greater than or equal to this value:
Constraint:
where:
- is parent node impurity
- is child node impurity
- is minimum decrease threshold
- is child/parent sample ratio
Purpose:
- Prevents weak splits
- Controls tree growth
- Ensures meaningful splits
- Pre-pruning mechanism
Typical values:
- 0.0: All splits allowed
- 0.0001-0.001: Weak pruning
- >0.01: Strong pruning
ClassWeight
enumClass importance weighting scheme:
Purpose:
- Handles class imbalance
- Adjusts misclassification costs
- Controls class importance
- Influences tree splits
Impact:
- Training bias
- Error penalties
- Decision boundaries
- Model sensitivity
Note: Critical for imbalanced classification tasks
Uniform class weights:
Formula: for all classes
Properties:
- Equal class importance
- No bias adjustment
- Natural class distribution
- Default behavior
Best for:
- Balanced datasets
- Equal error costs
- Standard problems
- When balance isn't critical
Note: May underperform on imbalanced data
Inverse frequency weighting:
Formula:
where:
- is weight for class i
- is total samples
- is number of classes
- is samples in class i
Properties:
- Automatic weight adjustment
- Compensates class imbalance
- Balanced error contribution
- Frequency-based weights
Best for:
- Imbalanced datasets
- Minority class importance
- Skewed distributions
- Fair classification needs
Note: May increase sensitivity to noise in rare classes
RandomState
u64Random number generator seed:
Controls randomization in:
- Feature selection
- Split point selection
- Sample ordering
Importance:
- Reproducibility
- Debugging
- Result validation
- Experimental control
CcpAlpha
f64Cost-Complexity Pruning alpha:
Formula: where:
- R(T): Tree error rate
- |T|: Number of leaves
- α: Complexity parameter
Effects:
- Post-pruning control
- Complexity reduction
- Overfitting prevention
- Size optimization
Values:
- 0.0: No pruning
- >0.0: Increases pruning strength
Hyperparameter optimization for Decision Tree Classification:
Search process:
-
Tree structure:
- Depth and size parameters
- Node constraints
- Leaf configurations
-
Split quality:
- Criteria selection
- Feature sampling
- Threshold optimization
-
Regularization:
- Pruning parameters
- Sample constraints
- Complexity control
Computational impact:
- Time: O(n_params * n_samples * max_depth)
- Memory: O(n_params * n_leaf_nodes)
- Disk: O(n_models)
Best practices:
- Start coarse, refine later
- Consider parameter interactions
- Monitor resource usage
- Use domain knowledge
Criterion
[enum, ...]Split quality measurement criteria:
Purpose:
- Evaluates potential splits
- Guides tree construction
- Measures node purity
- Optimizes classification
Selection impact:
- Tree structure
- Learning bias
- Computational cost
- Model performance
Gini impurity:
Properties:
- Range: [0, 1-1/K]
- Quadratic measure
- Computationally efficient
- Default choice
Best for:
- General classification
- Balanced datasets
- Quick training
- Most applications
Information gain:
Properties:
- Range: [0, log(K)]
- Information theoretic
- More computations
- Slightly different splits
Best for:
- Multi-class problems
- Unbalanced datasets
- When maximizing information
- Theoretical analysis
Logarithmic loss:
Properties:
- Probabilistic measure
- Sensitive to uncertainty
- Penalizes confident mistakes
- Probability-focused
Best for:
- Probability estimation
- Risk-sensitive applications
- When confidence matters
- Calibrated predictions
Splitter
[enum, ...]The strategy used to choose the split at each node.
Impact:
- Tree construction speed
- Split optimality
- Model randomization
- Computation time
Trade-offs:
- Speed vs accuracy
- Deterministic vs random
- Memory usage
- Search complexity
Exhaustive best split search:
Properties:
- Evaluates all possible splits
- Optimal local decisions
- Deterministic results
- More computations
Best for:
- Small to medium datasets
- When optimality matters
- Reproducible results
- Default choice
Random split selection:
Properties:
- Evaluates random subset
- Faster computation
- Introduces randomness
- Sub-optimal splits
Best for:
- Large datasets
- Random forest base learners
- When speed matters
- Ensemble methods
MaxDepth
[u32, ...]Tree depth ranges:
Common patterns:
- Basic: [3, 5, 7, 10]
- Extensive: [3, 5, 7, 10, 15, 20]
- Unlimited: Include [0]
Impact:
- Model complexity
- Memory requirements
- Training time
- Prediction speed
MinSamplesSplit
[u32, ...]Node splitting thresholds:
Search ranges:
- Fine: [2, 5, 10]
- Medium: [2, 5, 10, 20, 50]
- Coarse: [10, 30, 50, 100]
Considerations:
- Sample size
- Noise level
- Overfitting risk
- Statistical significance
MinSamplesLeaf
[u32, ...]Leaf size constraints:
Common ranges:
- Detailed: [1, 2, 4]
- Balanced: [1, 5, 10, 20]
- Smooth: [10, 25, 50]
Effects:
- Prediction stability
- Model variance
- Generalization
- Leaf purity
MinWeightFractionLeaf
[f64, ...]Weighted leaf constraints:
Typical ranges:
- Light: [0.0, 0.01, 0.05]
- Moderate: [0.0, 0.05, 0.1, 0.2]
- Heavy: [0.1, 0.2, 0.3, 0.4]
Applications:
- Weighted samples
- Imbalanced data
- Cost-sensitive learning
- Rare event detection
MaxFeatures
[enum, ...]Feature subset selection strategy for splits:
Purpose:
- Controls feature randomization
- Manages computational complexity
- Reduces overfitting
- Influences tree diversity
Impact:
- Training speed
- Model variance
- Feature exploration
- Memory usage
Note: Critical parameter for high-dimensional datasets
Uses all available features:
Formula: where F is total features
Properties:
- No feature subsampling
- Deterministic splits
- Complete feature evaluation
- Maximum information use
Best for:
- Low-dimensional data
- Important feature interactions
- When all features matter
- Smaller datasets
Note: Can be computationally intensive for high-dimensional data
Square root of total features:
Formula: where F is total features
Properties:
- Common in Random Forests
- Balanced exploration
- Reduced computation
- Tree decorrelation
Best for:
- Medium to high dimensions
- Ensemble methods
- General classification
- Most applications
Note: Default choice for many tree-based ensembles
Logarithmic scaling of features:
Formula: where F is total features
Properties:
- More aggressive reduction
- Faster computation
- Higher randomization
- Memory efficient
Best for:
- High-dimensional data
- Feature-rich datasets
- Quick training needs
- Memory constraints
Note: Useful for very high-dimensional problems
User-specified feature count:
Properties:
- Full control over feature sampling
- Flexible optimization
- Problem-specific tuning
- Manual optimization
Best for:
- Expert users
- Specific requirements
- Performance optimization
- Research purposes
Note: Requires domain knowledge for optimal setting
MaxFeaturesF
[u32, ...]Custom feature counts:
Search patterns:
- Small: [1, 2, 3]
- Medium: [2, 4, 6, 8]
- Large: [5, 10, 15, 20]
Note:
- Only used with max_features=Custom
- Must be <= total features
- Affects computation speed
MaxLeafNodes
[u32, ...]Leaf node constraints:
Search spaces:
- Limited: [10, 20, 50]
- Extended: [20, 50, 100, 200]
- Include unlimited: [0, 50, 100]
Impact:
- Tree size
- Memory usage
- Model complexity
- Training speed
MinImpurityDecrease
[f64, ...]Impurity threshold ranges:
Common values:
- Fine: [0.0, 0.0001, 0.001]
- Medium: [0.0, 0.001, 0.01, 0.1]
- Coarse: [0.01, 0.05, 0.1]
Effects:
- Split quality
- Tree growth
- Pruning level
- Model sparsity
ClassWeight
[enum, ...]Class importance weighting scheme:
Purpose:
- Handles class imbalance
- Adjusts misclassification costs
- Controls class importance
- Influences tree splits
Impact:
- Training bias
- Error penalties
- Decision boundaries
- Model sensitivity
Note: Critical for imbalanced classification tasks
Uniform class weights:
Formula: for all classes
Properties:
- Equal class importance
- No bias adjustment
- Natural class distribution
- Default behavior
Best for:
- Balanced datasets
- Equal error costs
- Standard problems
- When balance isn't critical
Note: May underperform on imbalanced data
Inverse frequency weighting:
Formula:
where:
- is weight for class i
- is total samples
- is number of classes
- is samples in class i
Properties:
- Automatic weight adjustment
- Compensates class imbalance
- Balanced error contribution
- Frequency-based weights
Best for:
- Imbalanced datasets
- Minority class importance
- Skewed distributions
- Fair classification needs
Note: May increase sensitivity to noise in rare classes
RandomState
u64Random seed control:
Ensures:
- Reproducible results
- Consistent splits
- Deterministic search
- Comparable outcomes
Important for:
- Research
- Debugging
- Validation
- Benchmarking
CcpAlpha
[f64, ...]Cost-complexity pruning alphas:
Search ranges:
- Fine: [0.0, 0.001, 0.01]
- Medium: [0.0, 0.01, 0.05, 0.1]
- Aggressive: [0.1, 0.2, 0.3]
Effects:
- Tree size reduction
- Complexity control
- Overfitting prevention
- Model simplification
RefitScore
enumPerformance evaluation metrics for Decision Tree classification:
Purpose:
- Model evaluation
- Cross-validation scoring
- Model selection
- Performance monitoring
Selection criteria:
- Problem objectives
- Class distribution
- Error costs
- Application requirements
Uses model's built-in scoring method:
Properties:
- Accuracy for classification
- Standard evaluation
- Fast computation
- Consistent baseline
Best for:
- Initial evaluation
- Quick assessment
- Standard problems
- Balanced datasets
Standard classification accuracy:
Formula:
Properties:
- Range: [0, 1]
- Intuitive interpretation
- Equal error weights
- Fast computation
Best for:
- Balanced classes
- Equal error costs
- General evaluation
- Simple problems
Class-normalized accuracy score:
Formula:
Properties:
- Range: [0, 1]
- Class-weighted average
- Handles imbalance
- Fairer evaluation
Best for:
- Imbalanced datasets
- Varying class sizes
- Minority class importance
- Fair evaluation needs
Logarithmic loss (Cross-entropy):
Formula:
Properties:
- Range: [0, ∞)
- Probability-sensitive
- Penalizes uncertainty
- Information theoretic
Best for:
- Probability estimation
- Confidence assessment
- Risk-sensitive tasks
- Model calibration
Area Under ROC Curve:
Properties:
- Range: [0, 1]
- Threshold-invariant
- Ranking quality
- Discrimination ability
Best for:
- Binary classification
- Ranking problems
- Threshold optimization
- Model comparison
Note: For multi-class, computes micro-average ROC AUC
Split
oneofStandard train-test split configuration optimized for general classification tasks.
Configuration:
- Test size: 20% (0.2)
- Random seed: 98
- Shuffling: Enabled
- Stratification: Based on target distribution
Advantages:
- Preserves class distribution
- Provides reliable validation
- Suitable for most datasets
Best for:
- Medium to large datasets
- Independent observations
- Initial model evaluation
Splitting uses the ShuffleSplit strategy or StratifiedShuffleSplit strategy depending on the field stratified
. Note: If shuffle is false then stratified must be false.
Configurable train-test split parameters for specialized requirements. Allows fine-tuning of data division strategy for specific use cases or constraints.
Use cases:
- Time series data
- Grouped observations
- Specific train/test ratios
- Custom validation schemes
RandomState
u64Random seed for reproducible splits. Ensures:
- Consistent train/test sets
- Reproducible experiments
- Comparable model evaluations
Same seed guarantees identical splits across runs.
Shuffle
boolData shuffling before splitting. Effects:
- true: Randomizes order, better for i.i.d. data
- false: Maintains order, important for time series
When to disable:
- Time dependent data
- Sequential patterns
- Grouped observations
TrainSize
f64Proportion of data for training. Considerations:
- Larger (e.g., 0.8-0.9): Better model learning
- Smaller (e.g., 0.5-0.7): Better validation
Common splits:
- 0.8: Standard (80/20 split)
- 0.7: More validation emphasis
- 0.9: More training emphasis
Stratified
boolMaintain class distribution in splits. Important when:
- Classes are imbalanced
- Small classes present
- Representative splits needed
Requirements:
- Classification tasks only
- Cannot use with shuffle=false
- Sufficient samples per class
Cv
oneofStandard cross-validation configuration using stratified 3-fold splitting.
Configuration:
- Folds: 3
- Method: StratifiedKFold
- Stratification: Preserves class proportions
Advantages:
- Balanced evaluation
- Reasonable computation time
- Good for medium-sized datasets
Limitations:
- May be insufficient for small datasets
- Higher variance than larger fold counts
- May miss some data patterns
Configurable stratified k-fold cross-validation for specific validation requirements.
Features:
- Adjustable fold count with
NFolds
determining the number of splits. - Stratified sampling
- Preserved class distributions
Use cases:
- Small datasets (more folds)
- Large datasets (fewer folds)
- Detailed model evaluation
- Robust performance estimation
NFolds
u32Number of cross-validation folds. Guidelines:
- 3-5: Large datasets, faster training
- 5-10: Standard choice, good balance
- 10+: Small datasets, thorough evaluation
Trade-offs:
- More folds: Better evaluation, slower training
- Fewer folds: Faster training, higher variance
Must be at least 2.
K-fold cross-validation without stratification. Divides data into k consecutive folds for iterative validation.
Process:
- Splits data into k equal parts
- Each fold serves as validation once
- Remaining k-1 folds form training set
Use cases:
- Regression problems
- Large, balanced datasets
- When stratification unnecessary
- Continuous target variables
Limitations:
- May not preserve class distributions
- Less suitable for imbalanced data
- Can create biased splits with ordered data
NSplits
u32Number of folds for cross-validation. Selection guide: Recommended values:
- 5: Standard choice (default)
- 3: Large datasets/quick evaluation
- 10: Thorough evaluation/smaller datasets
Trade-offs:
- Higher values: More thorough, computationally expensive
- Lower values: Faster, potentially higher variance
Must be at least 2 for valid cross-validation.
RandomState
u64Random seed for fold generation when shuffling. Important for:
- Reproducible results
- Consistent fold assignments
- Benchmark comparisons
- Debugging and validation
Set specific value for reproducibility across runs.
Shuffle
boolWhether to shuffle data before splitting into folds. Effects:
- true: Randomized fold composition (recommended)
- false: Sequential splitting
Enable when:
- Data may have ordering
- Better fold independence needed
Disable for:
- Time series data
- Ordered observations
Stratified K-fold cross-validation maintaining class proportions across folds.
Key features:
- Preserves class distribution in each fold
- Handles imbalanced datasets
- Ensures representative splits
Best for:
- Classification problems
- Imbalanced class distributions
- When class proportions matter
Requirements:
- Classification tasks only
- Sufficient samples per class
- Categorical target variable
NSplits
u32Number of stratified folds. Guidelines: Typical values:
- 5: Standard for most cases
- 3: Quick evaluation/large datasets
- 10: Detailed evaluation/smaller datasets
Considerations:
- Must allow sufficient samples per class per fold
- Balance between stability and computation time
- Consider smallest class size when choosing
RandomState
u64Seed for reproducible stratified splits. Ensures:
- Consistent fold assignments
- Reproducible results
- Comparable experiments
- Systematic validation
Fixed seed guarantees identical stratified splits.
Shuffle
boolData shuffling before stratified splitting. Impact:
- true: Randomizes while maintaining stratification
- false: Maintains data order within strata
Use cases:
- true: Independent observations
- false: Grouped or sequential data
Class proportions maintained regardless of setting.
Random permutation cross-validator with independent sampling.
Characteristics:
- Random sampling for each split
- Independent train/test sets
- More flexible than K-fold
- Can have overlapping test sets
Advantages:
- Control over test size
- Fresh splits each iteration
- Good for large datasets
Limitations:
- Some samples might never be tested
- Others might be tested multiple times
- No guarantee of complete coverage
NSplits
u32Number of random splits to perform. Consider: Common values:
- 5: Standard evaluation
- 10: More thorough assessment
- 3: Quick estimates
Trade-offs:
- More splits: Better estimation, longer runtime
- Fewer splits: Faster, less stable estimates
Balance between computation and stability.
RandomState
u64Random seed for reproducible shuffling. Controls:
- Split randomization
- Sample selection
- Result reproducibility
Important for:
- Debugging
- Comparative studies
- Result verification
TestSize
f64Proportion of samples for test set. Guidelines: Common ratios:
- 0.2: Standard (80/20 split)
- 0.25: More validation emphasis
- 0.1: More training data
Considerations:
- Dataset size
- Model complexity
- Validation requirements
It must be between 0.0 and 1.0.
Stratified random permutation cross-validator combining shuffle-split with stratification.
Features:
- Maintains class proportions
- Random sampling within strata
- Independent splits
- Flexible test size
Ideal for:
- Imbalanced datasets
- Large-scale problems
- When class distributions matter
- Flexible validation schemes
NSplits
u32Number of stratified random splits. Guidelines: Recommended values:
- 5: Standard evaluation
- 10: Detailed analysis
- 3: Quick assessment
Consider:
- Sample size per class
- Computational resources
- Stability requirements
RandomState
u64Seed for reproducible stratified sampling. Ensures:
- Consistent class proportions
- Reproducible splits
- Comparable experiments
Critical for:
- Benchmarking
- Research studies
- Quality assurance
TestSize
f64Fraction of samples for stratified test set. Best practices: Common splits:
- 0.2: Balanced evaluation
- 0.3: More thorough testing
- 0.15: Preserve training size
Consider:
- Minority class size
- Overall dataset size
- Validation objectives
It must be between 0.0 and 1.0.
Time Series cross-validator. Provides train/test indices to split time series data samples that are observed at fixed time intervals, in train/test sets. It is a variation of k-fold which returns first k
folds as train set and the k + 1
th fold as test set. Note that unlike standard cross-validation methods, successive training sets are supersets of those that come before them. Also, it adds all surplus data to the first training partition, which is always used to train the model.
Key features:
- Maintains temporal dependence
- Expanding window approach
- Forward-chaining splits
- No future data leakage
Use cases:
- Sequential data
- Financial forecasting
- Temporal predictions
- Time-dependent patterns
Note: Training sets are supersets of previous iterations.
NSplits
u32Number of temporal splits. Considerations: Typical values:
- 5: Standard forward chaining
- 3: Limited historical data
- 10: Long time series
Impact:
- Affects training window growth
- Determines validation points
- Influences computational load
MaxTrainSize
u64Maximum size of training set. Should be strictly less than the number of samples. Applications:
- 0: Use all available past data
- >0: Rolling window of fixed size
Use cases:
- Limit historical relevance
- Control computational cost
- Handle concept drift
- Memory constraints
TestSize
u64Number of samples in each test set. When 0:
- Auto-calculated as n_samples/(n_splits+1)
- Ensures equal-sized test sets
Considerations:
- Forecast horizon
- Validation requirements
- Available future data
Gap
u64Number of samples to exclude from the end of each train set before the test set.Gap between train and test sets. Uses:
- Avoid data leakage
- Model forecast lag
- Buffer periods
Common scenarios:
- 0: Continuous prediction
- >0: Forward gap for realistic evaluation
- Match business forecasting needs