-
Notifications
You must be signed in to change notification settings - Fork 29
/
Transformers.jl
2017 lines (1520 loc) · 61 KB
/
Transformers.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
# Note that doc-strings appear at the end
# # IMPUTER
round_median(v::AbstractVector) = v -> round(eltype(v), median(v))
_median(e) = skipmissing(e) |> median
_round_median(e) = skipmissing(e) |> (f -> round(eltype(f), median(f)))
_mode(e) = skipmissing(e) |> mode
@with_kw_noshow mutable struct UnivariateFillImputer <: Unsupervised
continuous_fill::Function = _median
count_fill::Function = _round_median
finite_fill::Function = _mode
end
function MMI.fit(transformer::UnivariateFillImputer,
verbosity::Integer,
v)
filler(v, ::Type) = throw(ArgumentError(
"Imputation is not supported for vectors "*
"of elscitype $(elscitype(v))."))
filler(v, ::Type{<:Union{Continuous,Missing}}) =
transformer.continuous_fill(v)
filler(v, ::Type{<:Union{Count,Missing}}) =
transformer.count_fill(v)
filler(v, ::Type{<:Union{Finite,Missing}}) =
transformer.finite_fill(v)
fitresult = (filler=filler(v, elscitype(v)),)
cache = nothing
report = NamedTuple()
return fitresult, cache, report
end
function replace_missing(::Type{<:Finite}, vnew, filler)
all(in(levels(filler)), levels(vnew)) ||
error(ArgumentError("The `column::AbstractVector{<:Finite}`"*
" to be transformed must contain the same levels"*
" as the categorical value to be imputed"))
replace(vnew, missing => filler)
end
function replace_missing(::Type, vnew, filler)
T = promote_type(nonmissing(eltype(vnew)), typeof(filler))
w_tight = similar(vnew, T)
@inbounds for i in eachindex(vnew)
if ismissing(vnew[i])
w_tight[i] = filler
else
w_tight[i] = vnew[i]
end
end
return w_tight
end
function MMI.transform(transformer::UnivariateFillImputer,
fitresult,
vnew)
filler = fitresult.filler
scitype(filler) <: elscitype(vnew) ||
error("Attempting to impute a value of scitype $(scitype(filler)) "*
"into a vector of incompatible elscitype, namely $(elscitype(vnew)). ")
if elscitype(vnew) >: Missing
w_tight = replace_missing(nonmissing(elscitype(vnew)), vnew, filler)
else
w_tight = vnew
end
return w_tight
end
MMI.fitted_params(::UnivariateFillImputer, fitresult) = fitresult
@with_kw_noshow mutable struct FillImputer <: Unsupervised
features::Vector{Symbol} = Symbol[]
continuous_fill::Function = _median
count_fill::Function = _round_median
finite_fill::Function = _mode
end
function MMI.fit(transformer::FillImputer, verbosity::Int, X)
s = schema(X)
features_seen = s.names |> collect # "seen" = "seen in fit"
scitypes_seen = s.scitypes |> collect
features = isempty(transformer.features) ? features_seen :
transformer.features
issubset(features, features_seen) || throw(ArgumentError(
"Some features specified do not exist in the supplied table. "))
# get corresponding scitypes:
mask = map(features_seen) do ftr
ftr in features
end
features = @view features_seen[mask] # `features` re-ordered
scitypes = @view scitypes_seen[mask]
features_and_scitypes = zip(features, scitypes) #|> collect
# now keep those features that are imputable:
function isimputable(ftr, T::Type)
if verbosity > 0 && !isempty(transformer.features)
@info "Feature $ftr will not be imputed "*
"(imputation for $T not supported). "
end
return false
end
isimputable(ftr, ::Type{<:Union{Continuous,Missing}}) = true
isimputable(ftr, ::Type{<:Union{Count,Missing}}) = true
isimputable(ftr, ::Type{<:Union{Finite,Missing}}) = true
mask = map(features_and_scitypes) do tup
isimputable(tup...)
end
features_to_be_imputed = @view features[mask]
univariate_transformer =
UnivariateFillImputer(continuous_fill=transformer.continuous_fill,
count_fill=transformer.count_fill,
finite_fill=transformer.finite_fill)
univariate_fitresult(ftr) = MMI.fit(univariate_transformer,
verbosity - 1,
selectcols(X, ftr))[1]
fitresult_given_feature =
Dict(ftr=> univariate_fitresult(ftr) for ftr in features_to_be_imputed)
fitresult = (features_seen=features_seen,
univariate_transformer=univariate_transformer,
fitresult_given_feature=fitresult_given_feature)
report = NamedTuple()
cache = nothing
return fitresult, cache, report
end
function MMI.transform(transformer::FillImputer, fitresult, X)
features_seen = fitresult.features_seen # seen in fit
univariate_transformer = fitresult.univariate_transformer
fitresult_given_feature = fitresult.fitresult_given_feature
all_features = Tables.schema(X).names
# check that no new features have appeared:
all(e -> e in features_seen, all_features) || throw(ArgumentError(
"Attempting to transform table with "*
"feature labels not seen in fit.\n"*
"Features seen in fit = $features_seen.\n"*
"Current features = $([all_features...]). "))
features = keys(fitresult_given_feature)
cols = map(all_features) do ftr
col = MMI.selectcols(X, ftr)
if ftr in features
fr = fitresult_given_feature[ftr]
return transform(univariate_transformer, fr, col)
end
return col
end
named_cols = NamedTuple{all_features}(tuple(cols...))
return MMI.table(named_cols, prototype=X)
end
function MMI.fitted_params(::FillImputer, fr)
dict = fr.fitresult_given_feature
filler_given_feature = Dict(ftr=>dict[ftr].filler for ftr in keys(dict))
return (features_seen_in_fit=fr.features_seen,
univariate_transformer=fr.univariate_transformer,
filler_given_feature=filler_given_feature)
end
## UNIVARIATE DISCRETIZER
# helper function:
reftype(::CategoricalArray{<:Any,<:Any,R}) where R = R
@with_kw_noshow mutable struct UnivariateDiscretizer <:Unsupervised
n_classes::Int = 512
end
struct UnivariateDiscretizerResult{C}
odd_quantiles::Vector{Float64}
even_quantiles::Vector{Float64}
element::C
end
function MMI.fit(transformer::UnivariateDiscretizer, verbosity::Int, X)
n_classes = transformer.n_classes
quantiles = quantile(X, Array(range(0, stop=1, length=2*n_classes+1)))
clipped_quantiles = quantiles[2:2*n_classes] # drop 0% and 100% quantiles
# odd_quantiles for transforming, even_quantiles used for
# inverse_transforming:
odd_quantiles = clipped_quantiles[2:2:(2*n_classes-2)]
even_quantiles = clipped_quantiles[1:2:(2*n_classes-1)]
# determine optimal reference type for encoding as categorical:
R = reftype(categorical(1:n_classes, compress=true))
output_prototype = categorical(R(1):R(n_classes), compress=true, ordered=true)
element = output_prototype[1]
cache = nothing
report = NamedTuple()
res = UnivariateDiscretizerResult(odd_quantiles, even_quantiles, element)
return res, cache, report
end
# acts on scalars:
function transform_to_int(
result::UnivariateDiscretizerResult{<:CategoricalValue{R}},
r::Real) where R
k = oneR = R(1)
@inbounds for q in result.odd_quantiles
if r > q
k += oneR
end
end
return k
end
# transforming scalars:
MMI.transform(::UnivariateDiscretizer, result, r::Real) =
transform(result.element, transform_to_int(result, r))
# transforming vectors:
function MMI.transform(::UnivariateDiscretizer, result, v)
w = [transform_to_int(result, r) for r in v]
return transform(result.element, w)
end
# inverse_transforming raw scalars:
function MMI.inverse_transform(
transformer::UnivariateDiscretizer, result , k::Integer)
k <= transformer.n_classes && k > 0 ||
error("Cannot transform an integer outside the range "*
"`[1, n_classes]`, where `n_classes = $(transformer.n_classes)`")
return result.even_quantiles[k]
end
# inverse transforming a categorical value:
function MMI.inverse_transform(
transformer::UnivariateDiscretizer, result, e::CategoricalValue)
k = CategoricalArrays.DataAPI.unwrap(e)
return inverse_transform(transformer, result, k)
end
# inverse transforming raw vectors:
MMI.inverse_transform(transformer::UnivariateDiscretizer, result,
w::AbstractVector{<:Integer}) =
[inverse_transform(transformer, result, k) for k in w]
# inverse transforming vectors of categorical elements:
function MMI.inverse_transform(transformer::UnivariateDiscretizer, result,
wcat::AbstractVector{<:CategoricalValue})
w = MMI.int(wcat)
return [inverse_transform(transformer, result, k) for k in w]
end
MMI.fitted_params(::UnivariateDiscretizer, fitresult) = (
odd_quantiles=fitresult.odd_quantiles,
even_quantiles=fitresult.even_quantiles
)
# # CONTINUOUS TRANSFORM OF TIME TYPE FEATURES
mutable struct UnivariateTimeTypeToContinuous <: Unsupervised
zero_time::Union{Nothing, TimeType}
step::Period
end
function UnivariateTimeTypeToContinuous(;
zero_time=nothing, step=Dates.Hour(24))
model = UnivariateTimeTypeToContinuous(zero_time, step)
message = MMI.clean!(model)
isempty(message) || @warn message
return model
end
function MMI.clean!(model::UnivariateTimeTypeToContinuous)
# Step must be able to be added to zero_time if provided.
msg = ""
if model.zero_time !== nothing
try
tmp = model.zero_time + model.step
catch err
if err isa MethodError
model.zero_time, model.step, status, msg = _fix_zero_time_step(
model.zero_time, model.step)
if status === :error
# Unable to resolve, rethrow original error.
throw(err)
end
else
throw(err)
end
end
end
return msg
end
function _fix_zero_time_step(zero_time, step)
# Cannot add time parts to dates nor date parts to times.
# If a mismatch is encountered. Conversion from date parts to time parts
# is possible, but not from time parts to date parts because we cannot
# represent fractional date parts.
msg = ""
if zero_time isa Dates.Date && step isa Dates.TimePeriod
# Convert zero_time to a DateTime to resolve conflict.
if step % Hour(24) === Hour(0)
# We can convert step to Day safely
msg = "Cannot add `TimePeriod` `step` to `Date` `zero_time`. Converting `step` to `Day`."
step = convert(Day, step)
else
# We need datetime to be compatible with the step.
msg = "Cannot add `TimePeriod` `step` to `Date` `zero_time`. Converting `zero_time` to `DateTime`."
zero_time = convert(DateTime, zero_time)
end
return zero_time, step, :success, msg
elseif zero_time isa Dates.Time && step isa Dates.DatePeriod
# Convert step to Hour if possible. This will fail for
# isa(step, Month)
msg = "Cannot add `DatePeriod` `step` to `Time` `zero_time`. Converting `step` to `Hour`."
step = convert(Hour, step)
return zero_time, step, :success, msg
else
return zero_time, step, :error, msg
end
end
function MMI.fit(model::UnivariateTimeTypeToContinuous, verbosity::Int, X)
if model.zero_time !== nothing
min_dt = model.zero_time
step = model.step
# Check zero_time is compatible with X
example = first(X)
try
X - min_dt
catch err
if err isa MethodError
@warn "`$(typeof(min_dt))` `zero_time` is not compatible with `$(eltype(X))` vector. Attempting to convert `zero_time`."
min_dt = convert(eltype(X), min_dt)
else
throw(err)
end
end
else
min_dt = minimum(X)
step = model.step
message = ""
try
min_dt + step
catch err
if err isa MethodError
min_dt, step, status, message = _fix_zero_time_step(min_dt, step)
if status === :error
# Unable to resolve, rethrow original error.
throw(err)
end
else
throw(err)
end
end
isempty(message) || @warn message
end
cache = nothing
report = NamedTuple()
fitresult = (min_dt, step)
return fitresult, cache, report
end
function MMI.transform(model::UnivariateTimeTypeToContinuous, fitresult, X)
min_dt, step = fitresult
if typeof(min_dt) ≠ eltype(X)
# Cannot run if eltype in transform differs from zero_time from fit.
throw(ArgumentError("Different `TimeType` encountered during `transform` than expected from `fit`. Found `$(eltype(X))`, expected `$(typeof(min_dt))`"))
end
# Set the size of a single step.
next_time = min_dt + step
if next_time == min_dt
# Time type loops if step is a multiple of Hour(24), so calculate the
# number of multiples, then re-scale to Hour(12) and adjust delta to match original.
m = step / Dates.Hour(12)
delta = m * (
Float64(Dates.value(min_dt + Dates.Hour(12)) - Dates.value(min_dt)))
else
delta = Float64(Dates.value(min_dt + step) - Dates.value(min_dt))
end
return @. Float64(Dates.value(X - min_dt)) / delta
end
# # UNIVARIATE STANDARDIZATION
"""
UnivariateStandardizer()
Transformer type for standardizing (whitening) single variable data.
This model may be deprecated in the future. Consider using
[`Standardizer`](@ref), which handles both tabular *and* univariate data.
"""
mutable struct UnivariateStandardizer <: Unsupervised end
function MMI.fit(transformer::UnivariateStandardizer, verbosity::Int,
v::AbstractVector{T}) where T<:Real
stdv = std(v)
stdv > eps(typeof(stdv)) ||
@warn "Extremely small standard deviation encountered in standardization."
fitresult = (mean(v), stdv)
cache = nothing
report = NamedTuple()
return fitresult, cache, report
end
MMI.fitted_params(::UnivariateStandardizer, fitresult) =
(mean=fitresult[1], std=fitresult[2])
# for transforming single value:
function MMI.transform(transformer::UnivariateStandardizer, fitresult, x::Real)
mu, sigma = fitresult
return (x - mu)/sigma
end
# for transforming vector:
MMI.transform(transformer::UnivariateStandardizer, fitresult, v) =
[transform(transformer, fitresult, x) for x in v]
# for single values:
function MMI.inverse_transform(transformer::UnivariateStandardizer, fitresult, y::Real)
mu, sigma = fitresult
return mu + y*sigma
end
# for vectors:
MMI.inverse_transform(transformer::UnivariateStandardizer, fitresult, w) =
[inverse_transform(transformer, fitresult, y) for y in w]
# # STANDARDIZATION OF ORDINAL FEATURES OF TABULAR DATA
mutable struct Standardizer <: Unsupervised
# features to be standardized; empty means all
features::Union{AbstractVector{Symbol}, Function}
ignore::Bool # features to be ignored
ordered_factor::Bool
count::Bool
end
# keyword constructor
function Standardizer(
;
features::Union{AbstractVector{Symbol}, Function}=Symbol[],
ignore::Bool=false,
ordered_factor::Bool=false,
count::Bool=false
)
transformer = Standardizer(features, ignore, ordered_factor, count)
message = MMI.clean!(transformer)
isempty(message) || throw(ArgumentError(message))
return transformer
end
function MMI.clean!(transformer::Standardizer)
err = ""
if (
typeof(transformer.features) <: AbstractVector{Symbol} &&
isempty(transformer.features) &&
transformer.ignore
)
err *= "Features to be ignored must be specified in features field."
end
return err
end
function MMI.fit(transformer::Standardizer, verbosity::Int, X)
# if not a table, it must be an abstract vector, eltpye AbstractFloat:
is_univariate = !Tables.istable(X)
# are we attempting to standardize Count or OrderedFactor?
is_invertible = !transformer.count && !transformer.ordered_factor
# initialize fitresult:
fitresult_given_feature = LittleDict{Symbol,Tuple{AbstractFloat,AbstractFloat}}()
# special univariate case:
if is_univariate
fitresult_given_feature[:unnamed] =
MMI.fit(UnivariateStandardizer(), verbosity - 1, X)[1]
return (is_univariate=true,
is_invertible=true,
fitresult_given_feature=fitresult_given_feature),
nothing, nothing
end
all_features = Tables.schema(X).names
feature_scitypes =
collect(elscitype(selectcols(X, c)) for c in all_features)
scitypes = Vector{Type}([Continuous])
transformer.ordered_factor && push!(scitypes, OrderedFactor)
transformer.count && push!(scitypes, Count)
AllowedScitype = Union{scitypes...}
# determine indices of all_features to be transformed
if transformer.features isa AbstractVector{Symbol}
if isempty(transformer.features)
cols_to_fit = filter!(eachindex(all_features) |> collect) do j
feature_scitypes[j] <: AllowedScitype
end
else
!issubset(transformer.features, all_features) && verbosity > -1 &&
@warn "Some specified features not present in table to be fit. "
cols_to_fit = filter!(eachindex(all_features) |> collect) do j
ifelse(
transformer.ignore,
!(all_features[j] in transformer.features) &&
feature_scitypes[j] <: AllowedScitype,
(all_features[j] in transformer.features) &&
feature_scitypes[j] <: AllowedScitype
)
end
end
else
cols_to_fit = filter!(eachindex(all_features) |> collect) do j
ifelse(
transformer.ignore,
!(transformer.features(all_features[j])) &&
feature_scitypes[j] <: AllowedScitype,
(transformer.features(all_features[j])) &&
feature_scitypes[j] <: AllowedScitype
)
end
end
isempty(cols_to_fit) && verbosity > -1 &&
@warn "No features to standarize."
# fit each feature and add result to above dict
verbosity > 1 && @info "Features standarized: "
for j in cols_to_fit
col_data = if (feature_scitypes[j] <: OrderedFactor)
coerce(selectcols(X, j), Continuous)
else
selectcols(X, j)
end
col_fitresult, _, _ =
MMI.fit(UnivariateStandardizer(), verbosity - 1, col_data)
fitresult_given_feature[all_features[j]] = col_fitresult
verbosity > 1 &&
@info " :$(all_features[j]) mu=$(col_fitresult[1]) "*
"sigma=$(col_fitresult[2])"
end
fitresult = (is_univariate=false, is_invertible=is_invertible,
fitresult_given_feature=fitresult_given_feature)
cache = nothing
report = (features_fit=keys(fitresult_given_feature),)
return fitresult, cache, report
end
function MMI.fitted_params(::Standardizer, fitresult)
is_univariate, _, dic = fitresult
is_univariate &&
return fitted_params(UnivariateStandardizer(), dic[:unnamed])
features_fit = keys(dic) |> collect
zipped = map(ftr->dic[ftr], features_fit)
means, stds = zip(zipped...) |> collect
return (; features_fit, means, stds)
end
MMI.transform(::Standardizer, fitresult, X) =
_standardize(transform, fitresult, X)
function MMI.inverse_transform(::Standardizer, fitresult, X)
fitresult.is_invertible ||
error("Inverse standardization is not supported when `count=true` "*
"or `ordered_factor=true` during fit. ")
return _standardize(inverse_transform, fitresult, X)
end
function _standardize(operation, fitresult, X)
# `fitresult` is dict of column fitresults, keyed on feature names
is_univariate, _, fitresult_given_feature = fitresult
if is_univariate
univariate_fitresult = fitresult_given_feature[:unnamed]
return operation(UnivariateStandardizer(), univariate_fitresult, X)
end
features_to_be_transformed = keys(fitresult_given_feature)
all_features = Tables.schema(X).names
all(e -> e in all_features, features_to_be_transformed) ||
error("Attempting to transform data with incompatible feature labels.")
col_transformer = UnivariateStandardizer()
cols = map(all_features) do ftr
ftr_data = selectcols(X, ftr)
if ftr in features_to_be_transformed
col_to_transform = coerce(ftr_data, Continuous)
operation(col_transformer,
fitresult_given_feature[ftr],
col_to_transform)
else
ftr_data
end
end
named_cols = NamedTuple{all_features}(tuple(cols...))
return MMI.table(named_cols, prototype=X)
end
# # UNIVARIATE BOX-COX TRANSFORMATIONS
function standardize(v)
map(v) do x
(x - mean(v))/std(v)
end
end
function midpoints(v::AbstractVector{T}) where T <: Real
return [0.5*(v[i] + v[i + 1]) for i in 1:(length(v) -1)]
end
function normality(v)
n = length(v)
v = standardize(convert(Vector{Float64}, v))
# sort and replace with midpoints
v = midpoints(sort!(v))
# find the (approximate) expected value of the size (n-1)-ordered statistics for
# standard normal:
d = Distributions.Normal(0,1)
w = map(collect(1:(n-1))/n) do x
quantile(d, x)
end
return cor(v, w)
end
function boxcox(lambda, c, x::Real)
c + x >= 0 || throw(DomainError)
if lambda == 0.0
c + x > 0 || throw(DomainError)
return log(c + x)
end
return ((c + x)^lambda - 1)/lambda
end
boxcox(lambda, c, v::AbstractVector{T}) where T <: Real =
[boxcox(lambda, c, x) for x in v]
@with_kw_noshow mutable struct UnivariateBoxCoxTransformer <: Unsupervised
n::Int = 171 # nbr values tried in optimizing exponent lambda
shift::Bool = false # whether to shift data away from zero
end
function MMI.fit(transformer::UnivariateBoxCoxTransformer, verbosity::Int,
v::AbstractVector{T}) where T <: Real
m = minimum(v)
m >= 0 || error("Cannot perform a Box-Cox transformation on negative data.")
c = 0.0 # default
if transformer.shift
if m == 0
c = 0.2*mean(v)
end
else
m != 0 || error("Zero value encountered in data being Box-Cox transformed.\n"*
"Consider calling `fit!` with `shift=true`.")
end
lambdas = range(-0.4, stop=3, length=transformer.n)
scores = Float64[normality(boxcox(l, c, v)) for l in lambdas]
lambda = lambdas[argmax(scores)]
return (lambda, c), nothing, NamedTuple()
end
MMI.fitted_params(::UnivariateBoxCoxTransformer, fitresult) =
(λ=fitresult[1], c=fitresult[2])
# for X scalar or vector:
MMI.transform(transformer::UnivariateBoxCoxTransformer, fitresult, X) =
boxcox(fitresult..., X)
# scalar case:
function MMI.inverse_transform(transformer::UnivariateBoxCoxTransformer,
fitresult, x::Real)
lambda, c = fitresult
if lambda == 0
return exp(x) - c
else
return (lambda*x + 1)^(1/lambda) - c
end
end
# vector case:
function MMI.inverse_transform(transformer::UnivariateBoxCoxTransformer,
fitresult, w::AbstractVector{T}) where T <: Real
return [inverse_transform(transformer, fitresult, y) for y in w]
end
# # ONE HOT ENCODING
@with_kw_noshow mutable struct OneHotEncoder <: Unsupervised
features::Vector{Symbol} = Symbol[]
drop_last::Bool = false
ordered_factor::Bool = true
ignore::Bool = false
end
# we store the categorical refs for each feature to be encoded and the
# corresponing feature labels generated (called
# "names"). `all_features` is stored to ensure no new features appear
# in new input data, causing potential name clashes.
struct OneHotEncoderResult <: MMI.MLJType
all_features::Vector{Symbol} # all feature labels
ref_name_pairs_given_feature::Dict{Symbol,Vector{Union{Pair{<:Unsigned,Symbol}, Pair{Missing, Symbol}}}}
fitted_levels_given_feature::Dict{Symbol, CategoricalArray}
end
# join feature and level into new label without clashing with anything
# in all_features:
function compound_label(all_features, feature, level)
label = Symbol(string(feature, "__", level))
# in the (rare) case subft is not a new feature label:
while label in all_features
label = Symbol(string(label,"_"))
end
return label
end
function MMI.fit(transformer::OneHotEncoder, verbosity::Int, X)
all_features = Tables.schema(X).names # a tuple not vector
if isempty(transformer.features)
specified_features = collect(all_features)
else
if transformer.ignore
specified_features = filter(all_features |> collect) do ftr
!(ftr in transformer.features)
end
else
specified_features = transformer.features
end
end
ref_name_pairs_given_feature = Dict{Symbol,Vector{Pair{<:Unsigned,Symbol}}}()
allowed_scitypes = ifelse(
transformer.ordered_factor,
Union{Missing, Finite},
Union{Missing, Multiclass}
)
fitted_levels_given_feature = Dict{Symbol, CategoricalArray}()
col_scitypes = schema(X).scitypes
# apply on each feature
for j in eachindex(all_features)
ftr = all_features[j]
col = MMI.selectcols(X,j)
T = col_scitypes[j]
if T <: allowed_scitypes && ftr in specified_features
ref_name_pairs_given_feature[ftr] = Pair{<:Unsigned,Symbol}[]
shift = transformer.drop_last ? 1 : 0
levels = classes(col)
fitted_levels_given_feature[ftr] = levels
if verbosity > 0
@info "Spawning $(length(levels)-shift) sub-features "*
"to one-hot encode feature :$ftr."
end
for level in levels[1:end-shift]
ref = MMI.int(level)
name = compound_label(all_features, ftr, level)
push!(ref_name_pairs_given_feature[ftr], ref => name)
end
end
end
fitresult = OneHotEncoderResult(collect(all_features),
ref_name_pairs_given_feature,
fitted_levels_given_feature)
# get new feature names
d = ref_name_pairs_given_feature
new_features = Symbol[]
features_to_be_transformed = keys(d)
for ftr in all_features
if ftr in features_to_be_transformed
append!(new_features, last.(d[ftr]))
else
push!(new_features, ftr)
end
end
report = (features_to_be_encoded=
collect(keys(ref_name_pairs_given_feature)),
new_features=new_features)
cache = nothing
return fitresult, cache, report
end
MMI.fitted_params(::OneHotEncoder, fitresult) = (
all_features = fitresult.all_features,
fitted_levels_given_feature = fitresult.fitted_levels_given_feature,
ref_name_pairs_given_feature = fitresult.ref_name_pairs_given_feature,
)
# If v=categorical('a', 'a', 'b', 'a', 'c') and MMI.int(v[1]) = ref
# then `_hot(v, ref) = [true, true, false, true, false]`
hot(v::AbstractVector{<:CategoricalValue}, ref) = map(v) do c
MMI.int(c) == ref
end
function hot(col::AbstractVector{<:Union{Missing, CategoricalValue}}, ref) map(col) do c
if ismissing(ref)
missing
else
MMI.int(c) == ref
end
end
end
function MMI.transform(transformer::OneHotEncoder, fitresult, X)
features = Tables.schema(X).names # tuple not vector
d = fitresult.ref_name_pairs_given_feature
# check the features match the fit result
all(e -> e in fitresult.all_features, features) ||
error("Attempting to transform table with feature "*
"names not seen in fit. ")
new_features = Symbol[]
new_cols = [] # not Vector[] !!
features_to_be_transformed = keys(d)
for ftr in features
col = MMI.selectcols(X, ftr)
if ftr in features_to_be_transformed
Set(fitresult.fitted_levels_given_feature[ftr]) ==
Set(classes(col)) ||
error("Found category level mismatch in feature `$(ftr)`. "*
"Consider using `levels!` to ensure fitted and transforming "*
"features have the same category levels.")
append!(new_features, last.(d[ftr]))
pairs = d[ftr]
refs = first.(pairs)
names = last.(pairs)
cols_to_add = map(refs) do ref
if ismissing(ref) missing
else float.(hot(col, ref))
end
end
append!(new_cols, cols_to_add)
else
push!(new_features, ftr)
push!(new_cols, col)
end
end
named_cols = NamedTuple{tuple(new_features...)}(tuple(new_cols)...)
return MMI.table(named_cols, prototype=X)
end
# # CONTINUOUS_ENCODING
@with_kw_noshow mutable struct ContinuousEncoder <: Unsupervised
drop_last::Bool = false
one_hot_ordered_factors::Bool = false
end
function MMI.fit(transformer::ContinuousEncoder, verbosity::Int, X)
# what features can be converted and therefore kept?
s = schema(X)
features = s.names
scitypes = s.scitypes
Convertible = Union{Continuous, Finite, Count}
feature_scitype_tuples = zip(features, scitypes) |> collect
features_to_keep =
first.(filter(t -> last(t) <: Convertible, feature_scitype_tuples))
features_to_be_dropped = setdiff(collect(features), features_to_keep)
if verbosity > 0
if !isempty(features_to_be_dropped)
@info "Some features cannot be replaced with "*
"`Continuous` features and will be dropped: "*
"$features_to_be_dropped. "
end
end
# fit the one-hot encoder:
hot_encoder =
OneHotEncoder(ordered_factor=transformer.one_hot_ordered_factors,
drop_last=transformer.drop_last)
hot_fitresult, _, hot_report = MMI.fit(hot_encoder, verbosity - 1, X)
new_features = setdiff(hot_report.new_features, features_to_be_dropped)
fitresult = (features_to_keep=features_to_keep,
one_hot_encoder=hot_encoder,
one_hot_encoder_fitresult=hot_fitresult)
# generate the report:
report = (features_to_keep=features_to_keep,
new_features=new_features)
cache = nothing
return fitresult, cache, report
end
MMI.fitted_params(::ContinuousEncoder, fitresult) = fitresult
function MMI.transform(transformer::ContinuousEncoder, fitresult, X)
features_to_keep, hot_encoder, hot_fitresult = values(fitresult)
# dump unseen or untransformable features:
if !issubset(features_to_keep, MMI.schema(X).names)
throw(
ArgumentError(
"Supplied frame does not admit previously selected features."
)
)
end
X0 = MMI.selectcols(X, features_to_keep)
# one-hot encode:
X1 = transform(hot_encoder, hot_fitresult, X0)
# convert remaining to continuous:
return coerce(X1, Count=>Continuous, OrderedFactor=>Continuous)
end
# # INTERACTION TRANSFORMER
@mlj_model mutable struct InteractionTransformer <: Static
order::Int = 2::(_ > 1)
features::Union{Nothing, Vector{Symbol}} = nothing::(_ !== nothing ? length(_) > 1 : true)
end
infinite_scitype(col) = eltype(scitype(col)) <: Infinite
actualfeatures(features::Nothing, table) =
filter(feature -> infinite_scitype(Tables.getcolumn(table, feature)), Tables.columnnames(table))
function actualfeatures(features::Vector{Symbol}, table)
diff = setdiff(features, Tables.columnnames(table))
diff != [] && throw(ArgumentError(string("Column(s) ", join([x for x in diff], ", "), " are not in the dataset.")))
for feature in features
infinite_scitype(Tables.getcolumn(table, feature)) || throw(ArgumentError("Column $feature's scitype is not Infinite."))
end
return Tuple(features)
end
interactions(columns, order::Int) =
collect(Iterators.flatten(combinations(columns, i) for i in 2:order))
interactions(columns, variables...) =
.*((Tables.getcolumn(columns, var) for var in variables)...)
function MMI.transform(model::InteractionTransformer, _, X)
features = actualfeatures(model.features, X)
interactions_ = interactions(features, model.order)
interaction_features = Tuple(Symbol(join(inter, "_")) for inter in interactions_)
columns = Tables.Columns(X)
interaction_table = NamedTuple{interaction_features}([interactions(columns, inter...) for inter in interactions_])
return merge(Tables.columntable(X), interaction_table)
end