Export a Decision Tree to a SQL CASE WHEN Expression
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `tree_to_sql(model, feature_names=None)` that takes a fitted sklearn `DecisionTreeClassifier` or `DecisionTreeRegressor` and returns a single nested SQL expression string that reproduces `model.predict` when evaluated per row.
Requirements:
- Each internal node becomes `CASE WHEN {feat} <= {thr} THEN {left} ELSE {right} END` (single spaces, recursing left then right). Thresholds are formatted as `repr(float(thr))`.
- Feature names come from `feature_names`, defaulting to `x0`, `x1`, ... when it is `None`.
- A classifier leaf is the `argmax` class from `classes_`. Integers and bools are written as `str(int(v))`, strings are single-quoted with `'` escaped as `''`, and floats are written as `repr(float(v))`.
- A regressor leaf is the node mean as `repr(float(v))` (for example `3.0`).
- A single-leaf tree returns just the bare leaf value (for example `"4"`).
Examples:
```python
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
X = [[1], [2], [3], [4], [5], [6]]
y = [0, 0, 0, 1, 1, 2]
m = DecisionTreeClassifier(random_state=0).fit(X, y)
tree_to_sql(m, ["x"])
# 'CASE WHEN x <= 3.5 THEN 0 ELSE CASE WHEN x <= 5.5 THEN 1 ELSE 2 END END'
r = DecisionTreeRegressor(random_state=0).fit([[1], [2], [3], [4]], [1, 1, 5, 5])
tree_to_sql(r)
# 'CASE WHEN x0 <= 2.5 THEN 1.0 ELSE 5.0 END'
```
```hint Where the tree lives
A fitted sklearn tree keeps its structure in parallel arrays on `model.tree_`. Work out which array marks a leaf and which ones give a node's feature, threshold and children.
```
```hint Leaf values
Print the shape of `tree_.value[node]` for a classifier and for a regressor before deciding how to turn it into a SQL literal.
```
### Constraints & Assumptions
- The output is executed in SQLite as `SELECT {sql} FROM t` with `REAL` feature columns.
- Missing values are out of scope.
- The model is single-output (one target column).
### What a Strong Answer Covers
- Reading the fitted structure from `tree_` and recognizing leaf nodes.
- Matching sklearn's routing rule and printing thresholds without losing precision.
- Leaf literals for both model types, including string quoting and escaping and the single-leaf case.
- Telling classifiers from regressors, and the cost of the recursion.
- Whether the SQL can ever disagree with `predict`, and why.
### Follow-up Questions
- How would you export class probabilities instead of the predicted label?
- Deep trees can hit SQL nesting or query-length limits. How would you avoid that?
- How would you export a random forest or gradient-boosted ensemble?
Overview: Write a function that turns a fitted scikit-learn decision tree classifier or regressor into one nested SQL CASE WHEN expression that reproduces predict row by row. It tests reading the fitted tree_ arrays, matching the split rule and float formatting, and emitting correct SQL literals for leaf values.