Understand the idea
A classification tree asks a sequence of threshold questions. A useful split separates class counts, reducing impurity. A leaf predicts from the classes reaching it. Scaling is unnecessary; depth and minimum leaf size constrain overfitting.
Illustrative data
| Class | (width, length) |
|---|---|
| Class A | t1: (2, 3); t2: (3, 5); t3: (4, 4); t7: (7, 8) |
| Class B | t4: (7, 3); t5: (8, 6); t6: (6, 6) |
Click the highlighted code to change the result.
example_model = DecisionTreeClassifier(max_depth=2, random_state=42)
example_model.fit(example[["width", "length"]], example["class"])
row = pd.DataFrame([{"width": , "length": }])
example_model.predict(row) # At2: width 3 ≤ 5: yes → predict A.
What the syntax does
DecisionTreeClassifier(max_depth=3, random_state=42)- Creates a decision tree classifier.
max_depth:3,5,Nonerandom_state:42,None
max_depthis a positive integer or None (the default, without this cap). min_samples_leaf is a positive count or a fitting-row fraction.- More depth or smaller leaves permits finer fits and can overfit; validate before opening final rows.
- Scaling is unnecessary for these thresholds.
model.apply(row)- Finds the leaf reached by a row; predict returns the class selected at that leaf.
Supplied for this practice
These objects are prepared afresh before your editor runs.
X- Feature dataframe for the declared population, preserving row indices.
X = df[['length', 'width']] y- Target series, aligned with
X.y = df.label X_train/X_test/y_train/y_test- Training feature rows from the declared split. Final-test feature rows from the declared split. Training targets, aligned with
X_train. Final-test targets, aligned withX_test.X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
Outputs you create
leaf- Requested result described in the task and deliverables.
label- Requested result described in the task and deliverables.
length | width | label |
|---|---|---|
| 236.033 | -0.805568 | A |
| 581.297 | 0.728558 | A |
| -1511.27 | -1.00866 | A |
| 99.0248 | -0.24496 | A |
| -13.0141 | -0.660765 | A |
| 681.179 | 0.602475 | A |
| 51.1472 | 0.873157 | A |
| 362.131 | -0.665605 | A |
- Fit a tree with maximum depth 3.
- For the first test row, store its terminal node ID in
leafand its predicted class inlabel.
leaflabelHints
Think: A tree follows feature thresholds to a leaf with a learned class prediction.
Tools: DecisionTreeClassifier, apply and predict.
Approach: Fit the declared depth-limited tree, then obtain the first test row’s leaf and label.
Explained solution
from sklearn.tree import DecisionTreeClassifier
model=DecisionTreeClassifier(max_depth=3,random_state=42).fit(X_train,y_train)
leaf=int(model.apply(X_test.iloc[:1])[0])
label=model.predict(X_test.iloc[:1])[0]
The two outputs connect tree traversal with classification without requiring any regression-tree prerequisite.