-
Notifications
You must be signed in to change notification settings - Fork 9
/
sk_model.py
1007 lines (879 loc) · 39 KB
/
sk_model.py
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
"""Scikit-learn model wrapper."""
import logging
import os
from functools import wraps
from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Union
import numpy as np
from datasets import Dataset, DatasetDict
from datasets.combine import concatenate_datasets
from numpy.typing import ArrayLike
from scipy.sparse import issparse
from sklearn.base import BaseEstimator as SKBaseEstimator
from sklearn.base import TransformerMixin
from sklearn.exceptions import NotFittedError
from sklearn.model_selection import GridSearchCV, PredefinedSplit, RandomizedSearchCV
from sklearn.pipeline import Pipeline
from cyclops.data.utils import is_out_of_core
from cyclops.models.utils import get_split, is_sklearn_class, is_sklearn_instance
from cyclops.models.wrappers.utils import DatasetColumn
from cyclops.utils.file import join, load_pickle, process_dir_save_path, save_pickle
from cyclops.utils.log import setup_logging
LOGGER = logging.getLogger(__name__)
setup_logging(print_level="INFO", logger=LOGGER)
class SKModel:
"""Scikit-learn model wrapper.
Parameters
----------
model : sklearn.base.BaseEstimator
Scikit-learn model instance or class.
model_params: dict
Scikit-learn estimator parameters
batch_size: int, optional
The batch size used when using Hugging Face Dataset, \
by default 64
**kwargs : dict, optional
Additional keyword arguments to pass to model.
Notes
-----
This wrapper does not inherit from models.wrappers.base.ModelWrapper
because it uses the decorator pattern to expose the sklearn API, which
is what the base wrapper is meant to abstract away.
"""
def __init__(
self,
model: SKBaseEstimator,
**params: Dict[str, Any],
) -> None:
"""Initialize wrapper."""
self.model = model # possibly uninstantiated class
self.batch_size = params.pop("batch_size", 64)
self.initialize_model(**params)
@property
def model_name(self) -> str:
"""Model name.
Returns
-------
str
Model name.
"""
return self.model_.__class__.__name__
def initialize_model(self, **kwargs):
"""Initialize model.
Parameters
----------
kwargs : dict, optional
Additional keyword arguments to pass to model.
Returns
-------
self
Raises
------
ValueError
If model is not an sklearn model instance or class.
"""
if is_sklearn_instance(self.model) and not kwargs:
self.model_ = self.model
elif is_sklearn_instance(self.model) and kwargs:
self.model_ = type(self.model)(**kwargs)
elif is_sklearn_class(self.model):
self.model_ = self.model(**kwargs)
else:
raise ValueError("Model must be an sklearn model instance or class.")
return self
def find_best( # noqa: PLR0912, PLR0915
self,
parameters: Union[Dict, List[Dict]],
X: Union[ArrayLike, Dataset, DatasetDict],
y: Optional[ArrayLike] = None,
feature_columns: Optional[Union[str, List[str]]] = None,
target_columns: Optional[Union[str, List[str]]] = None,
transforms: Optional[Union[Pipeline, TransformerMixin, Callable]] = None,
metric: Optional[Union[str, Callable, Sequence, Dict]] = None,
method: Literal["grid", "random"] = "grid",
splits_mapping: dict = None,
**kwargs,
):
"""Search on hyper parameters.
Parameters
----------
parameters : dict or list of dicts
The hyperparameters to be tuned.
X : Union[Dataset, ArrayLike]
The data features or a Hugging Face dataset containing features and labels.
y : Optional[ArrayLike], optional
The labels of the data. This is required when the input dataset is not \
a huggingface dataset and only contains features, by default None
feature_columns : Optional[Union[str, List[str]]], optional
List of feature columns in the dataset. This is required when the input is \
a Hugging Face Dataset, by default None
target_columns : Optional[Union[str, List[str]]], optional
List of target columns in the dataset. This is required when the input is \
a Hugging Face Dataset, by default None
transforms : Optional[Union[Pipeline, TransformerMixin, Callable]], optional
The transformation to be applied to the data before prediction, \
This is used when the input is a Hugging Face Dataset, \
by default None
metric : str, callable, sequence, dict, optional
The metric to be used for model evaluation.
method : Literal["grid", "random"], default="grid"
The tuning method to be used.
splits_mapping: Optional[dict], optional
Mapping from 'train', 'validation' and 'test' to dataset splits names, \
used when input is a dataset dictionary,
by default {"train": "train", "validation": "validation"}
**kwargs : dict, optional
Additional keyword arguments to be passed to the search method.
Returns
-------
self : `SKModel`
Raises
------
ValueError
If search method is not supported.
ValueError
If `X` is a Hugging Face Dataset and the feature column(s) is not provided.
ValueError
If `X` is a Hugging Face Dataset and the target column(s) is not provided.
RuntimeError
If dataset size is larger than the available memory.
"""
# TODO: check the `metric` argument; allow using cyclops.evaluate.metrics
# TODO: allow passing group
if splits_mapping is None:
splits_mapping = {"train": "train", "validation": "validation"}
if method == "grid":
clf = GridSearchCV(
estimator=self.model_,
param_grid=parameters,
scoring=metric,
**kwargs,
)
elif method == "random":
clf = RandomizedSearchCV(
estimator=self.model_,
param_distributions=parameters,
scoring=metric,
**kwargs,
)
else:
raise ValueError("Method must be either 'grid' or 'random'.")
if isinstance(X, (Dataset, DatasetDict)):
if feature_columns is None:
raise ValueError(
"Missing target columns 'feature_columns'. Please provide \
the name of feature columns when using a \
Hugging Face dataset as the input.",
)
if isinstance(feature_columns, str):
feature_columns = [feature_columns]
if target_columns is None:
raise ValueError(
"Missing target columns 'target_columns'. Please provide \
the name of target columns when using a \
Hugging Face dataset as the input.",
)
if isinstance(target_columns, str):
target_columns = [target_columns]
if isinstance(X, DatasetDict):
train_split = get_split(X, "train", splits_mapping)
try:
val_split = get_split(X, "validation", splits_mapping)
except ValueError:
LOGGER.info("No validation split was found.")
val_split = None
if val_split is None:
return self.find_best(
parameters,
X[train_split],
feature_columns=feature_columns,
target_columns=target_columns,
transforms=transforms,
metric=metric,
method=method,
)
if X[train_split].dataset_size is not None and is_out_of_core(
X[train_split].dataset_size,
):
raise RuntimeError("Dataset size cannot fit into memory!")
format_kwargs = {}
is_callable_transform = callable(transforms)
if is_callable_transform:
format_kwargs["transform"] = transforms
with X[train_split].formatted_as(
"custom" if is_callable_transform else "numpy",
columns=feature_columns + target_columns,
**format_kwargs,
):
X_train = np.stack(
[X[train_split][feature] for feature in feature_columns],
axis=1,
).squeeze()
if transforms is not None and not is_callable_transform:
try:
X_train = transforms.transform(X_train)
except NotFittedError:
X_train = transforms.fit_transform(X_train)
y_train = np.stack(
[X[train_split][target] for target in target_columns],
axis=1,
).squeeze()
if issparse(X_train):
X_train = X_train.toarray()
with X[val_split].formatted_as(
"custom" if is_callable_transform else "numpy",
columns=feature_columns + target_columns,
**format_kwargs,
):
X_val = np.stack(
[X[val_split][feature] for feature in feature_columns],
axis=1,
).squeeze()
if transforms is not None and not is_callable_transform:
try:
X_val = transforms.transform(X_val)
except NotFittedError:
X_val = transforms.fit_transform(X_val)
y_val = np.stack(
[X[val_split][target] for target in target_columns],
axis=1,
).squeeze()
if issparse(X_val):
X_val = X_val.toarray()
split_index = [-1] * len(X_train) + [0] * len(X_val)
X = np.concatenate((X_train, X_val), axis=0)
y = np.concatenate((y_train, y_val), axis=0)
clf.cv = PredefinedSplit(test_fold=split_index)
clf.fit(X, y)
elif isinstance(X, Dataset):
if X.dataset_size is not None and is_out_of_core(X.dataset_size):
raise RuntimeError("Dataset size cannot fit into memory!")
format_kwargs = {}
is_callable_transform = callable(transforms)
if is_callable_transform:
format_kwargs["transform"] = transforms
with X.formatted_as(
"custom" if is_callable_transform else "numpy",
columns=feature_columns + target_columns,
**format_kwargs,
):
X_train = np.stack(
[X[feature] for feature in feature_columns],
axis=1,
).squeeze()
y_train = np.stack(
[X[target] for target in target_columns],
axis=1,
).squeeze()
if transforms is not None and not is_callable_transform:
if isinstance(transforms, Pipeline):
transforms.steps.append(("clf", clf))
clf = transforms
else:
clf = Pipeline(
[
("transform", transforms),
("clf", clf),
],
)
if issparse(X_train):
X_train = X_train.toarray()
clf.fit(X_train, y_train)
else:
if y is None:
LOGGER.warning(
"Missing data labels 'y'. Please provide the labels \
for supervised training when not using a \
Hugging Face dataset as the input.",
)
clf.fit(X, y)
if isinstance(clf, Pipeline):
clf = clf["clf"]
for key, value in clf.best_params_.items():
LOGGER.info("Best %s: %s", key, value)
self.model_ = clf.best_estimator_
return self
def partial_fit(
self,
X: Union[ArrayLike, Dataset, DatasetDict],
y: Optional[ArrayLike] = None,
feature_columns: Optional[Union[str, List[str]]] = None,
target_columns: Optional[Union[str, List[str]]] = None,
transforms: Optional[Union[Pipeline, TransformerMixin, Callable]] = None,
classes: Optional[np.ndarray] = None,
splits_mapping: dict = None,
**kwargs,
):
"""Fit the model to the data incrementally.
Parameters
----------
X : Union[Dataset, ArrayLike]
The data features or Hugging Face dataset containing features and labels.
y : Optional[ArrayLike], optional
The labels of the data. This is required when the input dataset is not \
a huggingface dataset and only contains features, by default None
feature_columns : Optional[Union[str, List[str]]], optional
List of feature columns in the dataset. This is required when \
the input is a Hugging Face Dataset, by default None
target_columns : Optional[Union[str, List[str]]], optional
List of target columns in the dataset. This is required when \
the input is a Hugging Face Dataset, by default None
transforms : Optional[Union[Pipeline, TransformerMixin, Callable]], optional
The transformation to be applied to the data before prediction, \
This is used when the input is a Hugging Face Dataset, \
by default None
classes : Optional[np.ndarray], optional
All the possible classes in the dataset. This is required when \
the input dataset is not a huggingface dataset and \
only contains features, by default None
splits_mapping: Optional[dict], optional
Mapping from 'train', 'validation' and 'test' to dataset splits names, \
used when input is a dataset dictionary, by default {"train": "train"}
Returns
-------
self: `SKModel`
Raises
------
AttributeError
Model does not have partial_fit method.
ValueError
If `X` is a Hugging Face Dataset and the feature column(s) is not provided.
ValueError
If `X` is a Hugging Face Dataset and the target column(s) is not provided.
"""
if splits_mapping is None:
splits_mapping = {"train": "train"}
if not hasattr(self.model_, "partial_fit"):
raise AttributeError(
f"Model {self.model_name}" "does not have a `partial_fit` method.",
)
# Train data is a Hugging Face Dataset Dictionary.
if isinstance(X, DatasetDict):
train_split = get_split(X, "train", splits_mapping=splits_mapping)
return self.fit(
X[train_split],
feature_columns=feature_columns,
target_columns=target_columns,
transforms=transforms,
classes=classes,
)
# Train data is a Hugging Face Dataset.
if isinstance(X, Dataset):
if feature_columns is None:
raise ValueError(
"Missing feature columns 'feature_columns'. Please provide \
the name of feature columns when using a \
Hugging Face dataset as the input.",
)
if isinstance(feature_columns, str):
feature_columns = [feature_columns]
if target_columns is None:
raise ValueError(
"Missing target columns 'target_columns'. Please provide \
the name of target columns when using a \
Hugging Face dataset as the input.",
)
if isinstance(target_columns, str):
target_columns = [target_columns]
format_kwargs = {}
is_callable_transform = callable(transforms)
if is_callable_transform:
format_kwargs["transform"] = transforms
def fit_model(examples):
X_train = np.stack(
[examples[feature] for feature in feature_columns],
axis=1,
).squeeze()
if transforms is not None and not is_callable_transform:
try:
X_train = transforms.transform(X_train)
except NotFittedError:
LOGGER.warning(
"Fitting preprocessor on batch of size %d",
len(X_train),
)
X_train = transforms.fit_transform(X_train)
y_train = np.stack(
[examples[target] for target in target_columns],
axis=1,
).squeeze()
self.model_.partial_fit(
X_train,
y_train,
classes=np.unique(y_train),
**kwargs,
)
return examples
with X.formatted_as(
"custom" if is_callable_transform else "numpy",
columns=feature_columns + target_columns,
**format_kwargs,
):
X.map(
fit_model,
batched=True,
batch_size=self.batch_size,
)
# Train data is not a Hugging Face Dataset.
else:
if y is None:
LOGGER.warning(
"Missing data labels 'y'. Please provide the labels \
for supervised training when not using a \
Hugging Face dataset as the input.",
)
if classes is None:
LOGGER.warning(
"Missing unique class labels. Please provide a list of classes \
when using a numpy array or pandas dataframe as the input.",
)
self.model_.partial_fit(X, y, classes=classes, **kwargs)
return self
def fit( # noqa: PLR0912
self,
X: Union[ArrayLike, Dataset, DatasetDict],
y: Optional[ArrayLike] = None,
feature_columns: Optional[Union[str, List[str]]] = None,
target_columns: Optional[Union[str, List[str]]] = None,
transforms: Optional[Union[Pipeline, TransformerMixin, Callable]] = None,
splits_mapping: dict = None,
dim_reduction: bool = False,
**fit_params,
):
"""Fit the model.
Parameters
----------
X : Union[Dataset, ArrayLike]
The data features or a Hugging Face dataset containing features and labels.
y : Optional[ArrayLike], optional
The labels of the data. This is required when the input dataset is not \
a huggingface dataset and only contains features, by default None
feature_columns : Optional[Union[str, List[str]]], optional
List of feature columns in the dataset. This is required when the input is \
a Hugging Face Dataset, by default None
target_columns : Optional[Union[str, List[str]]], optional
List of target columns in the dataset. This is required when \
the input is a Hugging Face Dataset, by default None
transforms : Optional[Union[Pipeline, TransformerMixin, Callable]], optional
The transformation to be applied to the data before prediction,
This is used when the input is a Hugging Face Dataset, \
by default None
splits_mapping: Optional[dict], optional
Mapping from 'train', 'validation' and 'test' to dataset splits names, \
used when input is a dataset dictionary, by default {"train": "train"}
dim_reduction: bool, default=False
Whether the model is used for dimensionality reduction or prediction, \
Used when SKModel uses fit_transform instead of fit_predict and no labels
are expected.
Returns
-------
self : `SKModel`
Raises
------
ValueError
If `X` is a Hugging Face Dataset and the feature column(s) is not provided.
ValueError
If `X` is a Hugging Face Dataset and the target column(s) is not provided.
"""
# Train data is a Hugging Face Dataset Dictionary.
if splits_mapping is None:
splits_mapping = {"train": "train"}
if isinstance(X, DatasetDict):
train_split = get_split(X, "train", splits_mapping=splits_mapping)
return self.fit(
X[train_split],
feature_columns=feature_columns,
target_columns=target_columns,
transforms=transforms,
)
# Train data is a Hugging Face Dataset.
if isinstance(X, Dataset):
if feature_columns is None:
raise ValueError(
"Missing feature columns 'feature_columns'. Please provide \
the name of feature columns when using a \
Hugging Face dataset as the input.",
)
if isinstance(feature_columns, str):
feature_columns = [feature_columns]
if target_columns is None and not dim_reduction:
raise ValueError(
"Missing target columns 'target_columns'. Please provide \
the name of target columns when using a \
Hugging Face dataset as the input.",
)
if isinstance(target_columns, str):
target_columns = [target_columns]
if X.dataset_size is not None and is_out_of_core(X.dataset_size):
LOGGER.warning(
"Dataset size cannot fit into memory. Will call partial fit.",
)
return self.partial_fit(
X,
feature_columns=feature_columns,
target_columns=target_columns,
transforms=transforms,
)
format_kwargs = {}
is_callable_transform = callable(transforms)
if is_callable_transform:
format_kwargs["transform"] = transforms
with X.formatted_as(
"custom" if is_callable_transform else "numpy",
columns=feature_columns + target_columns
if not dim_reduction
else feature_columns,
**format_kwargs,
):
X_train = np.stack(
[X[feature] for feature in feature_columns],
axis=1,
).squeeze()
if transforms is not None and not is_callable_transform:
try:
X_train = transforms.transform(X_train)
except NotFittedError:
X_train = transforms.fit_transform(X_train)
if not dim_reduction:
y_train = np.stack(
[X[target] for target in target_columns],
axis=1,
).squeeze()
else:
y_train = None
if issparse(X_train):
X_train = X_train.toarray()
self.fit(X_train, y_train, **fit_params)
# Train data is not a Hugging Face Dataset.
else:
if y is None and not dim_reduction:
LOGGER.warning(
"Missing data labels 'y'. Please provide the labels \
for supervised training when not using a \
Hugging Face dataset as the input.",
)
self.model_ = self.model_.fit(X, y, **fit_params)
return self
def predict_proba(
self,
X: Union[ArrayLike, Dataset, DatasetDict],
feature_columns: Optional[Union[str, List[str]]] = None,
prediction_column_prefix: str = "predictions",
model_name: Optional[str] = None,
transforms: Optional[Union[Pipeline, TransformerMixin, Callable]] = None,
only_predictions: bool = False,
splits_mapping: dict = None,
) -> Union[Dataset, DatasetColumn, np.ndarray]:
"""Predict the probability output of the model.
Parameters
----------
X : Dataset
The data features or Hugging Face dataset containing features and labels.
feature_columns : Optional[Union[str, List[str]]], optional
List of feature columns in the dataset. This is required when the input is \
a Hugging Face Dataset, by default None
prediction_column_prefix : str, optional
Name of the prediction column to be added to the dataset, This is used \
when the input is a Hugging Face Dataset, by default "predictions"
model_name : Optional[str], optional
Model name used as suffix to the prediction column, This is used \
when the input is a Hugging Face Dataset, by default None
transforms : Optional[Callable], optional
The transformation to be applied to the data before prediction, \
This is used when the input is a Hugging Face Dataset, \
by default None
only_predictions : bool, optional
Whether to return only the predictions rather than the dataset \
with predictions when the input is a Hugging Face Dataset, \
by default False
splits_mapping: Optional[dict], optional
Mapping from 'train', 'validation' and 'test' to dataset splits names, \
used when input is a dataset dictionary, by default {"test": "test"}
Returns
-------
Union[Dataset, DatasetColumn, np.ndarray]
Dataset containing the predictions or the predictions array.
Raises
------
AttributeError
If model does not have predict_proba method.
ValueError
If `X` is a Hugging Face Dataset and the feature column(s) is not provided.
"""
if splits_mapping is None:
splits_mapping = {"test": "test"}
if not hasattr(self.model_, "predict_proba"):
raise AttributeError(
f"Model {self.model_name}" "does not have a `predict_proba` method.",
)
# Data is a Hugging Face Dataset Dictionary.
if isinstance(X, DatasetDict):
test_split = get_split(X, "test", splits_mapping=splits_mapping)
return self.predict_proba(
X[test_split],
feature_columns=feature_columns,
prediction_column_prefix=prediction_column_prefix,
model_name=model_name,
transforms=transforms,
only_predictions=only_predictions,
)
# Data is a Hugging Face Dataset.
if isinstance(X, Dataset):
if feature_columns is None:
raise ValueError(
"Missing feature columns 'feature_columns'. Please provide \
the name of feature columns when using a \
Hugging Face dataset as the input.",
)
if isinstance(feature_columns, str):
feature_columns = [feature_columns]
if model_name:
pred_column = f"{prediction_column_prefix}.{model_name}"
else:
pred_column = f"{prediction_column_prefix}.{self.model_name}"
format_kwargs = {}
is_callable_transform = callable(transforms)
if is_callable_transform:
format_kwargs["transform"] = transforms
def get_predictions(examples: Dict[str, Union[List, np.ndarray]]) -> dict:
X_eval = np.stack(
[examples[feature] for feature in feature_columns],
axis=1,
)
if transforms is not None and not is_callable_transform:
try:
X_eval = transforms.transform(X_eval)
except NotFittedError:
LOGGER.warning("Fitting preprocessor on evaluation data.")
X_eval = transforms.fit_transform(X_eval)
predictions = self.predict_proba(X_eval)
return {pred_column: predictions}
with X.formatted_as(
"custom" if is_callable_transform else "numpy",
columns=feature_columns,
output_all_columns=True,
**format_kwargs,
):
pred_ds = X.map(
get_predictions,
batched=True,
batch_size=self.batch_size,
remove_columns=X.column_names,
)
if only_predictions:
return DatasetColumn(pred_ds.with_format("numpy"), pred_column)
return concatenate_datasets([X, pred_ds], axis=1)
# Data is not a Hugging Face Dataset.
return self.model_.predict_proba(X)
def predict(
self,
X: Union[ArrayLike, Dataset],
feature_columns: Optional[Union[str, List[str]]] = None,
prediction_column_prefix: str = "predictions",
model_name: Optional[str] = None,
transforms: Optional[Union[Pipeline, TransformerMixin, Callable]] = None,
only_predictions: bool = False,
splits_mapping: dict = None,
dim_reduction: bool = False,
) -> Union[Dataset, DatasetColumn, np.ndarray]:
"""Predict the output of the model.
Parameters
----------
X : Dataset
The data features or Hugging Face dataset containing features and labels.
feature_columns : Optional[Union[str, List[str]]], optional
List of feature columns in the dataset. This is required when the input is \
a Hugging Face Dataset, by default None
prediction_column_prefix : str, optional
Name of the prediction column to be added to the dataset, This is used \
when the input is a Hugging Face Dataset, by default "predictions"
model_name : Optional[str], optional
Model name used as suffix to the prediction column, This is used \
when the input is a Hugging Face Dataset, by default None
transforms : Optional[Callable], optional
The transformation to be applied to the data before prediction, \
This is used when the input is a Hugging Face Dataset, \
by default None
only_predictions : bool, optional
Whether to return only the predictions rather than the dataset \
with predictions when the input is a Hugging Face Dataset, \
by default False
splits_mapping: Optional[dict], optional
Mapping from 'train', 'validation' and 'test' to dataset splits names, \
used when input is a dataset dictionary, by default {"test": "test"}
dim_reduction: bool, default=False
Whether the model is used for dimensionality reduction or prediction, \
Used when SKModel uses fit_transform instead of fit_predict and no labels
are expected.
Returns
-------
Union[Dataset, DatasetColumn, np.ndarray]
Dataset containing the predictions or the predictions array.
Raises
------
ValueError
If `X` is a Hugging Face Dataset and the feature column(s) is not provided.
"""
# Data is a Hugging Face Dataset Dictionary.
if splits_mapping is None:
splits_mapping = {"test": "test"}
if isinstance(X, DatasetDict):
test_split = get_split(X, "test", splits_mapping=splits_mapping)
return self.predict(
X[test_split],
feature_columns=feature_columns,
prediction_column_prefix=prediction_column_prefix,
model_name=model_name,
transforms=transforms,
only_predictions=only_predictions,
)
# Data is a Hugging Face Dataset.
if isinstance(X, Dataset):
if feature_columns is None:
raise ValueError(
"Missing feature columns 'feature_columns'. Please provide \
the name of feature columns when using a \
Hugging Face dataset as the input.",
)
if isinstance(feature_columns, str):
feature_columns = [feature_columns]
if model_name:
pred_column = f"{prediction_column_prefix}.{model_name}"
else:
pred_column = f"{prediction_column_prefix}.{self.model_name}"
format_kwargs = {}
is_callable_transform = callable(transforms)
if is_callable_transform:
format_kwargs["transform"] = transforms
def get_predictions(examples: Dict[str, Union[List, np.ndarray]]) -> dict:
X_eval = np.stack(
[examples[feature] for feature in feature_columns],
axis=1,
)
if transforms is not None and not is_callable_transform:
try:
X_eval = transforms.transform(X_eval)
except NotFittedError:
LOGGER.warning("Fitting preprocessor on evaluation data.")
X_eval = transforms.fit_transform(X_eval)
if not dim_reduction:
predictions = self.predict(X_eval)
else:
predictions = self.transform(X_eval)
return {pred_column: predictions}
with X.formatted_as(
"custom" if is_callable_transform else "numpy",
columns=feature_columns,
output_all_columns=True,
**format_kwargs,
):
pred_ds = X.map(
get_predictions,
batched=True,
batch_size=self.batch_size,
remove_columns=X.column_names,
)
if only_predictions:
return DatasetColumn(pred_ds.with_format("numpy"), pred_column)
return concatenate_datasets([X, pred_ds], axis=1)
# Data is not a Hugging Face Dataset.
if not dim_reduction:
output = self.model_.predict(X)
else:
output = self.model_.transform(X)
return output
def save_model(self, filepath: str, overwrite: bool = True, **kwargs) -> str:
"""Save model to file.
Parameters
----------
filepath : str
The path to save the model.
overwrite : bool, optional
Whether to overwrite the existing model, by default True
**kwargs : dict, optional
Additional keyword arguments to be passed to the save function.
Returns
-------
str
The path to the saved model.
"""
# filepath could be a directory
if len(os.path.basename(filepath).split(".")) == 1:
process_dir_save_path(filepath)
if os.path.isdir(filepath):
filepath = join(filepath, self.model_name, "model.pkl")
# filepath could be a file
dir_path = os.path.dirname(filepath)
if dir_path == "":
dir_path = f"./{self.model_name}"
filepath = join(dir_path, filepath)
process_dir_save_path(dir_path)
# filepath could be an existing file
if os.path.exists(filepath) and not overwrite:
LOGGER.warning(
"The file %s already exists and will not be overwritten.",
filepath,
)
return None
save_pickle(self.model_, filepath, log=kwargs.get("log", True))
return filepath
def load_model(self, filepath: str, **kwargs):
"""Load a saved model.
Parameters
----------
filepath : str
The path to the saved model.
**kwargs : dict, optional
Additional keyword arguments to be passed to the load function.
Returns
-------
self
"""
try:
model = load_pickle(filepath, log=kwargs.get("log", True))
assert is_sklearn_instance(
self.model_,
), "The loaded model is not an instance of a scikit-learn estimator."
self.model_ = model
except FileNotFoundError:
LOGGER.error("No saved model was found to load!")
return self
# dynamically offer every method and attribute of the sklearn model
def __getattr__(self, name: str) -> Any:
"""Get attribute.
Parameters
----------
name : str
attribute name.
Returns
-------
The attribute value. If the attribute is a method that returns self,
the wrapper instance is returned instead.
"""
attr = getattr(self.__dict__["model_"], name)
if callable(attr):
@wraps(attr)
def wrapper(*args, **kwargs):
result = attr(*args, **kwargs)
if result is self.__dict__["model_"]:
self.__dict__["model_"] = result
return result
return wrapper
return attr
def __setattr__(self, name: str, value: Any) -> None:
"""Set attribute.
If setting the model_ attribute, ensure that it is an sklearn model instance. If
model has been instantiated and the attribute being set is in the model's
__dict__, set the attribute in the model. Otherwise, set the attribute in the
wrapper.
"""
if "model_" in self.__dict__ and name == "model_":
if not is_sklearn_instance(value):
raise ValueError("Model must be an sklearn model instance.")
self.__dict__["model_"] = value
elif "model_" in self.__dict__ and name in self.__dict__["model_"].__dict__: