-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathresampling.jl
1868 lines (1524 loc) · 59.4 KB
/
resampling.jl
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
# TYPE ALIASES
const AbstractRow = Union{AbstractVector{<:Integer}, Colon}
const TrainTestPair = Tuple{AbstractRow,AbstractRow}
const TrainTestPairs = AbstractVector{<:TrainTestPair}
# # ERROR MESSAGES
const PREDICT_OPERATIONS_STRING = begin
strings = map(PREDICT_OPERATIONS) do op
"`"*string(op)*"`"
end
join(strings, ", ", ", or ")
end
const PROG_METER_DT = 0.1
const ERR_WEIGHTS_LENGTH =
DimensionMismatch("`weights` and target have different lengths. ")
const ERR_WEIGHTS_DICT =
ArgumentError("`class_weights` must be a "*
"dictionary with `Real` values. ")
const ERR_WEIGHTS_CLASSES =
DimensionMismatch("The keys of `class_weights` "*
"are not the same as the levels of the "*
"target, `y`. Do `levels(y)` to check levels. ")
const ERR_OPERATION_MEASURE_MISMATCH = DimensionMismatch(
"The number of operations and the number of measures are different. ")
const ERR_INVALID_OPERATION = ArgumentError(
"Invalid `operation` or `operations`. "*
"An operation must be one of these: $PREDICT_OPERATIONS_STRING. ")
_ambiguous_operation(model, measure) =
"`$measure` does not support a `model` with "*
"`prediction_type(model) == :$(prediction_type(model))`. "
err_ambiguous_operation(model, measure) = ArgumentError(
_ambiguous_operation(model, measure)*
"\nUnable to infer an appropriate operation for `$measure`. "*
"Explicitly specify `operation=...` or `operations=...`. ")
err_incompatible_prediction_types(model, measure) = ArgumentError(
_ambiguous_operation(model, measure)*
"If your model is truly making probabilistic predictions, try explicitly "*
"specifiying operations. For example, for "*
"`measures = [area_under_curve, accuracy]`, try "*
"`operations=[predict, predict_mode]`. ")
const LOG_AVOID = "\nTo override measure checks, set check_measure=false. "
const LOG_SUGGESTION1 =
"\nPerhaps you want to set `operation="*
"predict_mode` or need to "*
"specify multiple operations, "*
"one for each measure. "
const LOG_SUGGESTION2 =
"\nPerhaps you want to set `operation="*
"predict_mean` or `operation=predict_median`, or "*
"specify multiple operations, "*
"one for each measure. "
ERR_MEASURES_OBSERVATION_SCITYPE(measure, T_measure, T) = ArgumentError(
"\nobservation scitype of target = `$T` but ($measure) only supports "*
"`$T_measure`."*LOG_AVOID
)
ERR_MEASURES_PROBABILISTIC(measure, suggestion) = ArgumentError(
"The model subtypes `Probabilistic`, and so is not supported by "*
"`$measure`. $suggestion"*LOG_AVOID
)
ERR_MEASURES_DETERMINISTIC(measure) = ArgumentError(
"The model subtypes `Deterministic`, "*
"and so is not supported by `$measure`. "*LOG_AVOID
)
# ==================================================================
## MODEL TYPES THAT CAN BE EVALUATED
# not exported:
const Measurable = Union{Supervised, Annotator}
# ==================================================================
## RESAMPLING STRATEGIES
abstract type ResamplingStrategy <: MLJType end
show_as_constructed(::Type{<:ResamplingStrategy}) = true
# resampling strategies are `==` if they have the same type and their
# field values are `==`:
function ==(s1::S, s2::S) where S <: ResamplingStrategy
return all(getfield(s1, fld) == getfield(s2, fld) for fld in fieldnames(S))
end
# fallbacks for method to be implemented by each new strategy:
train_test_pairs(s::ResamplingStrategy, rows, X, y, w) =
train_test_pairs(s, rows, X, y)
train_test_pairs(s::ResamplingStrategy, rows, X, y) =
train_test_pairs(s, rows, y)
train_test_pairs(s::ResamplingStrategy, rows, y) =
train_test_pairs(s, rows)
# Helper to interpret rng, shuffle in case either is `nothing` or if
# `rng` is an integer:
function shuffle_and_rng(shuffle, rng)
if rng isa Integer
rng = MersenneTwister(rng)
end
if shuffle === nothing
shuffle = ifelse(rng===nothing, false, true)
end
if rng === nothing
rng = Random.GLOBAL_RNG
end
return shuffle, rng
end
# ----------------------------------------------------------------
# InSample
"""
in_sample = InSample()
Instantiate an `InSample` resampling strategy, for use in `evaluate!`, `evaluate` and in
tuning. In this strategy the train and test sets are the same, and consist of all
observations specified by the `rows` keyword argument. If `rows` is not specified, all
supplied rows are used.
# Example
```julia
using MLJBase, MLJModels
X, y = make_blobs() # a table and a vector
model = ConstantClassifier()
train, test = partition(eachindex(y), 0.7) # train:test = 70:30
```
Compute in-sample (training) loss:
```julia
evaluate(model, X, y, resampling=InSample(), rows=train, measure=brier_loss)
```
Compute the out-of-sample loss:
```julia
evaluate(model, X, y, resampling=[(train, test),], measure=brier_loss)
```
Or equivalently:
```julia
evaluate(model, X, y, resampling=Holdout(fraction_train=0.7), measure=brier_loss)
```
"""
struct InSample <: ResamplingStrategy end
train_test_pairs(::InSample, rows) = [(rows, rows),]
# ----------------------------------------------------------------
# Holdout
"""
holdout = Holdout(; fraction_train=0.7, shuffle=nothing, rng=nothing)
Instantiate a `Holdout` resampling strategy, for use in `evaluate!`, `evaluate` and in
tuning.
```julia
train_test_pairs(holdout, rows)
```
Returns the pair `[(train, test)]`, where `train` and `test` are
vectors such that `rows=vcat(train, test)` and
`length(train)/length(rows)` is approximatey equal to fraction_train`.
Pre-shuffling of `rows` is controlled by `rng` and `shuffle`. If `rng`
is an integer, then the `Holdout` keyword constructor resets it to
`MersenneTwister(rng)`. Otherwise some `AbstractRNG` object is
expected.
If `rng` is left unspecified, `rng` is reset to `Random.GLOBAL_RNG`,
in which case rows are only pre-shuffled if `shuffle=true` is
specified.
"""
struct Holdout <: ResamplingStrategy
fraction_train::Float64
shuffle::Bool
rng::Union{Int,AbstractRNG}
function Holdout(fraction_train, shuffle, rng)
0 < fraction_train < 1 ||
error("`fraction_train` must be between 0 and 1.")
return new(fraction_train, shuffle, rng)
end
end
# Keyword Constructor:
Holdout(; fraction_train::Float64=0.7, shuffle=nothing, rng=nothing) =
Holdout(fraction_train, shuffle_and_rng(shuffle, rng)...)
function train_test_pairs(holdout::Holdout, rows)
train, test = partition(rows, holdout.fraction_train,
shuffle=holdout.shuffle, rng=holdout.rng)
return [(train, test),]
end
# ----------------------------------------------------------------
# Cross-validation (vanilla)
"""
cv = CV(; nfolds=6, shuffle=nothing, rng=nothing)
Cross-validation resampling strategy, for use in `evaluate!`,
`evaluate` and tuning.
```julia
train_test_pairs(cv, rows)
```
Returns an `nfolds`-length iterator of `(train, test)` pairs of
vectors (row indices), where each `train` and `test` is a sub-vector
of `rows`. The `test` vectors are mutually exclusive and exhaust
`rows`. Each `train` vector is the complement of the corresponding
`test` vector. With no row pre-shuffling, the order of `rows` is
preserved, in the sense that `rows` coincides precisely with the
concatenation of the `test` vectors, in the order they are
generated. The first `r` test vectors have length `n + 1`, where `n, r
= divrem(length(rows), nfolds)`, and the remaining test vectors have
length `n`.
Pre-shuffling of `rows` is controlled by `rng` and `shuffle`. If `rng`
is an integer, then the `CV` keyword constructor resets it to
`MersenneTwister(rng)`. Otherwise some `AbstractRNG` object is
expected.
If `rng` is left unspecified, `rng` is reset to `Random.GLOBAL_RNG`,
in which case rows are only pre-shuffled if `shuffle=true` is
explicitly specified.
"""
struct CV <: ResamplingStrategy
nfolds::Int
shuffle::Bool
rng::Union{Int,AbstractRNG}
function CV(nfolds, shuffle, rng)
nfolds > 1 || throw(ArgumentError("Must have nfolds > 1. "))
return new(nfolds, shuffle, rng)
end
end
# Constructor with keywords
CV(; nfolds::Int=6, shuffle=nothing, rng=nothing) =
CV(nfolds, shuffle_and_rng(shuffle, rng)...)
function train_test_pairs(cv::CV, rows)
n_obs = length(rows)
n_folds = cv.nfolds
if cv.shuffle
rows=shuffle!(cv.rng, collect(rows))
end
n, r = divrem(n_obs, n_folds)
if n < 1
throw(ArgumentError(
"""Inusufficient data for $n_folds-fold cross-validation.
Try reducing nfolds. """
))
end
m = n + 1 # number of observations in first r folds
itr1 = Iterators.partition( 1 : m*r , m)
itr2 = Iterators.partition( m*r+1 : n_obs , n)
test_folds = Iterators.flatten((itr1, itr2))
return map(test_folds) do test_indices
test_rows = rows[test_indices]
train_rows = vcat(
rows[ 1 : first(test_indices)-1 ],
rows[ last(test_indices)+1 : end ]
)
(train_rows, test_rows)
end
end
# ----------------------------------------------------------------
# Cross-validation (TimeSeriesCV)
"""
tscv = TimeSeriesCV(; nfolds=4)
Cross-validation resampling strategy, for use in `evaluate!`,
`evaluate` and tuning, when observations are chronological and not
expected to be independent.
```julia
train_test_pairs(tscv, rows)
```
Returns an `nfolds`-length iterator of `(train, test)` pairs of
vectors (row indices), where each `train` and `test` is a sub-vector
of `rows`. The rows are partitioned sequentially into `nfolds + 1`
approximately equal length partitions, where the first partition is the first
train set, and the second partition is the first test set. The second
train set consists of the first two partitions, and the second test set
consists of the third partition, and so on for each fold.
The first partition (which is the first train set) has length `n + r`,
where `n, r = divrem(length(rows), nfolds + 1)`, and the remaining partitions
(all of the test folds) have length `n`.
# Examples
```julia-repl
julia> MLJBase.train_test_pairs(TimeSeriesCV(nfolds=3), 1:10)
3-element Vector{Tuple{UnitRange{Int64}, UnitRange{Int64}}}:
(1:4, 5:6)
(1:6, 7:8)
(1:8, 9:10)
julia> model = (@load RidgeRegressor pkg=MultivariateStats verbosity=0)();
julia> data = @load_sunspots;
julia> X = (lag1 = data.sunspot_number[2:end-1],
lag2 = data.sunspot_number[1:end-2]);
julia> y = data.sunspot_number[3:end];
julia> tscv = TimeSeriesCV(nfolds=3);
julia> evaluate(model, X, y, resampling=tscv, measure=rmse, verbosity=0)
┌───────────────────────────┬───────────────┬────────────────────┐
│ _.measure │ _.measurement │ _.per_fold │
├───────────────────────────┼───────────────┼────────────────────┤
│ RootMeanSquaredError @753 │ 21.7 │ [25.4, 16.3, 22.4] │
└───────────────────────────┴───────────────┴────────────────────┘
_.per_observation = [missing]
_.fitted_params_per_fold = [ … ]
_.report_per_fold = [ … ]
_.train_test_rows = [ … ]
```
"""
struct TimeSeriesCV <: ResamplingStrategy
nfolds::Int
function TimeSeriesCV(nfolds)
nfolds > 0 || throw(ArgumentError("Must have nfolds > 0. "))
return new(nfolds)
end
end
# Constructor with keywords
TimeSeriesCV(; nfolds::Int=4) = TimeSeriesCV(nfolds)
function train_test_pairs(tscv::TimeSeriesCV, rows)
if rows != sort(rows)
@warn "TimeSeriesCV is being applied to `rows` not in sequence. "
end
n_obs = length(rows)
n_folds = tscv.nfolds
m, r = divrem(n_obs, n_folds + 1)
if m < 1
throw(ArgumentError(
"Inusufficient data for $n_folds-fold " *
"time-series cross-validation.\n" *
"Try reducing nfolds. "
))
end
test_folds = Iterators.partition( m+r+1 : n_obs , m)
return map(test_folds) do test_indices
train_indices = 1 : first(test_indices)-1
rows[train_indices], rows[test_indices]
end
end
# ----------------------------------------------------------------
# Cross-validation (stratified; for `Finite` targets)
"""
stratified_cv = StratifiedCV(; nfolds=6,
shuffle=false,
rng=Random.GLOBAL_RNG)
Stratified cross-validation resampling strategy, for use in
`evaluate!`, `evaluate` and in tuning. Applies only to classification
problems (`OrderedFactor` or `Multiclass` targets).
```julia
train_test_pairs(stratified_cv, rows, y)
```
Returns an `nfolds`-length iterator of `(train, test)` pairs of
vectors (row indices) where each `train` and `test` is a sub-vector of
`rows`. The `test` vectors are mutually exclusive and exhaust
`rows`. Each `train` vector is the complement of the corresponding
`test` vector.
Unlike regular cross-validation, the distribution of the levels of the
target `y` corresponding to each `train` and `test` is constrained, as
far as possible, to replicate that of `y[rows]` as a whole.
The stratified `train_test_pairs` algorithm is invariant to label renaming.
For example, if you run `replace!(y, 'a' => 'b', 'b' => 'a')` and then re-run
`train_test_pairs`, the returned `(train, test)` pairs will be the same.
Pre-shuffling of `rows` is controlled by `rng` and `shuffle`. If `rng`
is an integer, then the `StratifedCV` keywod constructor resets it to
`MersenneTwister(rng)`. Otherwise some `AbstractRNG` object is
expected.
If `rng` is left unspecified, `rng` is reset to `Random.GLOBAL_RNG`,
in which case rows are only pre-shuffled if `shuffle=true` is
explicitly specified.
"""
struct StratifiedCV <: ResamplingStrategy
nfolds::Int
shuffle::Bool
rng::Union{Int,AbstractRNG}
function StratifiedCV(nfolds, shuffle, rng)
nfolds > 1 || throw(ArgumentError("Must have nfolds > 1. "))
return new(nfolds, shuffle, rng)
end
end
# Constructor with keywords
StratifiedCV(; nfolds::Int=6, shuffle=nothing, rng=nothing) =
StratifiedCV(nfolds, shuffle_and_rng(shuffle, rng)...)
# Description of the stratified CV algorithm:
#
# There are algorithms that are conceptually somewhat simpler than this
# algorithm, but this algorithm is O(n) and is invariant to relabelling
# of the target vector.
#
# 1) Use countmap() to get the count for each level.
#
# 2) Use unique() to get the order in which the levels appear. (Steps 1
# and 2 could be combined if countmap() used an OrderedDict.)
#
# 3) For y = ['b', 'c', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'a', 'a', 'a'],
# the levels occur in the order ['b', 'c', 'a'], and each level has a count
# of 4. So imagine a table like this:
#
# b b b b c c c c a a a a
# 1 2 3 1 2 3 1 2 3 1 2 3
#
# This table ensures that the levels are smoothly spread across the test folds.
# In other words, where one level leaves off, the next level picks up. So,
# for example, as the 'c' levels are encountered, the corresponding row indices
# are added to folds [2, 3, 1, 2], in that order. The table above is
# partitioned by y-level and put into a dictionary `fold_lookup` that maps
# levels to the corresponding array of fold indices.
#
# 4) Iterate i from 1 to length(rows). For each i, look up the corresponding
# level, i.e. `level = y[rows[i]]`. Then use `popfirst!(fold_lookup[level])`
# to find the test fold in which to put the i-th element of `rows`.
#
# 5) Concatenate the appropriate test folds together to get the train
# indices for each `(train, test)` pair.
function train_test_pairs(stratified_cv::StratifiedCV, rows, y)
st = scitype(y)
if stratified_cv.shuffle
rows=shuffle!(stratified_cv.rng, collect(rows))
end
n_folds = stratified_cv.nfolds
n_obs = length(rows)
obs_per_fold = div(n_obs, n_folds)
y_included = y[rows]
level_count_dict = countmap(y_included)
# unique() preserves the order of appearance of the levels.
# We need this so that the results are invariant to renaming of the levels.
y_levels = unique(y_included)
level_count = [level_count_dict[level] for level in y_levels]
fold_cycle = collect(Iterators.take(Iterators.cycle(1:n_folds), n_obs))
lasts = cumsum(level_count)
firsts = [1; lasts[1:end-1] .+ 1]
level_fold_indices = (fold_cycle[f:l] for (f, l) in zip(firsts, lasts))
fold_lookup = Dict(y_levels .=> level_fold_indices)
folds = [Int[] for _ in 1:n_folds]
for fold in folds
sizehint!(fold, obs_per_fold)
end
for i in 1:n_obs
level = y_included[i]
fold_index = popfirst!(fold_lookup[level])
push!(folds[fold_index], rows[i])
end
[(complement(folds, i), folds[i]) for i in 1:n_folds]
end
# ================================================================
## EVALUATION RESULT TYPE
abstract type AbstractPerformanceEvaluation <: MLJType end
"""
PerformanceEvaluation <: AbstractPerformanceEvaluation
Type of object returned by [`evaluate`](@ref) (for models plus data) or
[`evaluate!`](@ref) (for machines). Such objects encode estimates of the performance
(generalization error) of a supervised model or outlier detection model, and store other
information ancillary to the computation.
If [`evaluate`](@ref) or [`evaluate!`](@ref) is called with the `compact=true` option,
then a [`CompactPerformanceEvaluation`](@ref) object is returned instead.
When `evaluate`/`evaluate!` is called, a number of train/test pairs ("folds") of row
indices are generated, according to the options provided, which are discussed in the
[`evaluate!`](@ref) doc-string. Rows correspond to observations. The generated train/test
pairs are recorded in the `train_test_rows` field of the `PerformanceEvaluation` struct,
and the corresponding estimates, aggregated over all train/test pairs, are recorded in
`measurement`, a vector with one entry for each measure (metric) recorded in `measure`.
When displayed, a `PerformanceEvaluation` object includes a value under the heading
`1.96*SE`, derived from the standard error of the `per_fold` entries. This value is
suitable for constructing a formal 95% confidence interval for the given
`measurement`. Such intervals should be interpreted with caution. See, for example, [Bates
et al. (2021)](https://arxiv.org/abs/2104.00673).
### Fields
These fields are part of the public API of the `PerformanceEvaluation` struct.
- `model`: model used to create the performance evaluation. In the case a
tuning model, this is the best model found.
- `measure`: vector of measures (metrics) used to evaluate performance
- `measurement`: vector of measurements - one for each element of `measure` - aggregating
the performance measurements over all train/test pairs (folds). The aggregation method
applied for a given measure `m` is
`StatisticalMeasuresBase.external_aggregation_mode(m)` (commonly `Mean()` or `Sum()`)
- `operation` (e.g., `predict_mode`): the operations applied for each measure to generate
predictions to be evaluated. Possibilities are: $PREDICT_OPERATIONS_STRING.
- `per_fold`: a vector of vectors of individual test fold evaluations (one vector per
measure). Useful for obtaining a rough estimate of the variance of the performance
estimate.
- `per_observation`: a vector of vectors of vectors containing individual per-observation
measurements: for an evaluation `e`, `e.per_observation[m][f][i]` is the measurement for
the `i`th observation in the `f`th test fold, evaluated using the `m`th measure. Useful
for some forms of hyper-parameter optimization. Note that an aggregregated measurement
for some measure `measure` is repeated across all observations in a fold if
`StatisticalMeasures.can_report_unaggregated(measure) == true`. If `e` has been computed
with the `per_observation=false` option, then `e_per_observation` is a vector of
`missings`.
- `fitted_params_per_fold`: a vector containing `fitted params(mach)` for each machine
`mach` trained during resampling - one machine per train/test pair. Use this to extract
the learned parameters for each individual training event.
- `report_per_fold`: a vector containing `report(mach)` for each machine `mach` training
in resampling - one machine per train/test pair.
- `train_test_rows`: a vector of tuples, each of the form `(train, test)`, where `train`
and `test` are vectors of row (observation) indices for training and evaluation
respectively.
- `resampling`: the user-specified resampling strategy to generate the train/test pairs
(or literal train/test pairs if that was directly specified).
- `repeats`: the number of times the resampling strategy was repeated.
See also [`CompactPerformanceEvaluation`](@ref).
"""
struct PerformanceEvaluation{M,
Measure,
Measurement,
Operation,
PerFold,
PerObservation,
FittedParamsPerFold,
ReportPerFold,
R} <: AbstractPerformanceEvaluation
model::M
measure::Measure
measurement::Measurement
operation::Operation
per_fold::PerFold
per_observation::PerObservation
fitted_params_per_fold::FittedParamsPerFold
report_per_fold::ReportPerFold
train_test_rows::TrainTestPairs
resampling::R
repeats::Int
end
"""
CompactPerformanceEvaluation <: AbstractPerformanceEvaluation
Type of object returned by [`evaluate`](@ref) (for models plus data) or
[`evaluate!`](@ref) (for machines) when called with the option `compact = true`. Such
objects have the same structure as the [`PerformanceEvaluation`](@ref) objects returned by
default, except that the following fields are omitted to save memory:
`fitted_params_per_fold`, `report_per_fold`, `train_test_rows`.
For more on the remaining fields, see [`PerformanceEvaluation`](@ref).
"""
struct CompactPerformanceEvaluation{M,
Measure,
Measurement,
Operation,
PerFold,
PerObservation,
R} <: AbstractPerformanceEvaluation
model::M
measure::Measure
measurement::Measurement
operation::Operation
per_fold::PerFold
per_observation::PerObservation
resampling::R
repeats::Int
end
compactify(e::CompactPerformanceEvaluation) = e
compactify(e::PerformanceEvaluation) = CompactPerformanceEvaluation(
e.model,
e.measure,
e.measurement,
e.operation,
e.per_fold,
e. per_observation,
e.resampling,
e.repeats,
)
# pretty printing:
round3(x) = x
round3(x::AbstractFloat) = round(x, sigdigits=3)
const SE_FACTOR = 1.96 # For a 95% confidence interval.
_standard_error(v::AbstractVector{<:Real}) = SE_FACTOR*std(v) / sqrt(length(v) - 1)
_standard_error(v) = "N/A"
function _standard_errors(e::AbstractPerformanceEvaluation)
measure = e.measure
length(e.per_fold[1]) == 1 && return [nothing]
std_errors = map(_standard_error, e.per_fold)
return std_errors
end
# to address #874, while preserving the display worked out in #757:
_repr_(f::Function) = repr(f)
_repr_(x) = repr("text/plain", x)
# helper for row labels: _label(1) ="A", _label(2) = "B", _label(27) = "BA", etc
const alphabet = Char.(65:90)
_label(i) = map(digits(i - 1, base=26)) do d alphabet[d + 1] end |> join |> reverse
function Base.show(io::IO, ::MIME"text/plain", e::AbstractPerformanceEvaluation)
_measure = [_repr_(m) for m in e.measure]
_measurement = round3.(e.measurement)
_per_fold = [round3.(v) for v in e.per_fold]
_sterr = round3.(_standard_errors(e))
row_labels = _label.(eachindex(e.measure))
# Define header and data for main table
data = hcat(_measure, e.operation, _measurement)
header = ["measure", "operation", "measurement"]
if length(row_labels) > 1
data = hcat(row_labels, data)
header =["", header...]
end
if e isa PerformanceEvaluation
println(io, "PerformanceEvaluation object "*
"with these fields:")
println(io, " model, measure, operation,\n"*
" measurement, per_fold, per_observation,\n"*
" fitted_params_per_fold, report_per_fold,\n"*
" train_test_rows, resampling, repeats")
else
println(io, "CompactPerformanceEvaluation object "*
"with these fields:")
println(io, " model, measure, operation,\n"*
" measurement, per_fold, per_observation,\n"*
" train_test_rows, resampling, repeats")
end
println(io, "Extract:")
show_color = MLJBase.SHOW_COLOR[]
color_off()
PrettyTables.pretty_table(
io,
data;
header,
header_crayon=PrettyTables.Crayon(bold=false),
alignment=:l,
linebreaks=true,
)
# Show the per-fold table if needed:
if length(first(e.per_fold)) > 1
show_sterr = any(!isnothing, _sterr)
data2 = hcat(_per_fold, _sterr)
header2 = ["per_fold", "1.96*SE"]
if length(row_labels) > 1
data2 = hcat(row_labels, data2)
header2 =["", header2...]
end
PrettyTables.pretty_table(
io,
data2;
header=header2,
header_crayon=PrettyTables.Crayon(bold=false),
alignment=:l,
linebreaks=true,
)
end
show_color ? color_on() : color_off()
end
_summary(e) = Tuple(round3.(e.measurement))
Base.show(io::IO, e::PerformanceEvaluation) =
print(io, "PerformanceEvaluation$(_summary(e))")
Base.show(io::IO, e::CompactPerformanceEvaluation) =
print(io, "CompactPerformanceEvaluation$(_summary(e))")
# ===============================================================
## USER CONTROL OF DEFAULT LOGGING
const DOC_DEFAULT_LOGGER =
"""
The default logger is used in calls to [`evaluate!`](@ref) and [`evaluate`](@ref), and
in the constructors `TunedModel` and `IteratedModel`, unless the `logger` keyword is
explicitly specified.
!!! note
Prior to MLJ v0.20.7 (and MLJBase 1.5) the default logger was always `nothing`.
"""
"""
default_logger()
Return the current value of the default logger for use with supported machine learning
tracking platforms, such as [MLflow](https://mlflow.org/docs/latest/index.html).
$DOC_DEFAULT_LOGGER
When MLJBase is first loaded, the default logger is `nothing`. To reset the logger, see
below.
"""
default_logger() = DEFAULT_LOGGER[]
"""
default_logger(logger)
Reset the default logger.
# Example
Suppose an [MLflow](https://mlflow.org/docs/latest/index.html) tracking service is running
on a local server at `http://127.0.0.1:500`. Then every in every `evaluate` call in which
`logger` is not specified, as in the example below, the peformance evaluation is
automatically logged to the service.
```julia
using MLJ
logger = MLJFlow.Logger("http://127.0.0.1:5000/api")
default_logger(logger)
X, y = make_moons()
model = ConstantClassifier()
evaluate(model, X, y, measures=[log_loss, accuracy)])
```
"""
function default_logger(logger)
DEFAULT_LOGGER[] = logger
end
# ===============================================================
## EVALUATION METHODS
# ---------------------------------------------------------------
# Helpers
function actual_rows(rows, N, verbosity)
unspecified_rows = (rows === nothing)
_rows = unspecified_rows ? (1:N) : rows
if !unspecified_rows && verbosity > 0
@info "Creating subsamples from a subset of all rows. "
end
return _rows
end
function _check_measure(measure, operation, model, y)
# get observation scitype:
T = MLJBase.guess_observation_scitype(y)
# get type supported by measure:
T_measure = StatisticalMeasuresBase.observation_scitype(measure)
T == Unknown && (return true)
T_measure == Union{} && (return true)
isnothing(StatisticalMeasuresBase.kind_of_proxy(measure)) && (return true)
T <: T_measure || throw(ERR_MEASURES_OBSERVATION_SCITYPE(measure, T_measure, T))
incompatible = model isa Probabilistic &&
operation == predict &&
StatisticalMeasuresBase.kind_of_proxy(measure) != LearnAPI.Distribution()
if incompatible
if T <: Union{Missing,Finite}
suggestion = LOG_SUGGESTION1
elseif T <: Union{Missing,Infinite}
suggestion = LOG_SUGGESTION2
else
suggestion = ""
end
throw(ERR_MEASURES_PROBABILISTIC(measure, suggestion))
end
model isa Deterministic &&
StatisticalMeasuresBase.kind_of_proxy(measure) != LearnAPI.LiteralTarget() &&
throw(ERR_MEASURES_DETERMINISTIC(measure))
return true
end
function _check_measures(measures, operations, model, y)
all(eachindex(measures)) do j
_check_measure(measures[j], operations[j], model, y)
end
end
function _actual_measures(measures, model)
if measures === nothing
candidate = default_measure(model)
candidate === nothing && error("You need to specify measure=... ")
_measures = [candidate, ]
elseif !(measures isa AbstractVector)
_measures = [measures, ]
else
_measures = measures
end
# wrap in `robust_measure` to allow unsupported weights to be silently treated as
# uniform when invoked; `_check_measure` will throw appropriate warnings unless
# explicitly suppressed.
return StatisticalMeasuresBase.robust_measure.(_measures)
end
function _check_weights(weights, nrows)
length(weights) == nrows ||
throw(ERR_WEIGHTS_LENGTH)
return true
end
function _check_class_weights(weights, levels)
weights isa AbstractDict{<:Any,<:Real} ||
throw(ERR_WEIGHTS_DICT)
Set(levels) == Set(keys(weights)) ||
throw(ERR_WEIGHTS_CLASSES)
return true
end
function _check_weights_measures(weights,
class_weights,
measures,
mach,
operations,
verbosity,
check_measure)
if check_measure || !(weights isa Nothing) || !(class_weights isa Nothing)
y = mach.args[2]()
end
check_measure && _check_measures(measures, operations, mach.model, y)
weights isa Nothing || _check_weights(weights, nrows(y))
class_weights isa Nothing ||
_check_class_weights(class_weights, levels(y))
end
# here `operation` is what the user has specified, and `nothing` if
# not specified:
_actual_operations(operation, measures, args...) =
_actual_operations(fill(operation, length(measures)), measures, args...)
function _actual_operations(operation::AbstractVector, measures, args...)
length(measures) === length(operation) ||
throw(ERR_OPERATION_MEASURE_MISMATCH)
all(operation) do op
op in eval.(PREDICT_OPERATIONS)
end || throw(ERR_INVALID_OPERATION)
return operation
end
function _actual_operations(operation::Nothing,
measures, # vector of measures
model,
verbosity)
map(measures) do m
# `kind_of_proxy` is the measure trait corresponding to `prediction_type` model
# trait. But it's values are instances of LearnAPI.KindOfProxy, instead of
# symbols:
#
# `LearnAPI.LiteralTarget()` ~ `:deterministic` (`model isa Deterministic`)
# `LearnAPI.Distribution()` ~ `:probabilistic` (`model isa Deterministic`)
#
kind_of_proxy = StatisticalMeasuresBase.kind_of_proxy(m)
# `observation_type` is the measure trait which we need to match the model
# `target_scitype` but the latter refers to the whole target `y`, not a single
# observation.
#
# One day, models will have their own `observation_scitype`
observation_scitype = StatisticalMeasuresBase.observation_scitype(m)
# One day, models will implement LearnAPI and will get their own `kind_of_proxy`
# trait replacing `prediction_type` and `observation_scitype` trait replacing
# `target_scitype`.
isnothing(kind_of_proxy) && (return predict)
if MLJBase.prediction_type(model) === :probabilistic
if kind_of_proxy === LearnAPI.Distribution()
return predict
elseif kind_of_proxy === LearnAPI.LiteralTarget()
if observation_scitype <: Union{Missing,Finite}
return predict_mode
elseif observation_scitype <:Union{Missing,Infinite}
return predict_mean
else
throw(err_ambiguous_operation(model, m))
end
else
throw(err_ambiguous_operation(model, m))
end
elseif MLJBase.prediction_type(model) === :deterministic
if kind_of_proxy === LearnAPI.Distribution()
throw(err_incompatible_prediction_types(model, m))
elseif kind_of_proxy === LearnAPI.LiteralTarget()
return predict
else
throw(err_ambiguous_operation(model, m))
end
elseif MLJBase.prediction_type(model) === :interval
if kind_of_proxy === LearnAPI.ConfidenceInterval()
return predict
else
throw(err_ambiguous_operation(model, m))
end
else
throw(err_ambiguous_operation(model, m))
end
end
end
function _warn_about_unsupported(trait, str, measures, weights, verbosity)
if verbosity >= 0 && weights !== nothing
unsupported = filter(measures) do m
!trait(m)
end