create decision tree classifier in python

To create a decision tree classifier in Python, we can use the DecisionTreeClassifier class from the scikit-learn library. Here's an example:

main.py
# Import the required libraries
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split

# Load the iris dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Create the decision tree classifier
clf = DecisionTreeClassifier()

# Train the classifier on the training data
clf.fit(X_train, y_train)

# Test the classifier on the testing data
y_pred = clf.predict(X_test)

# Calculate the accuracy of the classifier
acc = clf.score(X_test, y_test)
print('Accuracy:', acc)
697 chars
26 lines

In this example, we first load the iris dataset and split it into training and testing sets. We then create a DecisionTreeClassifier object, train it on the training data, and test it on the testing data. Finally, we calculate the accuracy of the classifier.

gistlibby LogSnag