Skip to main content

A package for building customizable decision trees and random forests.

Project description


Custom Decision Trees

Static Badge GitHub License PyPI - Downloads Ruff

Custom Decision Trees is a Python package that lets you build machine learning models with advanced configuration :

Main Features

Splitting criteria customization

Define your own cutting criteria in Python language (documentation in the following sections).

This feature is particularly useful in "cost-dependent" scenarios. Examples:

  • Trading Movements Classification: When the goal is to maximize economic profit, the metric can be set to economic profit, optimizing tree splitting accordingly.
  • Churn Prediction: To minimize false negatives, metrics like F1 score or recall can guide the splitting process.
  • Fraud Detection: Splitting can be optimized based on the proportion of fraudulent transactions identified relative to the total, rather than overall classification accuracy.
  • Marketing Campaigns: The splitting can focus on maximizing expected revenue from customer segments identified by the tree.

Multi-conditional node splitting

Allow trees to split nodes with one or more simultaneous conditions.

Example of multi-condition splitting on the Titanic dataset:

Multi Conditional Node Splitting

Reminder on splitting criteria

Splitting in a decision tree is achieved by optimizing a metric. For example, Gini optimization consists in maximizing the $\Delta_{Gini}$ :

  • The Gini Index represents the impurity of a group of observations based on the observations of each class (0 and 1):

$$ I_{Gini} = 1 - p_0^2 - p_1^2 $$

  • The metric to be maximized is $\Delta_{Gini}$, the difference between the Gini index on the parent node and the weighted average of the Gini index between the two child nodes ($L$ and $R$).

$$ \Delta_{Gini} = I_{Gini} - \frac{N_L * I_{Gini_L}}{N} - \frac{N_R * I_{Gini_R}}{N} $$

At each node, the tree algorithm finds the split that minimizes $\Delta$ over all possible splits and over all features. Once the optimal split is selected, the tree is grown by recursively applying this splitting process to the resulting child nodes.

Usage

See ./notebooks/ folder for a complete examples.

Installation

pip install custom-decision-trees

Define your metric

To integrate a specific measure, the user must define a class containing the compute_metric and compute_delta methods, then insert this class into the classifier.

Example of a class with the Gini index :

import numpy as np

from custom_decision_trees.metrics import MetricBase


def compute_gini(
        metric_data: np.ndarray
    ) -> float:

    y = metric_data[:, 0]

    prop0 = np.sum(y == 0) / len(y)
    prop1 = np.sum(y == 1) / len(y)

    metric = 1 - (prop0**2 + prop1**2)

    return float(metric)

class Gini(MetricBase):
    """
    A class that implements the Gini impurity metric for decision trees.
    """

    def __init__(
            self,
        ) -> None:
        pass

    def compute_metric(
            self,
            metric_data: np.ndarray,
            mask: np.ndarray
        ) -> tuple[float, dict]:

        gini_parent = compute_gini(metric_data)
        gini_side1 = compute_gini(metric_data[mask])
        gini_side2 = compute_gini(metric_data[~mask])

        delta = (
            gini_parent - 
            gini_side1 * np.mean(mask) - 
            gini_side2 * (1 - np.mean(mask))
        )

        metadata = {"gini": round(gini_side1, 3)}

        return float(delta), metadata

Train and predict

Once you have instantiated the model with your custom metric, all you have to do is use the .fit and .predict_proba methods:

from custom_decision_trees import DecisionTree

gini = Gini()

decision_tree = DecisionTree(
    metric=gini,
    max_depth=2,
    nb_max_conditions_per_node=2 # Set to 1 for a traditional decision tree
)

decision_tree.fit(
    X=X_train,
    y=y_train,
    metric_data=metric_data,
)

probas = model.predict_probas(
    X=X_test
)

probas[:5]
>>> array([[0.75308642, 0.24691358],
           [0.36206897, 0.63793103],
           [0.75308642, 0.24691358],
           [0.36206897, 0.63793103],
           [0.90243902, 0.09756098]])

Print the tree

You can also display the decision tree, with the values of your metrics, using the print_tree method:

decision_tree.print_tree(
    feature_names=features,
    metric_name="MyMetric",
)
>>> [0] 712 obs -> MyMetric = 0.0
    |   [1] (x["Sex"] <= 0.0) AND (x["Pclass"] <= 2.0) | 157 obs -> MyMetric = 0.16
    |   |   [3] (x["Age"] <= 2.0) AND (x["Fare"] > 26.55) | 1 obs -> MyMetric = 0.01
    |   |   [4] (x["Age"] > 2.0) OR (x["Fare"] <= 26.55) | 156 obs -> MyMetric = 0.01
    |   [2] (x["Sex"] > 0.0) OR (x["Pclass"] > 2.0) | 555 obs -> MyMetric = 0.16
    |   |   [5] (x["SibSp"] <= 2.0) AND (x["Age"] <= 8.75) | 27 obs -> MyMetric = 0.05
    |   |   [6] (x["SibSp"] > 2.0) OR (x["Age"] > 8.75) | 528 obs -> MyMetric = 0.05

Plot the tree

decision_tree.plot_tree(
    feature_names=features,
    metric_name="delta gini",
)

Multi Conditional Node Splitting

Random Forest

Same with Random Forest Classifier :

from custom_decision_trees import RandomForest

random_forest = RandomForest(
    metric=gini,
    n_estimators=10,
    max_depth=2,
    nb_max_conditions_per_node=2,
)

random_forest.fit(
    X=X_train, 
    y=y_train, 
    metric_data=metric_data
)

probas = random_forest.predict_probas(
    X=X_test
)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

custom_decision_trees-2.0.0.tar.gz (20.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

custom_decision_trees-2.0.0-py3-none-any.whl (22.5 kB view details)

Uploaded Python 3

File details

Details for the file custom_decision_trees-2.0.0.tar.gz.

File metadata

  • Download URL: custom_decision_trees-2.0.0.tar.gz
  • Upload date:
  • Size: 20.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.9

File hashes

Hashes for custom_decision_trees-2.0.0.tar.gz
Algorithm Hash digest
SHA256 65bf58c8b08f46fdf6c9ba55912122fdb0f83f063414a785559444861c54285f
MD5 d99fa366c567bec6a9ad384a25b24c92
BLAKE2b-256 aa3fc4e3b2a56135a72406a8b9a90640a240bc00432cc5f3940e56d06248b12c

See more details on using hashes here.

File details

Details for the file custom_decision_trees-2.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for custom_decision_trees-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1eae5eb761c6791e5d9635203e26f7edbfe49c7768b762d6f60fa39c77a3add2
MD5 782f1369d3fe374811ce724562743a91
BLAKE2b-256 1eb920a248809c3d4f87a33297dc46ab4b2897d95d6ef56d5cc4b8cdbe644839

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page