![]() |
VOOZH | about |
A Decision Tree Classifier is a supervised machine learning algorithm that categorizes data by recursively splitting it based on feature-driven decision rules. Each internal node represents a condition on a feature, branches denote the outcomes of those conditions and leaf nodes assign the final class label.
Scikit-learn provides the DecisionTreeClassifier class for building decision tree models. The basic syntax is shown below:
class sklearn.tree.DecisionTreeClassifier(
*,
criterion='gini',
splitter='best',
max_depth=None,
min_samples_split=2,
min_samples_leaf=1,
min_weight_fraction_leaf=0.0,
max_features=None,
random_state=None,
max_leaf_nodes=None,
min_impurity_decrease=0.0,
class_weight=None,
ccp_alpha=0.0,
monotonic_cst=None
)
Parameters:
This tree-based structure makes the model both interpretable and effective for classification tasks.
Here we implement a Decision Tree Classifier using Scikit-Learn.
We will import libraries like Scikit-Learn for machine learning tasks.
In order to perform classification load a dataset. For demonstration one can use sample datasets from Scikit-Learn such as Iris or Breast Cancer.
Use the train_test_split method from sklearn.model_selection to split the dataset into training and testing sets.
Using DecisionTreeClassifier from sklearn.tree create an object for the Decision Tree Classifier.
Apply the fit method to train the classifier on the training data.
Output:
Apply the predict method to the test data and use the trained model to create predictions.
Output:
Accuracy: 0.9555555555555556
Hyperparameters are configuration settings that control how a decision tree model learns from data.
Refer: How to tune a Decision Tree in Hyperparameter tuning?
Let's make use of Scikit-Learn's GridSearchCV to find the best combination of hyperparameter values. The code is as follows:
Output:
Here we defined the parameter grid with a set of hyperparameters and a list of possible values. The GridSearchCV evaluates the different hyperparameter combinations for the Decision Tree Classifier and selects the best combination of hyperparameters based on the performance across all k folds.
Decision Tree visualization is used to interpret and comprehend model's choices. We'll plot feature importance obtained from the Decision Tree model to see which features have the greatest predictive power. Here we fetch the best estimator obtained from the GridSearchCV as the decision tree classifier.
Output:
We can see that it start from the root node (depth 0 at the top).