/
Processing.jl
1451 lines (1218 loc) · 51.3 KB
/
Processing.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
"Part of [BetaML](https://github.com/sylvaticus/BetaML.jl). Licence is MIT."
# Part of submodule Utils of BetaML - The Beta Machine Learning Toolkit
# Functions typically used for processing (manipulating) data, typically preprocessing data before running a ML model
import StatsBase: countmap
# ------------------------------------------------------------------------------
# Various reshaping functions
import Base.reshape
""" reshape(myNumber, dims..) - Reshape a number as a n dimensional Array """
reshape(x::T, dims...) where {T <: Number} = (x = [x]; reshape(x,dims) )
makecolvector(x::T) where {T} = [x]
makecolvector(x::T) where {T <: AbstractArray} = reshape(x,length(x))
makerowvector(x::T) where {T <: Number} = return [x]'
makerowvector(x::T) where {T <: AbstractArray} = reshape(x,1,length(x))
"""Transform an Array{T,1} in an Array{T,2} and leave unchanged Array{T,2}."""
makematrix(x::AbstractVector) = reshape(x, (size(x)...,1))
makematrix(x::AbstractMatrix) = x
"""Return wheather an array is sortable, i.e. has methos issort defined"""
issortable(::AbstractArray{T,N}) where {T,N} = hasmethod(isless, Tuple{nonmissingtype(T),nonmissingtype(T)})
allowmissing(x::AbstractArray{T,N}) where {T,N} = convert(Union{Array{T,N},Missing},x)
disallowmissing(x::AbstractArray{T,N}) where {T,N} = convert(Array{nonmissingtype(T),N},x)
"""
getpermutations(v::AbstractArray{T,1};keepStructure=false)
Return a vector of either (a) all possible permutations (uncollected) or (b) just those based on the unique values of the vector
Useful to measure accuracy where you don't care about the actual name of the labels, like in unsupervised classifications (e.g. clustering)
"""
function getpermutations(v::AbstractArray{T,1};keepStructure=false) where {T}
if !keepStructure
return Combinatorics.permutations(v)
else
classes = unique(v)
nCl = length(classes)
N = size(v,1)
pSet = Combinatorics.permutations(1:nCl)
nP = length(pSet)
vPermutations = fill(similar(v),nP)
vOrigIdx = [findfirst(x -> x == v[i] , classes) for i in 1:N]
for (pIdx,perm) in enumerate(pSet)
vPermutations[pIdx] = classes[perm[vOrigIdx]] # permuted specific version
end
return vPermutations
end
end
""" singleunique(x) Return the unique values of x whether x is an array of arrays, an array or a scalar"""
function singleunique(x::Union{T,AbstractArray{T}}) where {T <: Union{Any,AbstractArray{T2}} where T2 <: Any }
if typeof(x) <: AbstractArray{T2} where {T2 <: AbstractArray}
return unique(vcat(unique.(x)...))
elseif typeof(x) <: AbstractArray{T2} where {T2}
return unique(x)
else
return [x]
end
end
# API V2 for encoders
"""
$(TYPEDEF)
Hyperparameters for both [`OneHotEncoder`](@ref) and [`OrdinalEncoder`](@ref)
# Parameters:
$(FIELDS)
"""
Base.@kwdef mutable struct OneHotE_hp <: BetaMLHyperParametersSet
"The categories to represent as columns. [def: `nothing`, i.e. unique training values or range for integers]. Do not include `missing` in this list."
categories::Union{Vector,Nothing} = nothing
"How to handle categories not seen in training or not present in the provided `categories` array? \"error\" (default) rises an error, \"missing\" labels the whole output with missing values, \"infrequent\" adds a specific column for these categories in one-hot encoding or a single new category for ordinal one."
handle_unknown::String = "error"
"Which value during inverse transformation to assign to the \"other\" category (i.e. categories not seen on training or not present in the provided `categories` array? [def: ` nothing`, i.e. typemax(Int64) for integer vectors and \"other\" for other types]. This setting is active only if `handle_unknown=\"infrequent\"` and in that case it MUST be specified if the vector to one-hot encode is neither integer or strings"
other_categories_name = nothing
end
Base.@kwdef mutable struct OneHotEncoder_lp <: BetaMLLearnableParametersSet
categories_applied::Vector = []
original_vector_eltype::Union{Type,Nothing} = nothing
end
"""
$(TYPEDEF)
Encode a vector of categorical values as one-hot columns.
The algorithm distinguishes between _missing_ values, for which it returns a one-hot encoded row of missing values, and _other_ categories not in the provided list or not seen during training that are handled according to the `handle_unknown` parameter.
For the parameters see [`OneHotE_hp`](@ref) and [`BML_options`](@ref). This model supports `inverse_predict`.
# Example:
```julia
julia> using BetaML
julia> x = ["a","d","e","c","d"];
julia> mod = OneHotEncoder(handle_unknown="infrequent",other_categories_name="zz")
A OneHotEncoder BetaMLModel (unfitted)
julia> x_oh = fit!(mod,x) # last col is for the "infrequent" category
5×5 Matrix{Bool}:
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 1 0 0 0
julia> x2 = ["a","b","c"];
julia> x2_oh = predict(mod,x2)
3×5 Matrix{Bool}:
1 0 0 0 0
0 0 0 0 1
0 0 0 1 0
julia> x2_back = inverse_predict(mod,x2_oh)
3-element Vector{String}:
"a"
"zz"
"c"
```
"""
mutable struct OneHotEncoder <: BetaMLUnsupervisedModel
hpar::OneHotE_hp
opt::BML_options
par::Union{Nothing,OneHotEncoder_lp}
cres::Union{Nothing,Matrix{Bool},Matrix{Union{Bool,Missing}}}
fitted::Bool
info::Dict{String,Any}
end
"""
$(TYPEDEF)
Encode a vector of categorical values as integers.
The algorithm distinguishes between _missing_ values, for which it propagate the missing, and _other_ categories not in the provided list or not seen during training that are handled according to the `handle_unknown` parameter.
For the parameters see [`OneHotE_hp`](@ref) and [`BML_options`](@ref). This model supports `inverse_predict`.
# Example:
```julia
julia> using BetaML
julia> x = ["a","d","e","c","d"];
julia> mod = OrdinalEncoder(handle_unknown="infrequent",other_categories_name="zz")
A OrdinalEncoder BetaMLModel (unfitted)
julia> x_int = fit!(mod,x)
5-element Vector{Int64}:
1
2
3
4
2
julia> x2 = ["a","b","c","g"];
julia> x2_int = predict(mod,x2) # 5 is for the "infrequent" category
4-element Vector{Int64}:
1
5
4
5
julia> x2_back = inverse_predict(mod,x2_oh)
4-element Vector{String}:
"a"
"zz"
"c"
"zz"
```
"""
mutable struct OrdinalEncoder <: BetaMLUnsupervisedModel
hpar::OneHotE_hp
opt::BML_options
par::Union{Nothing,OneHotEncoder_lp}
cres::Union{Nothing,Vector{Int64},Vector{Union{Int64,Missing}}}
fitted::Bool
info::Dict{String,Any}
end
function OneHotEncoder(;kwargs...)
m = OneHotEncoder(OneHotE_hp(),BML_options(),OneHotEncoder_lp(),nothing,false,Dict{Symbol,Any}())
thisobjfields = fieldnames(nonmissingtype(typeof(m)))
for (kw,kwv) in kwargs
found = false
for f in thisobjfields
fobj = getproperty(m,f)
if kw in fieldnames(typeof(fobj))
setproperty!(fobj,kw,kwv)
found = true
end
end
found || error("Keyword \"$kw\" is not part of this model.")
end
return m
end
function OrdinalEncoder(;kwargs...)
m = OrdinalEncoder(OneHotE_hp(),BML_options(),OneHotEncoder_lp(),nothing,false,Dict{Symbol,Any}())
thisobjfields = fieldnames(nonmissingtype(typeof(m)))
for (kw,kwv) in kwargs
found = false
for f in thisobjfields
fobj = getproperty(m,f)
if kw in fieldnames(typeof(fobj))
setproperty!(fobj,kw,kwv)
found = true
end
end
found || error("Keyword \"$kw\" is not part of this model.")
end
return m
end
function _fit!(m::Union{OneHotEncoder,OrdinalEncoder},x,enctype::Symbol)
x = makecolvector(x)
N = size(x,1)
vtype = eltype(x) # nonmissingtype(eltype(x))
# Parameter aliases
categories = m.hpar.categories
handle_unknown = m.hpar.handle_unknown
other_categories_name = m.hpar.other_categories_name
if isnothing(other_categories_name)
if nonmissingtype(vtype) <: Integer
other_categories_name = typemax(Int64)
else
other_categories_name = "other"
end
end
cache = m.opt.cache
verbosity = m.opt.verbosity
rng = m.opt.rng
if nonmissingtype(vtype) <: Number && !(nonmissingtype(vtype) <: Integer)
# continuous column: we just apply identity
m.par = OneHotEncoder_lp([],vtype)
return cache ? nothing : x
end
if isnothing(categories)
if nonmissingtype(vtype) <: Integer
minx = minimum(x)
maxx = maximum(x)
categories_applied = collect(minx:maxx)
else
categories_applied = collect(skipmissing(unique(x)))
end
else
categories_applied = deepcopy(categories)
end
handle_unknown == "infrequent" && push!(categories_applied,other_categories_name)
m.par = OneHotEncoder_lp(categories_applied,vtype)
if cache
if enctype == :onehot
K = length(categories_applied)
outx = fill(false,N,K)
else
K = 1
outx = zeros(Int64,N,K)
end
for n in 1:N
if ismissing(x[n])
outx = (enctype == :onehot) ? convert(Matrix{Union{Missing,Bool}},outx) : convert(Matrix{Union{Missing,Int64}},outx)
outx[n,:] = fill(missing,K)
continue
end
kidx = findfirst(y -> isequal(y,x[n]),categories_applied)
if isnothing(kidx)
if handle_unknown == "error"
error("Found a category ($(x[n])) not present in the list and the `handle_unknown` is set to `error`. Perhaps you want to swith it to either `missing` or `infrequent`.")
elseif handle_unknown == "missing"
outx = (enctype == :onehot) ? convert(Matrix{Union{Missing,Bool}},outx) : convert(Matrix{Union{Missing,Int64}},outx)
outx[n,:] = fill(missing,K);
continue
elseif handle_unknown == "infrequent"
outx[n,K] = (enctype == :onehot) ? true : length(categories_applied)
continue
else
error("I don't know how to process `handle_unknown == $(handle_unknown)`")
end
end
enctype == :onehot ? (outx[n,kidx] = true) : outx[n,1] = kidx
end
m.cres = (enctype == :onehot) ? outx : collect(dropdims(outx,dims=2))
end
m.info["fitted_records"] = get(m.info,"fitted_records",0) + size(x,1)
m.info["n_categories"] = length(categories_applied)
m.fitted = true
return cache ? m.cres : nothing
end
fit!(m::OneHotEncoder,x) = _fit!(m,x,:onehot)
fit!(m::OrdinalEncoder,x) = _fit!(m,x,:ordinal)
function _predict(m::Union{OneHotEncoder,OrdinalEncoder},x,enctype::Symbol)
x = makecolvector(x)
N = size(x,1)
vtype = eltype(x) # nonmissingtype(eltype(x))
# Parameter aliases
handle_unknown = m.hpar.handle_unknown
categories_applied = m.par.categories_applied
if enctype == :onehot
K = length(categories_applied)
outx = fill(false,N,K)
else
K = 1
outx = zeros(Int64,N,K)
end
for n in 1:N
if ismissing(x[n])
outx = (enctype == :onehot) ? convert(Matrix{Union{Missing,Bool}},outx) : convert(Matrix{Union{Missing,Int64}},outx)
outx[n,:] = fill(missing,K)
continue
end
kidx = findfirst(y -> isequal(y,x[n]),categories_applied)
if isnothing(kidx)
if handle_unknown == "error"
error("Found a category ($(x[n])) not present in the list and the `handle_unknown` is set to `error`. Perhaps you want to swith it to either `missing` or `infrequent`.")
continue
elseif handle_unknown == "missing"
outx = (enctype == :onehot) ? convert(Matrix{Union{Missing,Bool}},outx) : convert(Matrix{Union{Missing,Int64}},outx)
outx[n,:] = fill(missing,K);
continue
elseif handle_unknown == "infrequent"
outx[n,K] = (enctype == :onehot) ? true : length(categories_applied)
continue
else
error("I don't know how to process `handle_unknown == $(handle_unknown)`")
end
else
enctype == :onehot ? (outx[n,kidx] = true) : outx[n,1] = kidx
end
end
return (enctype == :onehot) ? outx : dropdims(outx,dims=2)
end
# Case where X is a vector of dictionaries
function _predict(m::Union{OneHotEncoder,OrdinalEncoder},x::Vector{<:Dict},enctype::Symbol)
N = size(x,1)
# Parameter aliases
handle_unknown = m.hpar.handle_unknown
categories_applied = m.par.categories_applied
if enctype == :onehot
K = length(categories_applied)
outx = fill(0.0,N,K)
else
error("Predictions of a Ordinal Encoded with a vector of dictionary is not supported")
end
for n in 1:N
for (k,v) in x[n]
kidx = findfirst(y -> isequal(y,k),categories_applied)
if isnothing(kidx)
if handle_unknown == "error"
error("Found a category ($(k)) not present in the list and the `handle_unknown` is set to `error`. Perhaps you want to swith it to either `missing` or `infrequent`.")
continue
elseif handle_unknown == "missing"
outx[n,:] = fill(missing,K);
continue
elseif handle_unknown == "infrequent"
outx[n,K] = v
continue
else
error("I don't know how to process `handle_unknown == $(handle_unknown)`")
end
else
outx[n,kidx] = v
end
end
end
return outx
end
predict(m::OneHotEncoder,x) = _predict(m,x,:onehot)
predict(m::OrdinalEncoder,x) = _predict(m,x,:ordinal)
function _inverse_predict(m,x,enctype::Symbol)
# Parameter aliases
handle_unknown = m.hpar.handle_unknown
categories_applied = m.par.categories_applied
original_vector_eltype = m.par.original_vector_eltype
other_categories_name = m.hpar.other_categories_name
if isnothing(other_categories_name)
if nonmissingtype(original_vector_eltype ) <: Integer
other_categories_name = typemax(Int64)
else
other_categories_name = "other"
end
end
N,D = size(x,1),size(x,2)
outx = Array{original_vector_eltype,1}(undef,N)
for n in 1:N
if enctype == :onehot
if any(ismissing.(x[n,:]))
outx[n] = missing
continue
elseif handle_unknown == "infrequent" && findfirst(c->c==true,x[n,:]) == D
outx[n] = other_categories_name
continue
end
outx[n] = categories_applied[findfirst(c->c==true,x[n,:])]
else
if ismissing(x[n])
outx[n] = missing
continue
elseif handle_unknown == "infrequent" && x[n] == length(categories_applied)
outx[n] = other_categories_name
continue
end
outx[n] = categories_applied[x[n]]
end
end
return outx
end
inverse_predict(m::OneHotEncoder,x::AbstractMatrix{<:Union{Int64,Bool,Missing}}) = _inverse_predict(m,x,:onehot)
function inverse_predict(m::OneHotEncoder,x::AbstractMatrix{<:Float64})
x2 = fit!(OneHotEncoder(categories=1:size(x,2)),mode(x))
return inverse_predict(m,x2)
end
inverse_predict(m::OrdinalEncoder,x) = _inverse_predict(m,x,:ordinal)
"""
partition(data,parts;shuffle,dims,rng)
Partition (by rows) one or more matrices according to the shares in `parts`.
# Parameters
* `data`: A matrix/vector or a vector of matrices/vectors
* `parts`: A vector of the required shares (must sum to 1)
* `shufle`: Whether to randomly shuffle the matrices (preserving the relative order between matrices)
* `dims`: The dimension for which to partition [def: `1`]
* `copy`: Wheter to _copy_ the actual data or only create a reference [def: `true`]
* `rng`: Random Number Generator (see [`FIXEDSEED`](@ref)) [deafult: `Random.GLOBAL_RNG`]
# Notes:
* The sum of parts must be equal to 1
* The number of elements in the specified dimension must be the same for all the arrays in `data`
# Example:
```julia
julia> x = [1:10 11:20]
julia> y = collect(31:40)
julia> ((xtrain,xtest),(ytrain,ytest)) = partition([x,y],[0.7,0.3])
```
"""
function partition(data::AbstractArray{T,1},parts::AbstractArray{Float64,1};shuffle=true,dims=1,copy=true,rng = Random.GLOBAL_RNG) where T <: AbstractArray
# the sets of vector/matrices
N = size(data[1],dims)
all(size.(data,dims) .== N) || @error "All matrices passed to `partition` must have the same number of elements for the required dimension"
ridx = shuffle ? Random.shuffle(rng,1:N) : collect(1:N)
return partition.(data,Ref(parts);shuffle=shuffle,dims=dims,fixed_ridx = ridx,copy=copy,rng=rng)
end
function partition(data::AbstractArray{T,Ndims}, parts::AbstractArray{Float64,1};shuffle=true,dims=1,fixed_ridx=Int64[],copy=true,rng = Random.GLOBAL_RNG) where {T,Ndims}
# the individual vector/matrix
N = size(data,dims)
nParts = size(parts)
toReturn = toReturn = Array{AbstractArray{T,Ndims},1}(undef,nParts)
if !(sum(parts) ≈ 1)
@error "The sum of `parts` in `partition` should total to 1."
end
ridx = fixed_ridx
if (isempty(ridx))
ridx = shuffle ? Random.shuffle(rng, 1:N) : collect(1:N)
end
allDimIdx = convert(Vector{Union{UnitRange{Int64},Vector{Int64}}},[1:i for i in size(data)])
current = 1
cumPart = 0.0
for (i,p) in enumerate(parts)
cumPart += parts[i]
final = i == nParts ? N : Int64(round(cumPart*N))
allDimIdx[dims] = ridx[current:final]
toReturn[i] = copy ? data[allDimIdx...] : @views data[allDimIdx...]
current = (final +=1)
end
return toReturn
end
# API V2 for Scale
abstract type AbstractScaler end
abstract type AbstractScalerLearnableParameter end
"""
$(TYPEDEF)
Scale the data to a given (def: unit) hypercube
# Parameters:
$(FIELDS)
# Example:
```julia
julia> using BetaML
julia> x = [[4000,1000,2000,3000] ["a", "categorical", "variable", "not to scale"] [4,1,2,3] [0.4, 0.1, 0.2, 0.3]]
4×4 Matrix{Any}:
4000 "a" 4 0.4
1000 "categorical" 1 0.1
2000 "variable" 2 0.2
3000 "not to scale" 3 0.3
julia> mod = Scaler(MinMaxScaler(outputRange=(0,10)), skip=[2])
A Scaler BetaMLModel (unfitted)
julia> xscaled = fit!(mod,x)
4×4 Matrix{Any}:
10.0 "a" 10.0 10.0
0.0 "categorical" 0.0 0.0
3.33333 "variable" 3.33333 3.33333
6.66667 "not to scale" 6.66667 6.66667
julia> xback = inverse_predict(mod, xscaled)
4×4 Matrix{Any}:
4000.0 "a" 4.0 0.4
1000.0 "categorical" 1.0 0.1
2000.0 "variable" 2.0 0.2
3000.0 "not to scale" 3.0 0.3
```
"""
Base.@kwdef mutable struct MinMaxScaler <: AbstractScaler
"The range of the input. [def: (minimum,maximum)]. Both ranges are functions of the data. You can consider other relative of absolute ranges using e.g. `inputRange=(x->minimum(x)*0.8,x->100)`"
inputRange::Tuple{Function,Function} = (minimum,maximum)
"The range of the scaled output [def: (0,1)]"
outputRange::Tuple{Real,Real} = (0,1)
end
Base.@kwdef mutable struct MinMaxScaler_lp <: AbstractScalerLearnableParameter
inputRangeApplied::Vector{Tuple{Float64,Float64}} = [(-Inf,+Inf)]
end
"""
$(TYPEDEF)
Standardise the input to zero mean and unit standard deviation, aka "Z-score".
Note that missing values are skipped.
# Parameters:
$(FIELDS)
# Example:
```julia
julia> using BetaML, Statistics
julia> x = [[4000,1000,2000,3000] [400,100,200,300] [4,1,2,3] [0.4, 0.1, 0.2, 0.3]]
4×4 Matrix{Float64}:
4000.0 400.0 4.0 0.4
1000.0 100.0 1.0 0.1
2000.0 200.0 2.0 0.2
3000.0 300.0 3.0 0.3
julia> mod = Scaler() # equiv to `Scaler(StandardScaler(scale=true, center=true))`
A Scaler BetaMLModel (unfitted)
julia> xscaled = fit!(mod,x)
4×4 Matrix{Float64}:
1.34164 1.34164 1.34164 1.34164
-1.34164 -1.34164 -1.34164 -1.34164
-0.447214 -0.447214 -0.447214 -0.447214
0.447214 0.447214 0.447214 0.447214
julia> col_means = mean(xscaled, dims=1)
1×4 Matrix{Float64}:
0.0 0.0 0.0 5.55112e-17
julia> col_var = var(xscaled, dims=1, corrected=false)
1×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
julia> xback = inverse_predict(mod, xscaled)
4×4 Matrix{Float64}:
4000.0 400.0 4.0 0.4
1000.0 100.0 1.0 0.1
2000.0 200.0 2.0 0.2
3000.0 300.0 3.0 0.3
```
"""
Base.@kwdef mutable struct StandardScaler <: AbstractScaler
"Scale to unit variance [def: true]"
scale::Bool=true
"Center to zero mean [def: true]"
center::Bool=true
end
Base.@kwdef mutable struct StandardScaler_lp <: AbstractScalerLearnableParameter
sfμ::Vector{Float64} = Float64[] # scale factor of mean
sfσ::Vector{Float64} = Float64[] # scale vector of st.dev.
end
function _fit(m::MinMaxScaler,skip,X,cache)
actualRanges = Tuple{Float64,Float64}[]
X_scaled = cache ? float.(X) : nothing
for (ic,c) in enumerate(eachcol(X))
if !(ic in skip)
imin,imax = (m.inputRange[1](skipmissing(c)), m.inputRange[2](skipmissing(c)) )
if cache
omin, omax = m.outputRange[1], m.outputRange[2]
X_scaled[:,ic] = (c .- imin) .* ((omax-omin)/(imax-imin)) .+ omin
end
push!(actualRanges,(imin,imax))
else
push!(actualRanges,(-Inf,+Inf))
end
end
return X_scaled, MinMaxScaler_lp(actualRanges)
end
function _fit(m::StandardScaler,skip,X::AbstractArray,cache)
nDims = ndims(X)
nR = size(X,1)
nD = (nDims == 1) ? 1 : size(X,2)
sfμ = zeros(nD)
sfσ = ones(nD)
X_scaled = cache ? float.(X) : nothing
for (ic,c) in enumerate(eachcol(X))
if !(ic in skip)
μ = m.center ? mean(skipmissing(c)) : 0.0
σ² = m.scale ? var(skipmissing(c),corrected=false) : 1.0
sfμ[ic] = - μ
sfσ[ic] = 1 ./ sqrt.(σ²)
if cache
X_scaled[:,ic] = (c .+ sfμ[ic]) .* sfσ[ic]
end
end
end
return X_scaled, StandardScaler_lp(sfμ,sfσ)
end
function _predict(m::MinMaxScaler,pars::MinMaxScaler_lp,skip,X;inverse=false)
if !inverse
xnew = float.(X)
for (ic,c) in enumerate(eachcol(X))
if !(ic in skip)
imin,imax = pars.inputRangeApplied[ic]
omin,omax = m.outputRange
xnew[:,ic] = (c .- imin) .* ((omax-omin)/(imax-imin)) .+ omin
end
end
return xnew
else
xorig = deepcopy(X)
for (ic,c) in enumerate(eachcol(X))
if !(ic in skip)
imin,imax = pars.inputRangeApplied[ic]
omin,omax = m.outputRange
xorig[:,ic] = (c .- omin) .* ((imax-imin)/(omax-omin)) .+ imin
end
end
return xorig
end
end
function _predict(m::StandardScaler,pars::StandardScaler_lp,skip,X;inverse=false)
if !inverse
xnew = float.(X)
for (ic,c) in enumerate(eachcol(X))
if !(ic in skip)
xnew[:,ic] = (c .+ pars.sfμ[ic]) .* pars.sfσ[ic]
end
end
return xnew
else
xorig = deepcopy(X)
for (ic,c) in enumerate(eachcol(X))
if !(ic in skip)
xorig[:,ic] = (c ./ pars.sfσ[ic] .- pars.sfμ[ic])
end
end
return xorig
end
end
"""
$(TYPEDEF)
Hyperparameters for the Scaler transformer
## Parameters
$(FIELDS)
"""
Base.@kwdef mutable struct Scaler_hp <: BetaMLHyperParametersSet
"The specific scaler method to employ with its own parameters. See [`StandardScaler`](@ref) [def] or [`MinMaxScaler`](@ref)."
method::AbstractScaler = StandardScaler()
"The positional ids of the columns to skip scaling (eg. categorical columns, dummies,...) [def: `[]`]"
skip::Vector{Int64} = Int64[]
end
Base.@kwdef mutable struct Scaler_lp <: BetaMLLearnableParametersSet
scalerpars::AbstractScalerLearnableParameter = StandardScaler_lp()
end
"""
$(TYPEDEF)
Scale the data according to the specific chosen method (def: `StandardScaler`)
For the parameters see [`Scaler_hp`](@ref) and [`BML_options`](@ref)
# Examples:
- Standard scaler (default)...
```julia
julia> using BetaML, Statistics
julia> x = [[4000,1000,2000,3000] [400,100,200,300] [4,1,2,3] [0.4, 0.1, 0.2, 0.3]]
4×4 Matrix{Float64}:
4000.0 400.0 4.0 0.4
1000.0 100.0 1.0 0.1
2000.0 200.0 2.0 0.2
3000.0 300.0 3.0 0.3
julia> mod = Scaler() # equiv to `Scaler(StandardScaler(scale=true, center=true))`
A Scaler BetaMLModel (unfitted)
julia> xscaled = fit!(mod,x)
4×4 Matrix{Float64}:
1.34164 1.34164 1.34164 1.34164
-1.34164 -1.34164 -1.34164 -1.34164
-0.447214 -0.447214 -0.447214 -0.447214
0.447214 0.447214 0.447214 0.447214
julia> col_means = mean(xscaled, dims=1)
1×4 Matrix{Float64}:
0.0 0.0 0.0 5.55112e-17
julia> col_var = var(xscaled, dims=1, corrected=false)
1×4 Matrix{Float64}:
1.0 1.0 1.0 1.0
julia> xback = inverse_predict(mod, xscaled)
4×4 Matrix{Float64}:
4000.0 400.0 4.0 0.4
1000.0 100.0 1.0 0.1
2000.0 200.0 2.0 0.2
3000.0 300.0 3.0 0.3
```
- Min-max scaler...
```julia
julia> using BetaML
julia> x = [[4000,1000,2000,3000] ["a", "categorical", "variable", "not to scale"] [4,1,2,3] [0.4, 0.1, 0.2, 0.3]]
4×4 Matrix{Any}:
4000 "a" 4 0.4
1000 "categorical" 1 0.1
2000 "variable" 2 0.2
3000 "not to scale" 3 0.3
julia> mod = Scaler(MinMaxScaler(outputRange=(0,10)),skip=[2])
A Scaler BetaMLModel (unfitted)
julia> xscaled = fit!(mod,x)
4×4 Matrix{Any}:
10.0 "a" 10.0 10.0
0.0 "categorical" 0.0 0.0
3.33333 "variable" 3.33333 3.33333
6.66667 "not to scale" 6.66667 6.66667
julia> xback = inverse_predict(mod,xscaled)
4×4 Matrix{Any}:
4000.0 "a" 4.0 0.4
1000.0 "categorical" 1.0 0.1
2000.0 "variable" 2.0 0.2
3000.0 "not to scale" 3.0 0.3
```
"""
mutable struct Scaler <: BetaMLUnsupervisedModel
hpar::Scaler_hp
opt::BML_options
par::Union{Nothing,Scaler_lp}
cres::Union{Nothing,Array}
fitted::Bool
info::Dict{String,Any}
end
function Scaler(;kwargs...)
m = Scaler(Scaler_hp(),BML_options(),Scaler_lp(),nothing,false,Dict{Symbol,Any}())
thisobjfields = fieldnames(nonmissingtype(typeof(m)))
for (kw,kwv) in kwargs
found = false
for f in thisobjfields
fobj = getproperty(m,f)
if kw in fieldnames(typeof(fobj))
setproperty!(fobj,kw,kwv)
found = true
end
end
found || error("Keyword \"$kw\" is not part of this model.")
end
return m
end
function Scaler(method;kwargs...)
m = Scaler(Scaler_hp(method=method),BML_options(),Scaler_lp(),nothing,false,Dict{Symbol,Any}())
thisobjfields = fieldnames(nonmissingtype(typeof(m)))
for (kw,kwv) in kwargs
found = false
for f in thisobjfields
fobj = getproperty(m,f)
if kw in fieldnames(typeof(fobj))
setproperty!(fobj,kw,kwv)
found = true
end
end
found || error("Keyword \"$kw\" is not part of this model.")
end
return m
end
function fit!(m::Scaler,x)
# Parameter alias..
scaler = m.hpar.method
skip = m.hpar.skip
cache = m.opt.cache
verbosity = m.opt.verbosity
rng = m.opt.rng
if m.fitted
verbosity >= STD && @warn "This model doesn't support online training. Training will be performed based on new data only."
end
m.cres,m.par.scalerpars = _fit(scaler,skip,x,cache)
m.info["fitted_records"] = get(m.info,"fitted_records",0) + size(x,1)
m.info["xndims"] = size(x,2)
m.fitted = true
return cache ? m.cres : nothing
end
function predict(m::Scaler,x)
return _predict(m.hpar.method,m.par.scalerpars,m.hpar.skip,x;inverse=false)
end
function inverse_predict(m::Scaler,x)
return _predict(m.hpar.method,m.par.scalerpars,m.hpar.skip,x;inverse=true)
end
"""
$(TYPEDEF)
Hyperparameters for the PCAEncoder transformer
## Parameters
$(FIELDS)
"""
Base.@kwdef mutable struct PCAE_hp <: BetaMLHyperParametersSet
"The size, that is the number of dimensions, to maintain (with `encoded_size <= size(X,2)` ) [def: `nothing`, i.e. the number of output dimensions is determined from the parameter `max_unexplained_var`]"
encoded_size::Union{Nothing,Int64} = nothing
"The maximum proportion of variance that we are willing to accept when reducing the number of dimensions in our data [def: 0.05]. It doesn't have any effect when the output number of dimensions is explicitly chosen with the parameter `encoded_size`"
max_unexplained_var::Float64 = 0.05
end
Base.@kwdef mutable struct PCA_lp <: BetaMLLearnableParametersSet
eigen_out::Union{Eigen,Nothing} =nothing
encoded_size_actual::Union{Int64,Nothing}=nothing
end
"""
$(TYPEDEF)
Perform a Principal Component Analysis, a dimensionality reduction tecnique employing a linear trasformation of the original matrix by the eigenvectors of the covariance matrix.
PCAEncoder returns the matrix reprojected among the dimensions of maximum variance.
For the parameters see [`PCAE_hp`](@ref) and [`BML_options`](@ref)
# Notes:
- PCAEncoder doesn't automatically scale the data. It is suggested to apply the [`Scaler`](@ref) model before running it.
- Missing data are not supported. Impute them first, see the [`Imputation`](@ref) module.
- If one doesn't know _a priori_ the maximum unexplained variance that he is willling to accept, nor the wished number of dimensions, he can run the model with all the dimensions in output (i.e. with `encoded_size=size(X,2)`), analise the proportions of explained cumulative variance by dimensions in `info(mod,""explained_var_by_dim")`, choose the number of dimensions K according to his needs and finally pick from the reprojected matrix only the number of dimensions required, i.e. `out.X[:,1:K]`.
# Example:
```julia
julia> using BetaML
julia> xtrain = [1 10 100; 1.1 15 120; 0.95 23 90; 0.99 17 120; 1.05 8 90; 1.1 12 95];
julia> mod = PCAEncoder(max_unexplained_var=0.05)
A PCAEncoder BetaMLModel (unfitted)
julia> xtrain_reproj = fit!(mod,xtrain)
6×2 Matrix{Float64}:
100.449 3.1783
120.743 6.80764
91.3551 16.8275
120.878 8.80372
90.3363 1.86179
95.5965 5.51254
julia> info(mod)
Dict{String, Any} with 5 entries:
"explained_var_by_dim" => [0.873992, 0.999989, 1.0]
"fitted_records" => 6
"prop_explained_var" => 0.999989
"retained_dims" => 2
"xndims" => 3
julia> xtest = [2 20 200];
julia> xtest_reproj = predict(mod,xtest)
1×2 Matrix{Float64}:
200.898 6.3566
```
"""
mutable struct PCAEncoder <: BetaMLUnsupervisedModel
hpar::PCAE_hp
opt::BML_options
par::Union{Nothing,PCA_lp}
cres::Union{Nothing,Matrix}
fitted::Bool
info::Dict{String,Any}
end
function PCAEncoder(;kwargs...)
m = PCAEncoder(PCAE_hp(),BML_options(),PCA_lp(),nothing,false,Dict{Symbol,Any}())
thisobjfields = fieldnames(nonmissingtype(typeof(m)))
for (kw,kwv) in kwargs
found = false
for f in thisobjfields
fobj = getproperty(m,f)
if kw in fieldnames(typeof(fobj))
setproperty!(fobj,kw,kwv)
found = true
end
end
# Correction for releasing without breaking.. to remove on v0.12 onward...
# found || error("Keyword \"$kw\" is not part of this model.")
if !found
if kw == :outdims
setproperty!(m.hpar,:encoded_size,kwv)
found = true
else
error("Keyword \"$kw\" is not part of this model.")
end
end
end
return m
end
function fit!(m::PCAEncoder,X)
# Parameter alias..
encoded_size = m.hpar.encoded_size
max_unexplained_var = m.hpar.max_unexplained_var
cache = m.opt.cache
verbosity = m.opt.verbosity
rng = m.opt.rng
if m.fitted
verbosity >= STD && @warn "This model doesn't support online training. Training will be performed based on new data only."
end
(N,D) = size(X)
if !isnothing(encoded_size) && encoded_size > D
@error("The parameter `encoded_size` must be ≤ of the number of dimensions of the input data matrix")
end
Σ = (1/N) * X'*(I-(1/N)*ones(N)*ones(N)')*X
E = eigen(Σ) # eigenvalues are ordered from the smallest to the largest
# Finding oudims_actual
totvar = sum(E.values)
explained_var_by_dim = cumsum(reverse(E.values)) ./ totvar
encoded_size_actual = isnothing(encoded_size) ? findfirst(x -> x >= (1-max_unexplained_var), explained_var_by_dim) : encoded_size