-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathqrf.py
More file actions
1565 lines (1327 loc) · 63.8 KB
/
qrf.py
File metadata and controls
1565 lines (1327 loc) · 63.8 KB
1
2
3
4
5
6
7
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Quantile Regression Forest imputation model with sequential imputation."""
import gc
import time
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
from pydantic import validate_call
from quantile_forest import RandomForestQuantileRegressor
from sklearn.ensemble import RandomForestClassifier
from microimpute.config import VALIDATE_CONFIG
from microimpute.models.imputer import Imputer, ImputerResults
try:
import psutil
PSUTIL_AVAILABLE = True
except ImportError:
PSUTIL_AVAILABLE = False
def _get_sequential_predictors(
predictors: List[str],
imputed_variables: List[str],
current_variable_index: int,
) -> List[str]:
"""Get the predictor set for sequential imputation.
Args:
predictors: Original predictor variables
imputed_variables: Variables being imputed
current_variable_index: Index of the current variable being imputed
Returns:
List of predictor columns including previously imputed variables
"""
return predictors + imputed_variables[:current_variable_index]
class _RandomForestClassifierModel:
"""Internal class to handle classification for categorical/boolean targets."""
def __init__(self, seed: int, logger):
self.seed = seed
self.logger = logger
self.classifier = None
self.output_column = None
self.var_type = None
self.categories = None
self.label_map = None
def fit(
self,
X: pd.DataFrame,
y: pd.Series,
var_type: str,
categories: List = None,
**rf_kwargs: Any,
) -> None:
"""Fit classifier for categorical/boolean target.
Note: y should be the ORIGINAL categorical/boolean column,
not dummy encoded.
"""
self.output_column = y.name
self.var_type = var_type
if var_type == "boolean":
# For boolean, convert to 0/1 but keep as single target
y_encoded = y.astype(int)
self.categories = [False, True]
else:
# For categorical, create label encoding
self.categories = categories if categories else y.unique().tolist()
self.label_map = {cat: i for i, cat in enumerate(self.categories)}
y_encoded = y.map(self.label_map)
# Check for unmapped values
if y_encoded.isna().any():
self.logger.warning(
f"Found {y_encoded.isna().sum()} unmapped values in {self.output_column}"
)
y_encoded = y_encoded.fillna(0) # Default to first category
# Extract relevant RF parameters from kwargs
classifier_params = {
"n_estimators": rf_kwargs.get("n_estimators", 100),
"max_depth": rf_kwargs.get("max_depth", None),
"min_samples_split": rf_kwargs.get("min_samples_split", 2),
"min_samples_leaf": rf_kwargs.get("min_samples_leaf", 1),
"max_features": rf_kwargs.get("max_features", "sqrt"),
"random_state": self.seed,
}
self.classifier = RandomForestClassifier(**classifier_params)
self.classifier.fit(X, y_encoded)
def predict(self, X: pd.DataFrame, return_probs: bool = False) -> pd.Series:
"""Predict classes or probabilities."""
if return_probs:
probs = self.classifier.predict_proba(X)
# Return both probabilities and the original category labels
# The probabilities are ordered according to self.classifier.classes_
# which are the encoded values, but we need to return the original labels
# in the same order
if self.var_type == "boolean":
# For boolean, classes are simply False and True
# sklearn's classifier.classes_ will be [0, 1] in order
original_classes = [False, True]
else:
# For categorical, map encoded values back to original labels
original_classes = []
for encoded_val in self.classifier.classes_:
# Find the original category for this encoded value
for cat, enc in self.label_map.items():
if enc == encoded_val:
original_classes.append(cat)
break
return {
"probabilities": probs,
"classes": np.array(original_classes),
}
else:
y_pred = self.classifier.predict(X)
if self.var_type == "boolean":
predictions = pd.Series(y_pred.astype(bool), index=X.index)
else:
# Map back to original categories
reverse_map = {i: cat for cat, i in self.label_map.items()}
predictions = pd.Series(y_pred).map(reverse_map)
predictions.index = X.index
predictions.name = self.output_column
return predictions
class _QRFModel:
"""Internal class to handle QRF model with quantile prediction logic."""
def __init__(self, seed: int, logger):
self.seed = seed
self.logger = logger
self.qrf = None
self.output_column = None
def fit(self, X: pd.DataFrame, y: pd.Series, **qrf_kwargs: Any) -> None:
"""Fit the QRF model.
Note: Assumes X is already preprocessed with categorical encoding
handled by the base Imputer class.
"""
self.output_column = y.name
# Remove random_state from kwargs if present, since we set it explicitly
qrf_kwargs_filtered = {
k: v for k, v in qrf_kwargs.items() if k != "random_state"
}
# Create and fit model
self.qrf = RandomForestQuantileRegressor(
random_state=self.seed, **qrf_kwargs_filtered
)
self.qrf.fit(X, y.values.ravel())
def predict(
self,
X: pd.DataFrame,
mean_quantile: float = 0.5,
count_samples: int = 10,
) -> pd.Series:
"""Predict using the fitted model with beta distribution sampling.
Note: Assumes X is already preprocessed with categorical encoding
handled by the base ImputerResults class.
"""
# Generate quantile grid
eps = 1.0 / (count_samples + 1)
quantile_grid = np.linspace(eps, 1.0 - eps, count_samples)
pred = self.qrf.predict(X, quantiles=list(quantile_grid))
# Sample from beta distribution
random_generator = np.random.default_rng(self.seed)
a = mean_quantile / (1 - mean_quantile)
input_quantiles = random_generator.beta(a, 1, size=len(X)) * count_samples
input_quantiles = np.clip(input_quantiles.astype(int), 0, count_samples - 1)
# Extract predictions
if len(pred.shape) == 2:
predictions = pred[np.arange(len(pred)), input_quantiles]
else:
predictions = pred[np.arange(len(pred)), :, input_quantiles]
return pd.Series(predictions, index=X.index, name=self.output_column)
class QRFResults(ImputerResults):
"""
Fitted QRF instance ready for imputation.
"""
def __init__(
self,
models: Dict[
str, Any
], # Can be _QRFModel, _RandomForestClassifierModel, or _ConstantValueModel
predictors: List[str],
imputed_variables: List[str],
seed: int,
imputed_vars_dummy_info: Optional[Dict[str, str]] = None,
original_predictors: Optional[List[str]] = None,
categorical_targets: Optional[Dict[str, Dict]] = None,
boolean_targets: Optional[Dict[str, Dict]] = None,
constant_targets: Optional[Dict[str, Dict]] = None,
dummy_processor: Optional[Any] = None,
log_level: Optional[str] = "WARNING",
) -> None:
"""Initialize the QRF results.
Args:
models: Dictionary of fitted models (QRF or RF classifier) for each variable.
predictors: List of column names used as predictors.
imputed_variables: List of column names to be imputed.
seed: Random seed for reproducibility.
imputed_vars_dummy_info: Optional dictionary containing information
about dummy variables for imputed variables.
original_predictors: Optional list of original predictor variable
names before dummy encoding.
categorical_targets: Dictionary of categorical target info.
boolean_targets: Dictionary of boolean target info.
dummy_processor: Processor for handling dummy encoding in test data.
"""
super().__init__(
predictors,
imputed_variables,
seed,
imputed_vars_dummy_info,
original_predictors,
log_level,
)
self.models = models
self.categorical_targets = categorical_targets or {}
self.boolean_targets = boolean_targets or {}
self.constant_targets = constant_targets or {}
self.dummy_processor = dummy_processor
def _get_encoded_predictors(self, current_predictors: List[str]) -> List[str]:
"""Get properly encoded predictor columns for sequential imputation.
Args:
current_predictors: List of predictor variable names
Returns:
List of encoded predictor column names
"""
if self.dummy_processor:
return self.dummy_processor.get_sequential_predictor_columns(
current_predictors
)
else:
return current_predictors
def _encode_imputed_variable(
self, data: pd.DataFrame, variable: str
) -> pd.DataFrame:
"""Encode a categorical imputed variable for use as predictor in subsequent iterations.
Args:
data: DataFrame containing the imputed variable
variable: Name of the variable that was just imputed
Returns:
DataFrame with encoded variable (adds dummy columns if categorical)
"""
if (
self.dummy_processor
and variable in self.dummy_processor.imputed_var_dummy_mapping
):
data = self.dummy_processor.sequential_imputed_predictor_encoding(
data, variable
)
self.logger.debug(
f" Encoded '{variable}' for use in sequential imputation"
)
return data
@validate_call(config=VALIDATE_CONFIG)
def _predict(
self,
X_test: pd.DataFrame,
quantiles: Optional[List[float]] = None,
mean_quantile: Optional[float] = 0.5,
return_probs: bool = False,
) -> Dict[float, pd.DataFrame]:
"""Predict values at specified quantiles using the QRF model.
Args:
X_test: DataFrame containing the test data.
quantiles: List of quantiles to predict (the quantile affects the
center of the beta distribution from which to sample when imputing each data point).
mean_quantile: The mean quantile to used for prediction if
quantiles are not provided.
return_probs: If True, return probability distributions for categorical variables.
Returns:
Dictionary mapping quantiles to predicted values.
If return_probs=True, includes 'probabilities' key.
Raises:
RuntimeError: If prediction fails.
"""
try:
# Create output dictionary with results
imputations: Dict[float, pd.DataFrame] = {}
prob_results = {} if return_probs else None
# Convert single mean_quantile to a list if quantiles not provided
quantiles_to_process = quantiles if quantiles else [mean_quantile]
if quantiles:
self.logger.info(
f"Predicting at {len(quantiles)} quantiles: {quantiles}"
)
else:
self.logger.info(
f"Predicting from a beta distribution centered at quantile: {mean_quantile:.4f}"
)
for q in quantiles_to_process:
imputed_df = pd.DataFrame()
# Create a copy of X_test that we'll augment with imputed values
X_test_augmented = X_test.copy()
self.logger.debug(
f"X_test columns at start of _predict: {X_test_augmented.columns.tolist()}"
)
# Track dummy columns created from imputed categorical variables
imputed_dummy_cols = set()
for i, variable in enumerate(self.imputed_variables):
var_start_time = time.time()
if not quantiles:
self.logger.info(
f"[{i + 1}/{len(self.imputed_variables)}] Predicting for '{variable}'"
)
model = self.models[variable]
# Build predictor set: original predictors + previously imputed variables
var_predictors = _get_sequential_predictors(
self.predictors, self.imputed_variables, i
)
# Get properly encoded predictor columns
encoded_predictors = self._get_encoded_predictors(var_predictors)
self.logger.debug(
f"var_predictors for {variable}: {var_predictors}"
)
self.logger.debug(
f"encoded_predictors for {variable}: {encoded_predictors}"
)
self.logger.debug(
f"Available columns in X_test_augmented: {X_test_augmented.columns.tolist()}"
)
# Ensure we have all needed columns in X_test_augmented
missing_cols = set(encoded_predictors) - set(
X_test_augmented.columns
)
if missing_cols:
# Check if these are dummy columns from previously imputed categorical variables
imputed_missing = missing_cols & imputed_dummy_cols
if imputed_missing:
self.logger.debug(
f"Adding zero-filled columns for missing categories "
f"from imputed variables: {imputed_missing}"
)
# Add zeros for dummy columns from imputed categoricals
for col in imputed_missing:
X_test_augmented[col] = 0.0
# Any other missing columns will cause an error when we try to select them,
# which is the desired behavior to alert the user of missing predictors
# Import constant model
from microimpute.models.imputer import _ConstantValueModel
# Predict using the appropriate predictor set
if isinstance(model, _ConstantValueModel):
# Constant model - just return the constant value
imputed_values = model.predict(X_test_augmented)
elif isinstance(model, _RandomForestClassifierModel):
# Classification for categorical/boolean targets
if return_probs and prob_results is not None:
# Get probabilities and classes
prob_info = model.predict(
X_test_augmented[encoded_predictors],
return_probs=True,
)
prob_results[variable] = prob_info
# Get class predictions
imputed_values = model.predict(
X_test_augmented[encoded_predictors],
return_probs=False,
)
else:
# Regression for numeric targets
imputed_values = model.predict(
X_test_augmented[encoded_predictors],
mean_quantile=q,
)
imputed_df[variable] = imputed_values
# Add the imputed values to X_test_augmented for subsequent variables
X_test_augmented[variable] = imputed_values
# Encode categorical/boolean imputed variable for next iteration
X_test_augmented = self._encode_imputed_variable(
X_test_augmented, variable
)
# Track the dummy columns that were added
if (
self.dummy_processor
and variable in self.dummy_processor.imputed_var_dummy_mapping
):
var_info = self.dummy_processor.imputed_var_dummy_mapping[
variable
]
if var_info["dummy_cols"]:
imputed_dummy_cols.update(var_info["dummy_cols"])
# Log timing for individual variables when not processing multiple quantiles
if not quantiles:
var_time = time.time() - var_start_time
self.logger.info(
f" ✓ {variable} predicted in {var_time:.2f}s ({len(imputed_values)} samples)"
)
self.logger.info(
f"QRF predictions completed for {variable} imputed variable"
)
imputations[q] = imputed_df
# Add probabilities to results if requested
if return_probs and prob_results:
imputations["probabilities"] = prob_results
qs = [k for k in imputations.keys() if k != "probabilities"]
if len(qs) < 2:
q = list(qs)[0]
# If quantiles not provided, decide what to return based on return_probs
if not quantiles:
if return_probs and prob_results:
# Return dict with both quantile predictions and probabilities
return imputations
else:
# Return just the DataFrame for the single quantile
return imputations[q]
else:
# Multiple quantiles requested, return the full dict
return imputations
except Exception as e:
self.logger.error(f"Error during QRF prediction: {str(e)}")
raise RuntimeError(f"Failed to predict with QRF model: {str(e)}") from e
class QRF(Imputer):
"""
Quantile Regression Forest model for imputation.
This model uses a Quantile Random Forest to predict quantiles.
The underlying QRF implementation is from the quantile_forest package.
"""
def __init__(
self,
log_level: Optional[str] = "WARNING",
memory_efficient: bool = False,
batch_size: Optional[int] = None,
cleanup_interval: int = 10,
max_train_samples: Optional[int] = None,
) -> None:
"""Initialize the QRF model.
Args:
log_level: Logging level for the imputer.
memory_efficient: Enable memory optimization features.
batch_size: Process variables in batches to reduce memory usage.
cleanup_interval: Frequency of garbage collection (every N variables).
max_train_samples: If set, subsample X_train to at most this many
rows before fitting. Reduces memory and training time while
preserving sequential covariance structure.
"""
super().__init__(log_level=log_level)
self.models = {}
self.log_level = log_level
self.memory_efficient = memory_efficient
self.batch_size = batch_size
self.cleanup_interval = cleanup_interval
if max_train_samples is not None and max_train_samples < 1:
raise ValueError("max_train_samples must be a positive integer")
self.max_train_samples = max_train_samples
self.logger.debug("Initializing QRF imputer")
if memory_efficient:
self.logger.info(
f"Memory-efficient mode enabled with cleanup_interval={cleanup_interval}"
)
if batch_size:
self.logger.info(
f"Batch processing enabled with batch_size={batch_size}"
)
def _get_encoded_predictors(
self,
current_predictors: List[str],
dummy_processor: Optional[Any] = None,
) -> List[str]:
"""Get properly encoded predictor columns for sequential imputation.
This helper ensures consistent encoding of categorical predictors across
all code paths (batch, non-batch, hyperparameter tuning, etc.).
Args:
current_predictors: List of predictor variable names
dummy_processor: Optional DummyVariableProcessor instance
Returns:
List of encoded predictor column names
"""
if dummy_processor is None:
dummy_processor = getattr(self, "dummy_processor", None)
if dummy_processor:
return dummy_processor.get_sequential_predictor_columns(current_predictors)
else:
return current_predictors
def _encode_imputed_variable(
self,
data: pd.DataFrame,
variable: str,
dummy_processor: Optional[Any] = None,
) -> pd.DataFrame:
"""Encode a categorical imputed variable for use as predictor in subsequent iterations.
This helper ensures consistent encoding of imputed categorical variables
across all code paths.
Args:
data: DataFrame containing the imputed variable
variable: Name of the variable that was just imputed
dummy_processor: Optional DummyVariableProcessor instance
Returns:
DataFrame with encoded variable (adds dummy columns if categorical)
"""
if dummy_processor is None:
dummy_processor = getattr(self, "dummy_processor", None)
if dummy_processor and variable in dummy_processor.imputed_var_dummy_mapping:
data = dummy_processor.sequential_imputed_predictor_encoding(data, variable)
self.logger.debug(
f" Encoded '{variable}' for use in sequential imputation"
)
return data
def _create_model_for_variable(self, variable: str, **kwargs) -> Any:
"""Create the appropriate model (classifier or regressor) based on variable type."""
categorical_targets = getattr(self, "categorical_targets", {})
boolean_targets = getattr(self, "boolean_targets", {})
if variable in categorical_targets:
# Use classifier for categorical targets
return _RandomForestClassifierModel(seed=self.seed, logger=self.logger)
elif variable in boolean_targets:
# Use classifier for boolean targets
return _RandomForestClassifierModel(seed=self.seed, logger=self.logger)
else:
# Use QRF for numeric targets
return _QRFModel(seed=self.seed, logger=self.logger)
def _fit_model(
self,
model: Any,
X: pd.DataFrame,
y: pd.Series,
variable: str,
**kwargs,
) -> None:
"""Fit the model with appropriate parameters based on variable type."""
categorical_targets = getattr(self, "categorical_targets", {})
boolean_targets = getattr(self, "boolean_targets", {})
# Extract appropriate parameters based on model type
# Handle nested structure from hyperparameter tuning
if isinstance(model, _RandomForestClassifierModel):
# Use RFC params if they exist in a nested structure
if "rfc" in kwargs:
model_params = kwargs["rfc"]
elif "qrf" in kwargs:
# Mixed case: only QRF params available, use defaults for RFC
model_params = {}
else:
# Flat dict: use all kwargs (backward compatible)
model_params = kwargs
if variable in categorical_targets:
model.fit(
X,
y,
var_type=categorical_targets[variable]["type"],
categories=categorical_targets[variable].get("categories"),
**model_params,
)
elif variable in boolean_targets:
model.fit(X, y, var_type="boolean", **model_params)
else:
# Use QRF params if they exist in a nested structure
if "qrf" in kwargs:
model_params = kwargs["qrf"]
elif "rfc" in kwargs:
# Mixed case: only RFC params available, use defaults for QRF
model_params = {}
else:
# Flat dict: use all kwargs (backward compatible)
model_params = kwargs
# Regular QRF fit
model.fit(X, y, **model_params)
def _get_memory_usage_info(self) -> str:
"""Get formatted memory usage information."""
if PSUTIL_AVAILABLE:
process = psutil.Process()
memory_mb = process.memory_info().rss / 1024 / 1024
return f"{memory_mb:.1f}MB"
return "N/A"
@validate_call(config=VALIDATE_CONFIG)
def _fit(
self,
X_train: pd.DataFrame,
predictors: List[str],
imputed_variables: List[str],
original_predictors: Optional[List[str]] = None,
categorical_targets: Optional[Dict[str, Dict]] = None,
boolean_targets: Optional[Dict[str, Dict]] = None,
numeric_targets: Optional[List[str]] = None,
constant_targets: Optional[Dict[str, Dict]] = None,
tune_hyperparameters: bool = False,
**qrf_kwargs: Any,
) -> QRFResults:
"""Fit the QRF model to the training data.
Args:
X_train: DataFrame containing the training data.
predictors: List of column names to use as predictors.
imputed_variables: List of column names to impute.
**qrf_kwargs: Additional keyword arguments to pass to QRF.
Returns:
The fitted model instance.
Raises:
RuntimeError: If model fitting fails.
"""
try:
# Subsample training data if max_train_samples is set
if (
self.max_train_samples is not None
and len(X_train) > self.max_train_samples
):
self.logger.info(
f"Subsampling training data from "
f"{len(X_train)} to {self.max_train_samples} rows"
)
X_train = X_train.sample(
n=self.max_train_samples,
random_state=self.seed,
).reset_index(drop=True)
# Store target type information early for hyperparameter tuning
self.categorical_targets = categorical_targets or {}
self.boolean_targets = boolean_targets or {}
self.numeric_targets = numeric_targets or []
self.constant_targets = constant_targets or {}
self.imputed_variables = imputed_variables
if tune_hyperparameters:
try:
qrf_kwargs = self._tune_hyperparameters(
data=X_train,
predictors=predictors,
imputed_variables=imputed_variables,
)
# Initialize and fit a QRF model for each variable
self.logger.info(
f"Training data shape: {X_train.shape}, Memory usage: {self._get_memory_usage_info()}"
)
# Handle batch processing if enabled
if self.batch_size and len(imputed_variables) > self.batch_size:
self.logger.info(
f"Processing {len(imputed_variables)} variables in batches of {self.batch_size}"
)
variable_batches = [
imputed_variables[i : i + self.batch_size]
for i in range(0, len(imputed_variables), self.batch_size)
]
for batch_idx, batch_variables in enumerate(variable_batches):
self.logger.info(
f"Processing batch {batch_idx + 1}/{len(variable_batches)} "
f"({len(batch_variables)} variables)"
)
self._fit_variable_batch(
X_train,
predictors,
imputed_variables,
batch_variables,
qrf_kwargs,
constant_targets,
)
# Memory cleanup after each batch
if self.memory_efficient:
gc.collect()
self.logger.info(
f"Batch {batch_idx + 1} completed. Memory usage: {self._get_memory_usage_info()}"
)
else:
# Process all variables sequentially
# Import constant model
from microimpute.models.imputer import (
_ConstantValueModel,
)
for i, variable in enumerate(imputed_variables):
var_start_time = time.time()
# Handle constant targets
if variable in (constant_targets or {}):
constant_val = constant_targets[variable]["value"]
self.models[variable] = _ConstantValueModel(
constant_val, variable
)
self.logger.info(
f"Using constant value {constant_val} for variable {variable}"
)
continue
# Build predictor set: original predictors + previously imputed variables
current_predictors = _get_sequential_predictors(
predictors, imputed_variables, i
)
# Get properly encoded predictor columns
dummy_processor = getattr(self, "dummy_processor", None)
encoded_predictors = self._get_encoded_predictors(
current_predictors, dummy_processor
)
# Log detailed pre-imputation information
self.logger.info(
f"[{i + 1}/{len(imputed_variables)}] Starting imputation for '{variable}'"
)
self.logger.info(
f" Features: {len(encoded_predictors)} predictors"
)
self.logger.info(
f" Memory usage: {self._get_memory_usage_info()}"
)
# Create appropriate model based on variable type
model = self._create_model_for_variable(variable)
self._fit_model(
model,
X_train[encoded_predictors],
X_train[variable],
variable,
**qrf_kwargs,
)
try:
# Log post-imputation information
var_time = time.time() - var_start_time
self.logger.info(
f" ✓ Success: {variable} fitted in {var_time:.2f}s"
)
# Get model complexity metrics if available
if hasattr(model, "qrf") and hasattr(
model.qrf, "n_estimators"
):
self.logger.info(
f" Model complexity: {model.qrf.n_estimators} trees"
)
elif hasattr(model, "classifier") and hasattr(
model.classifier, "n_estimators"
):
self.logger.info(
f" Model complexity: {model.classifier.n_estimators} trees (classifier)"
)
self.models[variable] = model
# Encode categorical/boolean imputed variable for next iteration
X_train = self._encode_imputed_variable(
X_train, variable, dummy_processor
)
except Exception as e:
self.logger.error(f" ✗ Failed: {variable} - {str(e)}")
raise
# Memory cleanup if enabled
if (
self.memory_efficient
and (i + 1) % self.cleanup_interval == 0
):
gc.collect()
self.logger.debug(
f" Memory cleanup performed. Usage: {self._get_memory_usage_info()}"
)
return (
QRFResults(
models=self.models,
predictors=predictors,
imputed_variables=imputed_variables,
imputed_vars_dummy_info=self.imputed_vars_dummy_info,
original_predictors=self.original_predictors,
categorical_targets=categorical_targets,
boolean_targets=boolean_targets,
constant_targets=constant_targets,
dummy_processor=getattr(self, "dummy_processor", None),
seed=self.seed,
),
qrf_kwargs,
)
except Exception as e:
self.logger.error(f"Error tuning hyperparameters: {str(e)}")
raise RuntimeError(
f"Failed to tune hyperparameters: {str(e)}"
) from e
else:
self.logger.info(
f"Fitting QRF model with {len(predictors)} predictors and "
f"optional parameters: {qrf_kwargs}"
)
self.logger.info(
f"Training data shape: {X_train.shape}, Memory usage: {self._get_memory_usage_info()}"
)
# Handle batch processing if enabled
if self.batch_size and len(imputed_variables) > self.batch_size:
self.logger.info(
f"Processing {len(imputed_variables)} variables in batches of {self.batch_size}"
)
variable_batches = [
imputed_variables[i : i + self.batch_size]
for i in range(0, len(imputed_variables), self.batch_size)
]
for batch_idx, batch_variables in enumerate(variable_batches):
self.logger.info(
f"Processing batch {batch_idx + 1}/{len(variable_batches)} "
f"({len(batch_variables)} variables)"
)
self._fit_variable_batch(
X_train,
predictors,
imputed_variables,
batch_variables,
qrf_kwargs,
constant_targets,
)
# Memory cleanup after each batch
if self.memory_efficient:
gc.collect()
self.logger.info(
f"Batch {batch_idx + 1} completed. Memory usage: {self._get_memory_usage_info()}"
)
else:
# Process all variables sequentially
# Import constant model
from microimpute.models.imputer import _ConstantValueModel
# Initialize and fit a QRF model for each variable
for i, variable in enumerate(imputed_variables):
var_start_time = time.time()
# Handle constant targets
if variable in (constant_targets or {}):
constant_val = constant_targets[variable]["value"]
self.models[variable] = _ConstantValueModel(
constant_val, variable
)
self.logger.info(
f"Using constant value {constant_val} for variable {variable}"
)
continue
# Build predictor set: original predictors + previously imputed variables
current_predictors = _get_sequential_predictors(
predictors, imputed_variables, i
)
# Get properly encoded predictor columns
dummy_processor = getattr(self, "dummy_processor", None)
encoded_predictors = self._get_encoded_predictors(
current_predictors, dummy_processor
)
# Log detailed pre-imputation information
self.logger.info(
f"[{i + 1}/{len(imputed_variables)}] Starting imputation for '{variable}'"
)
self.logger.info(
f" Features: {len(encoded_predictors)} predictors"
)
self.logger.info(
f" Memory usage: {self._get_memory_usage_info()}"
)
# Create and fit model
model = self._create_model_for_variable(variable)
try:
self._fit_model(
model,
X_train[encoded_predictors],
X_train[variable],
variable,
**qrf_kwargs,
)
# Log post-imputation information
var_time = time.time() - var_start_time
self.logger.info(
f" ✓ Success: {variable} fitted in {var_time:.2f}s"
)
# Get model complexity metrics if available
if hasattr(model, "qrf") and hasattr(
model.qrf, "n_estimators"
):
self.logger.info(
f" Model complexity: {model.qrf.n_estimators} trees"
)
elif hasattr(model, "classifier") and hasattr(
model.classifier, "n_estimators"
):
self.logger.info(
f" Model complexity: {model.classifier.n_estimators} trees (classifier)"
)
self.models[variable] = model
# Encode categorical/boolean imputed variable for next iteration
X_train = self._encode_imputed_variable(
X_train, variable, dummy_processor
)
except Exception as e:
self.logger.error(f" ✗ Failed: {variable} - {str(e)}")
raise
# Memory cleanup if enabled
if (
self.memory_efficient
and (i + 1) % self.cleanup_interval == 0
):
gc.collect()
self.logger.debug(
f" Memory cleanup performed. Usage: {self._get_memory_usage_info()}"
)
# Final memory cleanup if enabled
if self.memory_efficient:
gc.collect()