Skip to content

A Lightweight Decision Tree Framework supporting regular algorithms: ID3, C4.5, CART, CHAID and Regression Trees; some advanced techniques: Gradient Boosting, Random Forest and Adaboost w/categorical features support for Python

License

Notifications You must be signed in to change notification settings

serengil/chefboost

Repository files navigation

ChefBoost

Downloads Stars License Tests DOI

Blog YouTube Twitter

Support me on Patreon GitHub Sponsors Buy Me a Coffee

👨‍🍳

ChefBoostis a lightweight decision tree framework for Pythonwith categorical feature support.It covers regular decision tree algorithms:ID3,C4.5,CART,CHAIDandregression tree;also some advanved techniques:gradient boosting,random forestandadaboost.You just need to writea few lines of codeto build decision trees with Chefboost.

Installation-Demo

The easiest way to install ChefBoost framework is to download it fromfrom PyPI.It's going to install the library itself and its prerequisites as well.

pip install chefboost

Then, you will be able to import the library and use its functionalities

fromchefboostimportChefboostaschef

Usage-Demo

Basically, you just need to pass the dataset as pandas data frame and the optional tree configurations as illustrated below.

importpandasaspd

df=pd.read_csv("dataset/golf.txt")
config={'algorithm':'C4.5'}
model=chef.fit(df,config=config,target_label='Decision')

Pre-processing

Chefboost handles the both numeric and nominal features and target values in contrast to its alternatives. So, you don't have to apply any pre-processing to build trees.

Outcomes

Built decision trees are stored as Python if statements in thetests/outputs/rulesdirectory. A sample of decision rules is demonstrated below.

deffindDecision(Outlook,Temperature,Humidity,Wind):
ifOutlook=='Rain':
ifWind=='Weak':
return'Yes'
elifWind=='Strong':
return'No'
else:
return'No'
elifOutlook=='Sunny':
ifHumidity=='High':
return'No'
elifHumidity=='Normal':
return'Yes'
else:
return'Yes'
elifOutlook=='Overcast':
return'Yes'
else:
return'Yes'

Testing for custom instances

Decision rules will be stored inoutputs/rules/folder when you build decision trees. You can run the built decision tree for new instances as illustrated below.

prediction=chef.predict(model,param=['Sunny','Hot','High','Weak'])

You can consume built decision trees directly as well. In this way, you can restore already built decision trees and skip learning steps, or applytransfer learning.Loaded trees offer you findDecision method to test for new instances.

module_name="outputs/rules/rules"#this will load outputs/rules/rules.py
tree=chef.restoreTree(module_name)
prediction=tree.findDecision(['Sunny','Hot','High','Weak'])

tests/global-unit-test.py will guide you how to build a different decision trees and make predictions.

Model save and restoration

You can save your trained models. This makes your model ready for transfer learning.

chef.save_model(model,"model.pkl")

In this way, you can use the same model later to just make predictions. This skips the training steps. Restoration requires to store.py and.pkl files underoutputs/rules.

model=chef.load_model("model.pkl")
prediction=chef.predict(model,['Sunny',85,85,'Weak'])

Sample configurations

ChefBoost supports several decision tree, bagging and boosting algorithms. You just need to pass the configuration to use different algorithms.

Regular Decision Trees

Regular decision tree algorithms find the best feature and the best split point maximizing the information gain. It builds decision trees recursively in child nodes.

config={'algorithm':'C4.5'}#Set algorithm to ID3, C4.5, CART, CHAID or Regression
model=chef.fit(df,config)

The following regular decision tree algorithms are wrapped in the library.

Algorithm Metric Tutorial Demo
ID3 Entropy, Information Gain Tutorial Demo
C4.5 Entropy, Gain Ratio Tutorial Demo
CART GINI Tutorial Demo
CHAID Chi Square Tutorial Demo
Regression Standard Deviation Tutorial Demo

Gradient BoostingTutorial,Demo

Gradient boosting is basically based on building a tree, and then building another based on the previous one's error. In this way, it boosts results. Predictions will be the sum of each tree'e prediction result.

config={'enableGBM':True,'epochs':7,'learning_rate':1,'max_depth':5}

Random ForestTutorial,Demo

Random forest basically splits the data set into several sub data sets and builds different data set for those sub data sets. Predictions will be the average of each tree's prediction result.

config={'enableRandomForest':True,'num_of_trees':5}

AdaboostTutorial,Demo

Adaboost applies a decision stump instead of a decision tree. This is a weak classifier and aims to get min 50% score. It then increases the unclassified ones and decreases the classified ones. In this way, it aims to have a high score with weak classifiers.

config={'enableAdaboost':True,'num_of_weak_classifier':4}

Feature Importance-Demo

Decision trees are naturally interpretable and explainable algorithms. A decision is clear made by a single tree. Still we need some extra layers to understand the built models. Besides, random forest and GBM are hard to explain. Herein,feature importanceis one of the most common way to see the big picture and understand built models.

df=chef.feature_importance("outputs/rules/rules.py")
feature final_importance
Humidity 0.3688
Wind 0.3688
Outlook 0.2624
Temperature 0.0000

Paralellism

ChefBoost offers parallelism to speed model building up. Branches of a decision tree will be created in parallel in this way. You should set enableParallelism argument to False in the configuration if you don't want to use parallelism. Its default value is True. It allocates half of the total number of cores in your environment if parallelism is enabled.

if__name__=='__main__':
config={'algorithm':'C4.5','enableParallelism':True,'num_cores':2}
model=chef.fit(df,config)

Notice that you have to locate training step in an if block and it should check you are in main.

To not use parallelism set the parameter to False.

config={'algorithm':'C4.5','enableParallelism':False}
model=chef.fit(df,config)

ContributionTests

Pull requests are more than welcome! You should run the unit tests and linting locally by runningmake testandmake lintcommands before creating a PR. Once a PR created, GitHub test workflow will be run automatically and unit test results will be available inGitHub actionsbefore approval.

Support

There are many ways to support a project - starring⭐️ the GitHub repos is just one 🙏

You can also support this work onPatreon,GitHub SponsorsorBuy Me a Coffee.

Also, your company's logo will be shown on README on GitHub if you become sponsor in gold, silver or bronze tiers.

Citation

Please citeChefBoostin your publications if it helps your research. Here is an example BibTeX entry:

@misc{serengil2021chefboost,
author={Serengil, Sefik Ilkin},
title={ChefBoost: A Lightweight Boosted Decision Tree Framework},
month= oct,
year=2021,
publisher={Zenodo},
doi={10.5281/zenodo.5576203},
howpublished={https://doi.org/10.5281/zenodo.5576203}
}

Also, if you use chefboost in your GitHub projects, please add chefboost in the requirements.txt.

Licence

ChefBoost is licensed under the MIT License - seeLICENSEfor more details.