Metadata-Version: 2.4
Name: hybrid-dt-nn
Version: 0.1.4
Summary: A hybrid decision tree + neural network regressor implemented with scikit-learn and TensorFlow.
Author: Nishith
License-Expression: Apache-2.0
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24.0
Requires-Dist: pandas>=2.0.0
Requires-Dist: scikit-learn>=1.3.0
Requires-Dist: tensorflow>=2.16.1
Requires-Dist: optuna>=3.3.0
Requires-Dist: joblib>=1.3.0
Requires-Dist: h5py>=3.9.0
Provides-Extra: dev
Requires-Dist: pytest>=7.4.0; extra == "dev"
Dynamic: license-file

# Hybrid Region-Based Decision Tree Regressor

A scikit-learn-compatible regression model that combines **Decision Trees** with **region-specific Neural Networks**.

The Decision Tree first partitions the feature space into distinct regions (leaf nodes). A separate Neural Network is then trained for sufficiently populated regions to learn nonlinear relationships within those regions. For regions with insufficient training samples, the Decision Tree prediction is used as a fallback.

---

## Overview

Traditional Decision Tree regressors produce piecewise-constant predictions within their leaf regions. This can limit their ability to model complex nonlinear relationships inside individual regions.

This library uses a hybrid approach:

1. A Decision Tree partitions the feature space into regions.
2. Training samples are assigned to their corresponding leaf.
3. Regions with enough samples receive a dedicated Neural Network.
4. Each Neural Network learns the local nonlinear relationship within its region.
5. During prediction, the input is routed to its Decision Tree leaf.
6. If a Neural Network exists for that leaf, its prediction is returned.
7. Otherwise, the Decision Tree prediction is used.

This allows the model to combine **tree-based partitioning** with **localized nonlinear modeling**.

---

## Model Architecture

```text
                         Training Data
                              │
                              ▼
                   Decision Tree Regressor
                              │
                              ▼
                  Feature-Space Partitioning
                              │
               ┌──────────────┴──────────────┐
               │                             │
       Region has enough samples?            No
               │                             │
              Yes                            ▼
               │                     Decision Tree
               ▼                       prediction
      Train Neural Network
       for this region
               │
               ▼
      Local Nonlinear Model
               │
               └──────────────┐
                              ▼
                       Final Prediction
```

### Prediction

```text
Input
  │
  ▼
Decision Tree
  │
  ▼
Determine Leaf
  │
  ├── Neural Network exists ──► Neural Network Prediction
  │
  └── No Neural Network ──────► Decision Tree Prediction
```

---

## Key Features

- Scikit-learn-compatible estimator API
- Decision Tree-based feature-space partitioning
- Region-specific Neural Networks
- Configurable minimum samples per region
- Decision Tree fallback for small regions
- Optional Optuna-based hyperparameter optimization
- Compatible with common scikit-learn workflows
- Supports `fit()` and `predict()`
- Supports estimator cloning and parameter inspection
- Designed for experimentation with hybrid tree/neural regression

---

## Installation

### From PyPI

```bash
pip install hybrid-dt-nn
```

### From source

```bash
git clone https://github.com/nishith-dubey/Hybrid-Region-Based-Decision-Tree-Regressor.git

cd Hybrid-Region-Based-Decision-Tree-Regressor

pip install -e .
```

---

## Quick Start

```python
from hybrid_dt_nn import HybridTreeRegressor
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score

# Create sample regression data
X, y = make_regression(
    n_samples=1000,
    n_features=10,
    noise=0.1,
    random_state=42
)

# Split data
X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    random_state=42
)

# Create model
model = HybridTreeRegressor(
    dt_max_depth=5,
    dt_min_samples_leaf=50,
    nn_min_samples=50,
    use_hpo=False,
    random_state=42
)

# Train
model.fit(X_train, y_train)

# Predict
predictions = model.predict(X_test)

# Evaluate
print("R²:", r2_score(y_test, predictions))
```

---

## Hyperparameter Optimization

Optuna can optionally be used to optimize the Neural Network configuration for each eligible region.

Enable HPO with:

```python
model = HybridTreeRegressor(
    dt_max_depth=5,
    dt_min_samples_leaf=50,
    nn_min_samples=50,
    use_hpo=True,
    hpo_trials=30,
    random_state=42
)
```

The HPO configuration searches over Neural Network parameters such as:

- Optimizer
- Activation function
- Number of hidden layers
- Number of units

When HPO is disabled, a fixed Neural Network configuration is used.

---

## Important Parameters

| Parameter | Description |
|---|---|
| `dt_max_depth` | Maximum depth of the Decision Tree |
| `dt_min_samples_leaf` | Minimum samples required in a Decision Tree leaf |
| `nn_min_samples` | Minimum samples required to train a Neural Network for a region |
| `use_hpo` | Enables Optuna hyperparameter optimization |
| `hpo_trials` | Number of Optuna trials per eligible region |
| `nn_hidden_layers` | Number of hidden layers when HPO is disabled |
| `nn_units` | Number of neurons per hidden layer |
| `nn_epochs` | Number of Neural Network training epochs |
| `nn_batch_size` | Neural Network batch size |
| `random_state` | Random seed for reproducibility |

