Lexico Random Forest Classifier¶
Abstract of LexicoRandomForestClassifier
Extracted from Ribeiro & Freitas (2024), "Lexicographical random forests for longitudinal data classification".
Standard supervised machine learning methods often ignore the temporal information represented in longitudinal data, but that information can lead to more precise predictions in classification tasks. Data preprocessing techniques and classification algorithms can be adapted to cope directly with longitudinal data inputs, making use of temporal information such as the time-index of features and previous measurements of the class variable. In this article, we propose two changes to the classification task of predicting age-related diseases in a real-world dataset created from the English Longitudinal Study of Ageing. First, we explore the addition of previous measurements of the class variable, and estimating the missing data in those added features using intermediate classifiers. Second, we propose a new split-feature selection procedure for a random forest's decision trees, which considers the candidate features' time-indexes, in addition to the information gain ratio. Our experiments compared the proposed approaches to baseline approaches, in 3 prediction scenarios, varying the "time gap" for the prediction - how many years in advance the class (occurrence of an age-related disease) is predicted. The experiments were performed on 10 datasets varying the class variable, and showed that the proposed approaches increased the random forest's predictive accuracy.
Adapted and integrated into a Random Forest, this estimator builds an ensemble of LexicoDecisionTreeClassifiers — each tree applies the lexicographic split-selection procedure above and their predictions are aggregated through the standard random-forest voting scheme.
What are features_group and non_longitudinal_features?
Two key attributes, features_group and non_longitudinal_features, enable algorithms to interpret the
temporal structure of longitudinal data.
- features_group: A list of lists where each sublist contains indices of a longitudinal attribute's waves, ordered from oldest to most recent. This captures temporal dependencies.
- non_longitudinal_features: A list of indices for static, non-temporal features excluded from the temporal matrix.
Proper setup of these attributes is critical for leveraging temporal patterns effectively.
LexicoRandomForestClassifier ¶
Bases: RandomForestClassifier
Lexico Random Forest Classifier for longitudinal data classification.
This classifier extends scikit-learn's RandomForestClassifier for longitudinal data by integrating a
lexicographic optimisation approach within each tree of the forest, based on the premise that recent
measurements are more predictive and relevant. Splits are evaluated with a bi-objective rule: the primary
objective maximises the information-gain ratio (entropy criterion), and the secondary objective favours
features from more recent waves whenever competing gain ratios are within threshold_gain. The ensemble
aggregates these temporally-aware trees to reduce overfitting while preserving recency-driven decisions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_estimators
|
int, default=100
|
The number of trees in the forest. |
100
|
threshold_gain
|
float, default=0.0015
|
Threshold for comparing gain ratios during split selection. Lower values enforce stricter recency preference; higher values allow more flexibility. |
0.0015
|
features_group
|
List[List[int]]
|
Temporal matrix of feature indices for longitudinal attributes, ordered by recency. Required for longitudinal functionality. |
None
|
max_depth
|
Optional[int], default=None
|
Maximum depth of each tree. |
None
|
min_samples_split
|
int, default=2
|
Minimum samples required to split an internal node. |
2
|
min_samples_leaf
|
int, default=1
|
Minimum samples required at a leaf node. |
1
|
min_weight_fraction_leaf
|
float, default=0.0
|
Minimum weighted fraction of total sample weight at a leaf. |
0.0
|
max_features
|
Optional[Union[int, str]], default="sqrt"
|
Number of features to consider for splits (e.g., "sqrt", "log2", int). |
'sqrt'
|
random_state
|
Optional[int], default=None
|
Seed for random number generation. |
None
|
max_leaf_nodes
|
Optional[int], default=None
|
Maximum number of leaf nodes per tree. |
None
|
min_impurity_decrease
|
float, default=0.0
|
Minimum impurity decrease required for a split. |
0.0
|
class_weight
|
Optional[Union[dict, List[dict], str]], default=None
|
Class weights (e.g., |
None
|
ccp_alpha
|
float, default=0.0
|
Complexity parameter for pruning; non-negative. |
0.0
|
**kwargs
|
Additional arguments for |
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
classes_ |
ndarray of shape (n_classes,
|
The class labels. |
n_classes_ |
int
|
Number of classes. |
n_features_ |
int
|
Number of features when fit is performed. |
n_outputs_ |
int
|
Number of outputs (fixed to 1). |
feature_importances_ |
ndarray of shape (n_features,
|
Impurity-based feature importances. |
max_features_ |
int
|
Inferred value of |
estimators_ |
list of LexicoDecisionTreeClassifier
|
Fitted tree ensemble. |
Examples:
Basic Usage
from sklearn.metrics import accuracy_score
from scikit_longitudinal.estimators.ensemble import LexicoRandomForestClassifier
import numpy as np
from scikit_longitudinal.data_preparation import LongitudinalDataset
# Load dataset
dataset = LongitudinalDataset('./stroke_longitudinal.csv')
dataset.load_data()
dataset.load_target(target_column="stroke_w2")
dataset.setup_features_group("elsa")
dataset.load_train_test_split(test_size=0.2, random_state=42)
clf = LexicoRandomForestClassifier(features_group=dataset.feature_groups())
clf.fit(dataset.X_train, dataset.y_train)
y_pred = clf.predict(dataset.X_test)
print(f"Accuracy: {accuracy_score(dataset.y_test, y_pred)}")
Advanced: tuning threshold gain
from sklearn.metrics import accuracy_score
from scikit_longitudinal.estimators.ensemble import LexicoRandomForestClassifier
import numpy as np
from scikit_longitudinal.data_preparation import LongitudinalDataset
# Load dataset
dataset = LongitudinalDataset('./stroke_longitudinal.csv')
dataset.load_data()
dataset.load_target(target_column="stroke_w2")
dataset.setup_features_group("elsa")
dataset.load_train_test_split(test_size=0.2, random_state=42)
clf = LexicoRandomForestClassifier(
features_group=dataset.feature_groups(),
threshold_gain=0.001 # Change this value to tune the model
)
clf.fit(dataset.X_train, dataset.y_train)
y_pred = clf.predict(dataset.X_test)
print(f"Accuracy: {accuracy_score(dataset.y_test, y_pred)}")
clf = LexicoRandomForestClassifier(threshold_gain=0.001, features_group=[[0, 1], [2, 3]])
clf.fit(X, y)
y_pred = clf.predict(X)
print(f"Accuracy: {accuracy_score(y, y_pred)}")
Hyperparameter Tuning
Use GridSearchCV or RandomizedSearchCV from sklearn.model_selection to optimize threshold_gain
and other hyperparameters. For example:
from sklearn.model_selection import GridSearchCV
# ... Similar setup as above ...
param_grid = {
'threshold_gain': [0.001, 0.002, 0.003],
'n_estimators': [50, 100, 200],
}
grid_search = GridSearchCV(
LexicoRandomForestClassifier(
# features_group = ... Same as previous example ...
)
param_grid,
cv=5,
scoring='accuracy',
)
grid_search.fit(X, y)
print(f"Best parameters: {grid_search.best_params_}")
Source code in scikit_longitudinal/estimators/ensemble/lexicographical/lexico_random_forest.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | |
fit(X, y, sample_weight=None, *args, **kwargs)
¶
Fit the Lexico Random Forest Classifier to the training data.
Trains the classifier by constructing multiple LexicoDecisionTreeClassifiers, each utilizing the features_group
for lexicographic optimization tailored to longitudinal data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training input samples. |
required |
y
|
array-like of shape (n_samples,)
|
Target values (class labels). |
required |
*args
|
Additional positional arguments for the superclass |
()
|
|
**kwargs
|
Additional keyword arguments for the superclass |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
Fitted classifier instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Tuning Tip
Adjust n_estimators and threshold_gain to balance accuracy and computation time. Start with defaults
and refine based on your dataset.
Source code in scikit_longitudinal/estimators/ensemble/lexicographical/lexico_random_forest.py
predict(X)
¶
Predict class labels for the input samples.
Inherited from scikit-learn's RandomForestClassifier. Each tree votes for a class and the
class with the most votes is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Input samples. |
required |
Returns:
| Type | Description |
|---|---|
|
np.ndarray: Predicted class labels of shape |
Source code in scikit_longitudinal/estimators/ensemble/lexicographical/lexico_random_forest.py
predict_proba(X)
¶
Predict class probabilities for the input samples.
Inherited from scikit-learn's RandomForestClassifier. Probabilities are the mean of the
probabilistic predictions of the individual trees.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Input samples. |
required |
Returns:
| Type | Description |
|---|---|
|
np.ndarray: Class probabilities of shape |
|
|
as in |