Inspect a fitted scikit-learn decision tree: export its rules and build a per-node table
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement three functions around a scikit-learn decision tree:
- `fit_tree(X, y, max_depth=None, random_state=0)` fits and returns a Gini `DecisionTreeClassifier`.
- `export_rules(model, feature_names, class_names)` returns the tree's text rules.
- `node_table(model, class_names)` returns a per-node `pd.DataFrame` read from `model.tree_`.
The functions must meet these requirements:
- `fit_tree` must produce the same tree as scikit-learn's default classifier with the given `max_depth` and `random_state`.
- `export_rules` returns exactly the output of `export_text` with the given feature and class names and `decimals=2`.
- The table has these columns, in order: `node_id`, `depth`, `is_leaf`, `impurity`, `n_samples`, `predicted_class`. It has one row per node, ordered by `node_id`.
- Dtypes are `int64` for `node_id`, `depth` and `n_samples`, `bool` for `is_leaf`, `float64` for `impurity`, and `object` for `predicted_class`. The root has depth `0`.
- `predicted_class` is `class_names[argmax(tree_.value[i, 0])]` for every node, internal nodes included.
Example:
```python
X = [[1.0], [2.0], [3.0], [4.0]]
y = [0, 0, 1, 1]
model = fit_tree(X, y)
export_rules(model, ["x"], ["no", "yes"]) # contains "x <= 2.50", "class: no", "class: yes"
node_table(model, ["no", "yes"])
# node_id depth is_leaf impurity n_samples predicted_class
# 0 0 0 False 0.5 4 no
# 1 1 1 True 0.0 2 no
# 2 2 1 True 0.0 2 yes
```
```hint Where depth comes from
`model.tree_` stores child pointers, impurity, sample counts and class values for every node, but no depth. Think about how to derive depth from the child arrays.
```
### What a Strong Answer Covers
- Passing the criterion and seed through so the fitted structure is reproducible, and why the seed matters at all.
- Reusing `export_text` with the exact arguments the requirement names.
- Deriving each node's depth from the child arrays and identifying leaves correctly.
- Producing the required column order, row order and dtypes.
- Mapping the entries of `tree_.value` to class names in the order of `model.classes_`.
### Follow-up Questions
- Two fits on the same data, with every feature considered at each split, can still produce different trees when `random_state` is not fixed. Why?
- Depending on the scikit-learn version, `tree_.value` holds weighted class counts or class fractions. How would you get weighted counts per node either way?
- How would you find the leaf, and the full path of nodes, that a given row of `X` goes through?
Overview: Write three Python helpers around a scikit-learn decision tree: fit a reproducible Gini classifier, return its text rules, and build a per-node table from model.tree_. It tests how well you know the fitted tree's internal arrays, node depth, leaf detection and exact pandas dtypes.