forked from skrub-data/skrub
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_skrub_namespace.py
More file actions
2357 lines (2001 loc) · 81.6 KB
/
Copy path_skrub_namespace.py
File metadata and controls
2357 lines (2001 loc) · 81.6 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
import pickle
import typing
from sklearn import model_selection
from .. import selectors as s
from .._select_cols import DropCols, SelectCols
from ._data_ops import (
AppliedEstimator,
Apply,
Concat,
DataOp,
FreezeAfterFit,
IfElse,
Match,
Var,
check_data_op,
check_name,
deferred,
)
from ._estimator import ParamSearch, SkrubLearner, cross_validate, train_test_split
from ._evaluation import (
choices,
clone,
describe_steps,
evaluate,
nodes,
)
from ._inspection import (
describe_param_grid,
draw_data_op_graph,
full_report,
)
from ._subsampling import SubsamplePreviews, env_with_subsampling
from ._utils import NULL, attribute_error
def _var_values_provided(data_op, environment):
all_nodes = nodes(data_op)
names = {
node._skrub_impl.name for node in all_nodes if isinstance(node._skrub_impl, Var)
}
intersection = names.intersection(environment.keys())
return bool(intersection)
def _check_keep_subsampling(fitted, keep_subsampling):
if not fitted and keep_subsampling:
raise ValueError(
"Subsampling is only applied when fitting the estimator "
"on the data already provided when initializing variables. "
"Please pass `fitted=True` or `keep_subsampling=False`."
)
def _check_can_be_pickled(obj):
try:
dumped = pickle.dumps(obj)
pickle.loads(dumped)
except Exception as e:
msg = "The check to verify that the learner can be serialized failed."
if "recursion" in str(e).lower():
msg = (
f"{msg} Is a step in the learner holding a reference to "
"the full learner itself? For example a global variable "
"in a `@skrub.deferred` function?"
)
raise pickle.PicklingError(msg) from e
def _check_grid_search_possible(data_op):
for c in choices(data_op).values():
if hasattr(c, "rvs") and not isinstance(c, typing.Sequence):
raise ValueError(
"Cannot use grid search with continuous numeric ranges. "
"Please use `make_randomized_search` or provide a number "
f"of steps for this range: {c}"
)
class SkrubNamespace:
"""The data_ops' ``.skb`` attribute."""
# NOTE: if some DataOps types are given additional methods not
# available for all DataOps (eg if some methods specific to
# ``.skb.apply()`` nodes are added), we can create new namespace classes
# derived from this one and return the appropriate one in
# ``_data_ops._Skb.__get__``.
def __init__(self, data_op):
self._data_op = data_op
def _apply(
self,
estimator,
y=None,
cols=s.all(),
how="auto",
allow_reject=False,
unsupervised=False,
):
data_op = DataOp(
Apply(
estimator=estimator,
cols=cols,
X=self._data_op,
y=y,
how=how,
allow_reject=allow_reject,
unsupervised=unsupervised,
)
)
return data_op
@check_data_op
def apply(
self,
estimator,
*,
y=None,
cols=s.all(),
exclude_cols=None,
how="auto",
allow_reject=False,
unsupervised=False,
):
"""
Apply a scikit-learn estimator to a dataframe or numpy array.
Parameters
----------
estimator : scikit-learn estimator
The transformer or predictor to apply.
y : dataframe, column or numpy array, optional
The prediction targets when ``estimator`` is a supervised estimator.
cols : string, list of strings or skrub selector, optional
The columns to transform, when ``estimator`` is a transformer.
exclude_cols : string, list of strings or skrub selector, optional
When ``estimator`` is a transformer, columns to which it should
_not_ be applied. The columns that are matched by ``cols`` AND not
matched by ``exclude_cols`` are transformed.
how : "auto", "cols", "frame" or "no_wrap", optional
How the estimator is applied. In most cases the default "auto"
is appropriate.
- "cols" means `estimator` is wrapped in a :class:`ApplyToCols`
transformer, which fits a separate clone of `estimator` each
column in `cols`. `estimator` must be a transformer (have a
``fit_transform`` method).
- "frame" means `estimator` is wrapped in a :class:`ApplyToFrame`
transformer, which fits a single clone of `estimator` to the
selected part of the input dataframe. `estimator` must be a
transformer.
- "no_wrap" means no wrapping, `estimator` is applied directly to
the unmodified input.
- "auto" chooses the wrapping depending on the input and estimator.
If the input is not a dataframe or the estimator is not a
transformer, the "no_wrap" strategy is chosen. Otherwise if the
estimator has a ``__single_column_transformer__`` attribute,
"cols" is chosen. Otherwise "frame" is chosen.
allow_reject : bool, optional
Whether the transformer can refuse to transform columns for which
it does not apply, in which case they are passed through unchanged.
This can be useful to avoid specifying exactly which columns should
be transformed. For example if we apply ``skrub.ToDatetime()`` to
all columns with ``allow_reject=True``, string columns that can be
parsed as dates will be converted and all other columns will be
passed through. If we use ``allow_reject=False`` (the default), an
error would be raised if the dataframe contains columns for which
``ToDatetime`` does not apply (eg a column of numbers).
unsupervised : bool, optional
Use this to indicate that ``y`` is required for scoring but not
fitting, as is the case for clustering algorithms. If ``y`` is not
required at all (for example when applying an unsupervised
transformer, or when we are not interested in scoring with
ground-truth labels), simply leave the default ``y=None`` and there
is no need to pass a value for ``unsupervised``.
Returns
-------
result
The transformed dataframe when ``estimator`` is a transformer, and
the fitted ``estimator``'s predictions if it is a supervised
predictor.
See also
--------
skrub.DataOp.skb.make_learner :
Get a skrub learner for this DataOp.
skrub.ApplyToCols :
Transformer that applies a given transformer separately to each
selected column.
skrub.ApplyToFrame:
Transformer that applies a given transformer to part of a
dataframe.
Examples
--------
>>> import skrub
>>> data = skrub.datasets.toy_orders()
>>> x = skrub.X(data.X)
>>> x
<Var 'X'>
Result:
―――――――
ID product quantity date
0 1 pen 2 2020-04-03
1 2 cup 3 2020-04-04
2 3 cup 5 2020-04-04
3 4 spoon 1 2020-04-05
>>> datetime_encoder = skrub.DatetimeEncoder(add_total_seconds=False)
>>> x.skb.apply(skrub.TableVectorizer(datetime=datetime_encoder))
<Apply TableVectorizer>
Result:
―――――――
ID product_cup product_pen ... date_year date_month date_day
0 1.0 0.0 1.0 ... 2020.0 4.0 3.0
1 2.0 1.0 0.0 ... 2020.0 4.0 4.0
2 3.0 1.0 0.0 ... 2020.0 4.0 4.0
3 4.0 0.0 0.0 ... 2020.0 4.0 5.0
Transform only the ``'product'`` column:
>>> x.skb.apply(skrub.StringEncoder(n_components=2), cols='product') # doctest: +SKIP
<Apply StringEncoder>
Result:
―――――――
ID product_0 product_1 quantity date
0 1 -2.560113e-16 1.000000e+00 2 2020-04-03
1 2 1.000000e+00 7.447602e-17 3 2020-04-04
2 3 1.000000e+00 7.447602e-17 5 2020-04-04
3 4 -3.955170e-16 -8.326673e-17 1 2020-04-05
Transform all but the ``'ID'`` and ``'quantity'`` columns:
>>> x.skb.apply(
... skrub.StringEncoder(n_components=2), exclude_cols=["ID", "quantity"]
... ) # doctest: +SKIP
<Apply StringEncoder>
Result:
―――――――
ID product_0 product_1 quantity date_0 date_1
0 1 9.775252e-08 7.830415e-01 2 0.766318 -0.406667
1 2 9.999999e-01 0.000000e+00 3 0.943929 0.330148
2 3 9.999998e-01 -1.490116e-08 5 0.943929 0.330149
3 4 9.910963e-08 -6.219692e-01 1 0.766318 -0.406668
More complex selection of the columns to transform, here all numeric
columns except the ``'ID'``:
>>> from sklearn.preprocessing import StandardScaler
>>> from skrub import selectors as s
>>> x.skb.apply(StandardScaler(), cols=s.numeric() - "ID")
<Apply StandardScaler>
Result:
―――――――
ID product date quantity
0 1 pen 2020-04-03 -0.507093
1 2 cup 2020-04-04 0.169031
2 3 cup 2020-04-04 1.521278
3 4 spoon 2020-04-05 -1.183216
For supervised estimators, pass the targets as the argument for ``y``:
>>> from sklearn.dummy import DummyClassifier
>>> y = skrub.y(data.y)
>>> y
<Var 'y'>
Result:
―――――――
0 False
1 False
2 True
3 False
Name: delayed, dtype: bool
>>> x.skb.apply(skrub.TableVectorizer()).skb.apply(DummyClassifier(), y=y)
<Apply DummyClassifier>
Result:
―――――――
0 False
1 False
2 False
3 False
Name: delayed, dtype: bool
Sometimes we want to pass a value for ``y`` because it is required for
scoring and cross-validation, but it is not needed for fitting the
estimator. In this case pass ``unsupervised=True``.
>>> from sklearn.datasets import make_blobs
>>> from sklearn.cluster import KMeans
>>> X, y = make_blobs(n_samples=10, random_state=0)
>>> e = skrub.X(X).skb.apply(
... KMeans(n_clusters=2, n_init=1, random_state=0),
... y=skrub.y(y),
... unsupervised=True,
... )
>>> e.skb.cross_validate()["test_score"] # doctest: +SKIP
0 -19.437348
1 -12.463938
2 -11.804288
3 -37.238832
4 -4.857855
Name: test_score, dtype: float64
>>> learner = e.skb.make_learner().fit({"X": X})
>>> learner.predict({"X": X}) # doctest: +SKIP
array([0, 0, 0, 0, 0, 0, 1, 0, 0, 0], dtype=int32)
""" # noqa: E501
# TODO later we could also expose `wrap_transformer`'s `keep_original`
# and `rename_cols` params
if exclude_cols is not None:
cols = s.make_selector(cols) - exclude_cols
# unsupervised should be an actual bool
unsupervised = bool(unsupervised)
return self._apply(
estimator=estimator,
y=y,
cols=cols,
how=how,
allow_reject=allow_reject,
unsupervised=unsupervised,
)
def apply_func(self, func, *args, **kwargs):
r"""Apply the given function.
This is a convenience function; ``X.skb.apply_func(func)`` is
equivalent to ``skrub.deferred(func)(X)``.
Parameters
----------
func : function
The function to apply to the DataOp.
args
additional positional arguments passed to ``func``.
kwargs
named arguments passed to ``func``.
Returns
-------
data_op
The DataOp that evaluates to the result of calling ``func`` as
``func(self, *args, **kwargs)``.
Examples
--------
>>> import skrub
>>> def count_words(text, sep=None):
... return len(text.split(sep))
>>> text = skrub.var("text", "Hello, world!")
>>> text
<Var 'text'>
Result:
―――――――
'Hello, world!'
>>> count = text.skb.apply_func(count_words)
>>> count
<Call 'count_words'>
Result:
―――――――
2
>>> count.skb.eval({"text": "one two three four"})
4
We can pass extra arguments:
>>> text.skb.apply_func(count_words, sep="\n")
<Call 'count_words'>
Result:
―――――――
1
Using ``.skb.apply_func`` is the same as using ``deferred``, for example:
>>> skrub.deferred(count_words)(text)
<Call 'count_words'>
Result:
―――――――
2
"""
return deferred(func)(self._data_op, *args, **kwargs)
@check_data_op
def if_else(self, value_if_true, value_if_false):
"""Create a conditional DataOp.
If ``self`` evaluates to ``True``, the result will be
``value_if_true``, otherwise ``value_if_false``.
Parameters
----------
value_if_true
The value to return if ``self`` is true.
value_if_false
The value to return if ``self`` is false.
Returns
-------
Conditional DataOp
See also
--------
skrub.DataOp.skb.match :
Select based on the value of a DataOp.
Notes
-----
The branch which is not selected is not evaluated, which is the main
advantage compared to wrapping the conditional statement in a
``@skrub.deferred`` function.
Examples
--------
>>> import skrub
>>> import numpy as np
>>> a = skrub.var('a')
>>> shuffle_a = skrub.var('shuffle_a')
>>> @skrub.deferred
... def shuffled(values):
... print('shuffling')
... return np.random.default_rng(0).permutation(values)
>>> @skrub.deferred
... def copy(values):
... print('copying')
... return values.copy()
>>> b = shuffle_a.skb.if_else(shuffled(a), copy(a))
>>> b
<IfElse <Var 'shuffle_a'> ? <Call 'shuffled'> : <Call 'copy'>>
Note that only one of the 2 branches is evaluated:
>>> b.skb.eval({'a': np.arange(3), 'shuffle_a': True})
shuffling
array([2, 0, 1])
>>> b.skb.eval({'a': np.arange(3), 'shuffle_a': False})
copying
array([0, 1, 2])
"""
return DataOp(IfElse(self._data_op, value_if_true, value_if_false))
@check_data_op
def match(self, targets, default=NULL):
"""Select based on the value of a DataOp.
Evaluate ``self``, then compare the result to the keys in ``targets``.
If there is a match, evaluate the corresponding value and return it. If
there is no match and ``default`` has been provided, evaluate and return
``default``. Otherwise, a ``KeyError`` is raised.
Therefore, only one of the branches or the default is evaluated which
is the main advantage compared to placing the selection inside a
``@skrub.deferred`` function.
Parameters
----------
targets : dict
A dictionary providing which result to select. The keys must be
actual values, they **cannot** be DataOps. The values can be
DataOps or any object.
default : object, optional
If provided, the match falls back to the default when none of the
targets have matched.
Returns
-------
The value corresponding to the matching key or the default
See also
--------
skrub.deferred :
Wrap function calls in a :class:`DataOp`.
Examples
--------
>>> import skrub
>>> a = skrub.var("a")
>>> mode = skrub.var("mode")
>>> @skrub.deferred
... def mul(value, factor):
... result = value * factor
... print(f"{value} * {factor} = {result}")
... return result
>>> b = mode.skb.match(
... {"one": mul(a, 1.0), "two": mul(a, 2.0), "three": mul(a, 3.0)},
... default=mul(a, -1.0),
... )
>>> b.skb.eval({"a": 10.0, "mode": "two"})
10.0 * 2.0 = 20.0
20.0
>>> b.skb.eval({"a": 10.0, "mode": "three"})
10.0 * 3.0 = 30.0
30.0
>>> b.skb.eval({"a": 10.0, "mode": "twenty"})
10.0 * -1.0 = -10.0
-10.0
Note that only one of the multiplications gets evaluated.
"""
return DataOp(Match(self._data_op, targets, default))
@check_data_op
def select(self, cols):
"""Select a subset of columns.
``cols`` can be a column name or a list of column names, but also a
skrub selector. Importantly, the exact list of columns that match the
selector is stored during ``fit`` and then this same list of columns is
selected during ``transform``.
Parameters
----------
cols : string, list of strings, or skrub selector
The columns to select
Returns
-------
dataframe with only the selected columns
Examples
--------
>>> import skrub
>>> from skrub import selectors as s
>>> X = skrub.X(skrub.datasets.toy_orders().X)
>>> X
<Var 'X'>
Result:
―――――――
ID product quantity date
0 1 pen 2 2020-04-03
1 2 cup 3 2020-04-04
2 3 cup 5 2020-04-04
3 4 spoon 1 2020-04-05
>>> X.skb.select(['product', 'quantity'])
<Apply SelectCols>
Result:
―――――――
product quantity
0 pen 2
1 cup 3
2 cup 5
3 spoon 1
>>> X.skb.select(s.string())
<Apply SelectCols>
Result:
―――――――
product date
0 pen 2020-04-03
1 cup 2020-04-04
2 cup 2020-04-04
3 spoon 2020-04-05
"""
return self._apply(SelectCols(cols), how="no_wrap")
@check_data_op
def drop(self, cols):
"""Drop some columns.
``cols`` can be a column name or a list of column names, but also a
skrub selector. Importantly, the exact list of columns that match the
selector is stored during ``fit`` and then this same list of columns is
dropped during ``transform``.
Parameters
----------
cols : string, list of strings, or skrub selector
The columns to select
Returns
-------
dataframe without the dropped columns
Examples
--------
>>> import skrub
>>> from skrub import selectors as s
>>> X = skrub.X(skrub.datasets.toy_orders().X)
>>> X
<Var 'X'>
Result:
―――――――
ID product quantity date
0 1 pen 2 2020-04-03
1 2 cup 3 2020-04-04
2 3 cup 5 2020-04-04
3 4 spoon 1 2020-04-05
>>> X.skb.drop(['ID', 'date'])
<Apply DropCols>
Result:
―――――――
product quantity
0 pen 2
1 cup 3
2 cup 5
3 spoon 1
>>> X.skb.drop(s.string())
<Apply DropCols>
Result:
―――――――
ID quantity
0 1 2
1 2 3
2 3 5
3 4 1
"""
return self._apply(DropCols(cols), how="no_wrap")
@check_data_op
def concat(self, others, axis=0):
"""Concatenate dataframes vertically or horizontally.
Parameters
----------
others : list of dataframes
The dataframes to stack horizontally with ``self``
axis : {0, 1}, default 0
The axis to concatenate along.
0: stack vertically (rows)
1: stack horizontally (columns)
Returns
-------
dataframe
The combined dataframes.
Examples
--------
>>> import pandas as pd
>>> import skrub
>>> a = skrub.var('a', pd.DataFrame({'a1': [0], 'a2': [1]}))
>>> b = skrub.var('b', pd.DataFrame({'b1': [2], 'b2': [3]}))
>>> c = skrub.var('c', pd.DataFrame({'c1': [4], 'c2': [5]}))
>>> d = skrub.var('d', pd.DataFrame({'c1': [6], 'c2': [7]}))
>>> a
<Var 'a'>
Result:
―――――――
a1 a2
0 0 1
>>> a.skb.concat([b, c], axis=1)
<Concat: 3 dataframes>
Result:
―――――――
a1 a2 b1 b2 c1 c2
0 0 1 2 3 4 5
>>> c.skb.concat([d], axis=0)
<Concat: 2 dataframes>
Result:
―――――――
c1 c2
0 4 5
1 6 7
Note that even if we want to concatenate a single dataframe we must
still put it in a list:
>>> a.skb.concat([b], axis=1)
<Concat: 2 dataframes>
Result:
―――――――
a1 a2 b1 b2
0 0 1 2 3
""" # noqa: E501
return DataOp(Concat(self._data_op, others, axis=axis))
@check_data_op
def subsample(self, n=1000, *, how="head"):
"""Configure subsampling of a dataframe or numpy array.
Enables faster development by computing the previews on a subsample of
the available data. Outside of previews, no subsampling takes place by
default but it can be turned on with the ``keep_subsampling`` parameter
-- see the Notes section for details.
Parameters
----------
n : int, default=1000
Number of rows to keep.
how : 'head' or 'random'
How subsampling should be done (when it takes place). If 'head',
the first ``n`` rows are kept. If 'random', ``n`` rows are sampled
randomly, without maintaining order and without replacement.
Returns
-------
subsampled data
The subsampled dataframe, column or numpy array.
See Also
--------
DataOp.skb.preview :
Access a preview of the result on the subsampled data.
Notes
-----
This method configures *how* the dataframe should be subsampled. If it
has been configured, subsampling actually only takes place in some
specific situations:
- When computing the previews (results displayed when printing a
DataOp and the output of :meth:`DataOp.skb.preview`).
- When it is explicitly requested by passing ``keep_subsampling=True`` to one
of the functions that expose that parameter such as
:meth:`DataOp.skb.make_randomized_search` or :func:`cross_validate`.
When subsampling has not been configured (``subsample`` has not
been called anywhere in the DataOp plan), no subsampling is ever done.
Subsampling is never performed during inference (using the ``predict`` or ``score`` methods), as this would
lead to inconsistent shapes (number of samples) between the predictions
and the ground truth labels.
This method can only be used on steps that produce a dataframe, a
column (series) or a numpy array.
Note that subsampling is local to the variable that is being subsampled.
This means that, if two variables are meant to have the same number of
rows (e.g., ``X`` and ``y``), both should be subsampled with the same
strategy.
The seed for the ``random`` strategy is fixed, so the sampled rows are
constant when sampling across different variables.
Examples
--------
>>> from sklearn.datasets import load_diabetes
>>> from sklearn.linear_model import Ridge
>>> import skrub
>>> df = load_diabetes(as_frame=True)["frame"]
>>> df.shape
(442, 11)
>>> data = skrub.var("data", df).skb.subsample(n=15)
We can see that the previews use only a subsample of 15 rows:
>>> data.shape
<GetAttr 'shape'>
Result (on a subsample):
――――――――――――――――――――――――
(15, 11)
>>> X = data.drop("target", axis=1, errors="ignore").skb.mark_as_X()
>>> y = data["target"].skb.mark_as_y()
>>> pred = X.skb.apply(
... Ridge(alpha=skrub.choose_float(0.01, 10.0, log=True, name="α")), y=y
... )
Here also, the preview for the predictions contains 15 rows:
>>> pred
<Apply Ridge>
Result (on a subsample):
――――――――――――――――――――――――
0 142.866906
1 130.980765
2 138.555388
3 149.703363
4 136.015214
5 139.773213
6 134.110415
7 129.224783
8 140.161363
9 155.272033
10 139.552110
11 130.318783
12 135.956591
13 142.998060
14 132.511013
Name: target, dtype: float64
By default, model fitting and hyperparameter search are done on the
full data, so if we want the subsampling to take place we have to
pass ``keep_subsampling=True``:
>>> quick_search = pred.skb.make_randomized_search(
... keep_subsampling=True, fitted=True, n_iter=4, random_state=0
... )
>>> quick_search.detailed_results_[["mean_test_score", "mean_fit_time", "α"]] # doctest: +SKIP
mean_test_score mean_fit_time α
0 -0.597596 0.004322 0.431171
1 -0.599036 0.004328 0.443038
2 -0.615900 0.004272 0.643117
3 -0.637498 0.004219 1.398196
Now that we have checked our learner works on a subsample, we can
fit the hyperparameter search on the full data:
>>> full_search = pred.skb.make_randomized_search(
... fitted=True, n_iter=4, random_state=0
... )
>>> full_search.detailed_results_[["mean_test_score", "mean_fit_time", "α"]] # doctest: +SKIP
mean_test_score mean_fit_time α
0 0.457807 0.004791 0.431171
1 0.456808 0.004834 0.443038
2 0.439670 0.004849 0.643117
3 0.380719 0.004827 1.398196
This example dataset is so small that the subsampling does not change
the fit computation time but we can tell the second search used the
full data from the higher scores. For datasets of a realistic size
using the subsampling allows us to do a "dry run" of the
cross-validation or model fitting much faster than when using the
full data.
Sampling only one variable does not sample the other:
>>> data = skrub.var("data", df)
>>> X = data.drop("target", axis=1, errors="ignore").skb.mark_as_X()
>>> X = X.skb.subsample(n=15)
>>> y = data["target"].skb.mark_as_y()
>>> X.shape
<GetAttr 'shape'>
Result (on a subsample):
――――――――――――――――――――――――
(15, 10)
>>> y.shape
<GetAttr 'shape'>
Result:
―――――――
(442,)
Read more about subsampling in the :ref:`User Guide <user_guide_data_ops_subsampling>`.
""" # noqa : E501
return DataOp(SubsamplePreviews(self._data_op, n=n, how=how))
def clone(self, drop_values=True):
"""Get an independent clone of the DataOp.
Parameters
----------
drop_values : bool, default=True
Whether to drop the initial values passed to ``skrub.var()``.
This is convenient for example to serialize DataOps without
creating large files.
Returns
-------
clone
A new DataOp which does not share its state (such as fitted
estimators) or cache with the original, and possibly without the
variables' values.
Examples
--------
>>> import skrub
>>> c = skrub.var('a', 0) + skrub.var('b', 1)
>>> c
<BinOp: add>
Result:
―――――――
1
>>> c.skb.get_data()
{'a': 0, 'b': 1}
>>> clone = c.skb.clone()
>>> clone
<BinOp: add>
>>> clone.skb.get_data()
{}
We can ask to keep the variable values:
>>> clone = c.skb.clone(drop_values=False)
>>> clone.skb.get_data()
{'a': 0, 'b': 1}
Note that in that case the cache used for previews is still cleared. So
if we want the preview we need to prime the new DataOp by
accessing the preview once (either directly or by adding more steps to it):
>>> clone
<BinOp: add>
>>> clone.skb.preview()
1
>>> clone
<BinOp: add>
Result:
―――――――
1
"""
return clone(self._data_op, drop_preview_data=drop_values)
def eval(self, environment=None, *, keep_subsampling=False):
"""Evaluate the DataOp.
This returns the result produced by evaluating the DataOp, ie
running the corresponding learner. The result is always the output
of the learner's ``fit_transform`` -- a learner is refitted to the
provided data.
If no data is provided, the values passed when creating the variables
in the DataOp are used.
Parameters
----------
environment : dict or None, optional
If ``None``, the initial values of the variables contained in the
DataOp are used. If a dict, it must map the name of each
variable to a corresponding value.
keep_subsampling : bool, default=False
If True, and if subsampling has been configured (see
:meth:`DataOp.skb.subsample`), use a subsample of the data. By
default subsampling is not applied and all the data is used.
Returns
-------
result
The result of running the computation, ie of executing the
learner's ``fit_transform`` on the provided data.
See Also
--------
DataOp.skb.preview :
Access the preview of the result on the variables initial values,
with subsampling. Faster than ``eval`` but does not allow passing
new data and always applies subsampling.
Examples
--------
>>> import skrub
>>> a = skrub.var('a', 10)
>>> b = skrub.var('b', 5)
>>> c = a + b
>>> c
<BinOp: add>
Result:
―――――――
15
>>> c.skb.eval()
15
>>> c.skb.eval({'a': 1, 'b': 2})
3
"""
if environment is not None and not isinstance(environment, typing.Mapping):
raise TypeError(
"The `environment` passed to `eval()` should be None or a dictionary, "
f"got: '{type(environment)}'"
)
if environment is None:
environment = self.get_data()
else:
environment = {
**environment,
"_skrub_use_var_values": not _var_values_provided(
self._data_op, environment
),
}
environment = env_with_subsampling(self._data_op, environment, keep_subsampling)
return evaluate(
self._data_op, mode="fit_transform", environment=environment, clear=True
)
def preview(self):
"""Get the value computed for previews (shown when printing the DataOp).
Returns
-------
preview result
The result of evaluating the DataOp on the data stored in its
variables.
See Also
--------
DataOp.skb.subsample :
Specify how to subsample an intermediate result when computing
previews.
DataOp.skb.eval :
Evaluate the DataOp. Unlike ``preview``, we can pass new data
rather than using the values that variables were initialized with,
but results are not cached, and no subsampling takes place by
default.