Skip to content

Latest commit

 

History

History
243 lines (190 loc) · 6.87 KB

File metadata and controls

243 lines (190 loc) · 6.87 KB

Type Validation System for randomForest.default.R

Overview

The enhanced randomForest.default.R file now includes a comprehensive type validation system that checks parameter types early in the function execution. This helps catch errors immediately with clear, actionable error messages instead of failing later with cryptic C-level errors.

Architecture

Validation Functions

Two helper functions handle parameter validation:

1. .validate_bool(value, param_name)

Validates that a parameter is a single TRUE or FALSE value.

Usage:

.validate_bool(replace, "replace")
.validate_bool(importance, "importance")

What it checks:

  • Parameter must be logical type (not numeric, not character)
  • Parameter must be exactly one value (not a vector)
  • Parameter must not be NA

Error message example:

`replace` must be TRUE or FALSE, not the value 1.

2. .validate_whole_number(value, param_name, min_value = NA, max_value = NA)

Validates that a parameter is a whole number with optional range checking.

Usage:

.validate_whole_number(ntree, "ntree", min_value = 1)
.validate_whole_number(maxnodes, "maxnodes", min_value = 1)

What it checks:

  • Parameter must be numeric type
  • Parameter must be exactly one value (not a vector)
  • Parameter must not be NA
  • Parameter must be a whole number (no decimal part, e.g., 5.0 is OK, 5.5 is not)
  • If min_value specified: parameter must be >= min_value
  • If max_value specified: parameter must be <= max_value

Error message examples:

`ntree` must be a whole number, not a vector of length 3.
`nPerm` must be at least 1, not -5.
`nodesize` must be a whole number (no decimal part), not 3.5.

Validated Parameters

Boolean Parameters (7 total)

These parameters are checked to ensure they are TRUE or FALSE:

  • replace - Sampling with/without replacement
  • importance - Compute variable importance
  • localImp - Compute local importance
  • norm.votes - Normalize votes in classification
  • keep.forest - Keep forest in output
  • corr.bias - Correction bias
  • keep.inbag - Keep inbag information

Whole Number Parameters (3 required, 1 optional)

These parameters are checked to be positive whole numbers:

  • ntree - Number of trees to grow (min: 1)
  • nPerm - Number of times to permute features (min: 1)
  • nodesize - Minimum node size (min: 1)
  • maxnodes - Maximum number of terminal nodes (optional, min: 1)

Special Cases

  • do.trace - Can be boolean OR numeric (validation allows both)
  • proximity - Optional parameter, checked only if provided

Validation Flow

When randomForest() is called:

1. Function receives parameters
   ↓
2. Type validation checks run immediately
   ↓
3. If any type check fails → Stop with clear error message
   ↓
4. If all type checks pass → Continue with computation logic
   ↓
5. Further value validation (existing logic) runs
   ↓
6. Model computation proceeds

Benefits

1. Early Failure Detection

Errors are caught before expensive C-level computation begins, saving time.

2. Clear Error Messages

Instead of cryptic C errors like "data length [301] is not a sub-multiple", users see:

`ntree` must be a whole number (no decimal part), not 100.5.

3. Explicit Documentation

The type checks serve as inline documentation of what types each parameter expects.

4. Reduced Debugging Time

Users immediately understand what went wrong and how to fix it.

Examples

Example 1: Valid Call (passes validation)

# All parameters have correct types
rf <- randomForest(x, y,
                   ntree = 500,           # whole number ✓
                   replace = TRUE,        # boolean ✓
                   importance = TRUE)     # boolean ✓
# → Computation proceeds

Example 2: Type Error - Wrong Type

# replace is numeric instead of boolean
rf <- randomForest(x, y, replace = 1)

# ERROR:
# `replace` must be TRUE or FALSE, not the value 1.

Example 3: Type Error - Decimal Instead of Whole Number

# ntree has decimal part
rf <- randomForest(x, y, ntree = 100.5)

# ERROR:
# `ntree` must be a whole number (no decimal part), not 100.5.

Example 4: Type Error - Vector Instead of Scalar

# maxnodes is vector instead of single value
rf <- randomForest(x, y, maxnodes = c(10, 20))

# ERROR:
# `maxnodes` must be a whole number, not a vector of length 2.

Example 5: Type Error - Out of Range

# nPerm must be >= 1
rf <- randomForest(x, y, nPerm = -1)

# ERROR:
# `nPerm` must be at least 1, not -1.

Implementation Details

Validation Functions Location

Lines 4-63 in randomForest.default.R:

  • .validate_bool() definition: lines 13-26
  • .validate_whole_number() definition: lines 28-63

Validation Calls Location

Lines 97-135 in the function body:

  • Boolean parameter checks: lines 103-110
  • Whole number checks: lines 112-115
  • Optional parameter checks: lines 117-134

Commenting Strategy

  • Inline comments explain the validation purpose
  • Section headers clearly mark the validation block
  • Helper functions include roxygen2 documentation

Integration with Existing Code

The validation system:

  • ✓ Runs before any existing logic
  • ✓ Does NOT modify parameter values
  • ✓ Does NOT change function behavior for valid inputs
  • ✓ Complements (not replaces) existing validation logic
  • ✓ Provides better error messages for type errors

Example: Both systems check mtry validity:

# Type validation: Would check if mtry is numeric (if desired)
# Existing validation (lines after type checks): Checks if mtry is in valid range
# Result: Multiple layers of defense against invalid inputs

How to Extend

To add validation for additional parameters:

For Boolean Parameters:

.validate_bool(your_param, "your_param")

For Numeric Whole Number Parameters:

.validate_whole_number(your_param, "your_param", min_value = 1, max_value = 100)

For Custom Validation:

if (!your_condition) {
    stop(sprintf(
        "`%s` must satisfy your_condition, not %s.",
        "param_name",
        what_was_provided
    ), call. = FALSE)
}

Testing

A demonstration script (type_validation_demo.R) shows:

  • Valid parameter examples
  • How each type error is caught
  • The error messages generated
  • Benefits of early validation

Run it with:

Rscript type_validation_demo.R

Summary

The type validation system in randomForest.default.R provides:

  1. Early parameter validation - Catches type errors immediately
  2. Clear error messages - Explains what went wrong in user-friendly language
  3. Minimal overhead - Simple checks before expensive computation
  4. Better documentation - Parameter types are explicit in code
  5. Consistent patterns - Reusable validation functions for similar parameters

This follows best practices from packages like the tidyverse and the rlang package for input validation.