Example:

```python
model = HybridTreeRegressor(
    dt_max_depth=3,
    dt_min_samples_leaf=1000,
    nn_min_samples=50,
    use_hpo=True,
    hpo_trials=30,
    random_state=42
)
```

---

## How the Model Works

### Training

Given training data `(X, y)`:

```text
X, y
 │
 ▼
Decision Tree
 │
 ├── Leaf 1 ──► enough samples ──► Neural Network 1
 │
 ├── Leaf 2 ──► insufficient ───► Decision Tree fallback
 │
 ├── Leaf 3 ──► enough samples ──► Neural Network 3
 │
 └── ...
```

Each eligible leaf receives its own Neural Network trained using only the samples belonging to that region.

### Prediction

For a new sample:

```text
New Sample
    │
    ▼
Decision Tree
    │
    ▼
Leaf ID
    │
    ├── NN available ──► NN prediction
    │
    └── NN unavailable ─► DT prediction
```

The final prediction is therefore determined by the region into which the Decision Tree routes the sample.

---

## Why Use a Hybrid Model?

A standard Decision Tree divides the feature space into regions and produces a constant prediction within each leaf.

The hybrid approach keeps the Decision Tree's ability to partition the feature space while allowing Neural Networks to learn more complex relationships within sufficiently populated regions.

Conceptually:

```text
Decision Tree
    │
    └── Defines "where" the sample belongs
                     │
                     ▼
             Neural Network
                     │
                     └── Learns "how" the target behaves
                         within that region
```

This makes the approach particularly useful for experiments where different regions of the feature space may exhibit different nonlinear relationships.

---

## Scikit-learn Compatibility

The estimator follows the standard scikit-learn estimator interface:

```python
model.fit(X, y)
model.predict(X)
model.score(X, y)
```

It is designed to work with standard scikit-learn utilities such as:

```python
from sklearn.base import clone

model_copy = clone(model)
```

and can be used in workflows involving parameter search and pipelines, subject to the computational requirements of Neural Network training.

Example:

```python
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

pipeline = Pipeline([
    ("scaler", StandardScaler()),
    ("model", HybridTreeRegressor())
])

pipeline.fit(X_train, y_train)
predictions = pipeline.predict(X_test)
```

---

## Project Structure

```text
Hybrid-Region-Based-Decision-Tree-Regressor/
│
├── hybrid_dt_nn/
│   ├── __init__.py
│   └── estimator.py
│
├── tests/
│   └── test_package.py
│
├── .github/
│   └── workflows/
│       └── tests.yml
│
├── pyproject.toml
├── requirements.txt
├── README.md
└── LICENSE
```

---

## Requirements

- Python 3.10+
- NumPy
- scikit-learn
- TensorFlow
- Optuna

The exact versions are specified in `requirements.txt`.

---

## Testing

Run the package tests:

```bash
python -m pytest -q
```

Run the package's scikit-learn estimator checks if included in the test suite:

```bash
python -m pytest -v
```

---

## Building the Package

Install the packaging tools:

```bash
python -m pip install build twine
```

Build the source distribution and wheel:

```bash
python -m build
```

Verify the generated distributions:

```bash
python -m twine check dist/*
```

The generated files will be placed in:

```text
dist/
├── hybrid_dt_nn-<version>.tar.gz
└── hybrid_dt_nn-<version>-py3-none-any.whl
```

---

## TestPyPI

Upload a release to TestPyPI:

```bash
python -m twine upload --repository testpypi dist/*
```

Install a specific TestPyPI release:

```bash
pip install \
    --index-url https://test.pypi.org/simple/ \
    --extra-index-url https://pypi.org/simple \
    hybrid-dt-nn==<version>
```

The additional PyPI index is used to obtain dependencies that may not be available on TestPyPI.

---

## PyPI Release

After testing the package on TestPyPI:

```bash
python -m twine upload dist/*
```

Install the published package:

```bash
pip install hybrid-dt-nn
```

---

## Reproducibility

For reproducible experiments, specify a `random_state`:

```python
model = HybridTreeRegressor(
    random_state=42
)
```

Results can still vary slightly across different versions of TensorFlow, NumPy, scikit-learn, hardware, and operating systems.

---

## Limitations

- Training can be significantly more expensive than a standard Decision Tree because a separate Neural Network may be trained for multiple regions.
- Enabling HPO increases training time substantially.
- Very small regions are not suitable for training independent Neural Networks and therefore use the Decision Tree fallback.
- Neural Network training introduces additional computational and dependency requirements compared with a standard scikit-learn Decision Tree.

---

## Research Context

This project explores a region-based hybrid regression approach in which a Decision Tree provides the initial partitioning of the feature space and Neural Networks provide localized nonlinear modeling.

The goal is to investigate whether replacing the constant prediction within sufficiently populated tree regions with learned nonlinear models can improve regression performance.

Performance should therefore be evaluated experimentally on the target dataset rather than assumed to improve universally.

---

## License

This project is licensed under the license specified in the `LICENSE` file.
