Build a Decision Tree Classifier
Intermediate · Write the code · from Python Classification: Build a Classifier with scikit-learn
From the lesson: Python Classification: Build a Classifier with scikit-learn
Your email inbox sorts messages into "spam" or "not spam." A bank flags transactions as "fraudulent" or "legitimate." A doctor classifies a tumor as "benign" or "malignant." These are all classification problems - the model predicts which category something belongs to.
Read the lessonTrain a DecisionTreeClassifier with max_depth=3 and random_state=42. Print the accuracy on the test set rounded to 4 decimal places, then on the next line print the number of leaves in the tree.
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
X, y = make_classification(n_samples=200, n_features=4,
random_state=42)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
# Train and print accuracy + number of leaves
More Classification exercises
- Train a Logistic Regression ClassifierIntermediate
- Predict the OutputIntermediate
- Fix the KNN BugIntermediate
- Read a Confusion MatrixIntermediate
- Compare Three ClassifiersIntermediate
All Python exercises · 50 practice problems · Data Science & Machine Learning quiz