まとめ
- RuleFit extracts if-then rules from tree ensembles, keeps the original numeric features, and fits everything with an L1-regularized linear model.
- Rules capture interactions and thresholds, linear terms retain global trends, and sparsity keeps the model both predictive and interpretable.
- Tune
max_rules, tree depth/number, and (if applicable) boosting parameters; rely on cross-validation to control overfitting. - Visualize the top rules and translate them into business language before sharing with stakeholders.
1. Idea (with formulas) #
- Extract rules: each path to a leaf becomes a binary feature (r_j(x) \in {0,1}).
- Add scaled linear terms (z_k(x)) for continuous features.
- L1-regularized linear fit:
$$ \hat{y}(x) = \beta_0 + \sum_j \beta_j r_j(x) + \sum_k \gamma_k z_k(x) $$
L1 promotes sparsity so only influential rules/terms remain.
2. Dataset (OpenML: house_sales) #
King County housing prices (OpenML data_id=42092). Numeric columns only for clarity.
import japanize_matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
dataset = fetch_openml(data_id=42092, as_frame=True)
X = dataset.data.select_dtypes("number").copy()
y = dataset.target.astype(float)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
3. Fit RuleFit #
Python implementation: christophM/rulefit
from rulefit import RuleFit
import warnings
warnings.simplefilter("ignore")
rf = RuleFit(max_rules=200, tree_random_state=27)
rf.fit(X_train.values, y_train.values, feature_names=list(X_train.columns))
pred_tr = rf.predict(X_train.values)
pred_te = rf.predict(X_test.values)
def report(y_true, y_pred, name):
rmse = mean_squared_error(y_true, y_pred, squared=False)
mae = mean_absolute_error(y_true, y_pred)
r2 = r2_score(y_true, y_pred)
print(f"{name:8s} RMSE={rmse:,.0f} MAE={mae:,.0f} R2={r2:.3f}")
report(y_train, pred_tr, "Train")
report(y_test, pred_te, "Test")
4. Inspect top rules #
rules = rf.get_rules()
rules = rules[rules.coef != 0].sort_values(by="importance", ascending=False)
rules.head(10)
rule: if-then condition (type=lineardenotes a linear term)coef: regression coefficient (target units)support: fraction of samples that satisfy the ruleimportance: scaled score combining coefficient magnitude and support
5. Validate via visualization #
plt.figure(figsize=(6, 5))
plt.scatter(X_train["sqft_above"], y_train, s=10, alpha=0.5)
plt.xlabel("sqft_above")
plt.ylabel("price")
plt.title("Relationship between sqft_above and price")
plt.grid(alpha=0.3)
plt.show()
rule_mask = X["sqft_living"].le(3935.0) & X["lat"].le(47.5315)
applicable_data = np.log(y[rule_mask])
not_applicable = np.log(y[~rule_mask])
plt.figure(figsize=(8, 5))
plt.boxplot([applicable_data, not_applicable],
labels=["Rule satisfied", "Rule not satisfied"])
plt.ylabel("log(price)")
plt.title("Price distribution by rule satisfaction")
plt.grid(alpha=0.3)
plt.show()
6. Practical tips #
- Handle outliers (Winsorization, clipping) for stable rules.
- Clean categorical levels and encode only after grouping rare categories.
- Transform skewed targets (
log(y)or Box-Cox) if necessary. - Select rule counts/depths that stakeholders can read; cross-validate to pick limits.
- Summarize the top rules in plain language for business reports.
7. References #
- Friedman, J. H., & Popescu, B. E. (2008). Predictive Learning via Rule Ensembles. The Annals of Applied Statistics, 2(3), 916–954.
- Christoph Molnar. (2020). Interpretable Machine Learning. https://christophm.github.io/interpretable-ml-book/rulefit.html