Repository: JuliaML/MLUtils.jl
Pull request #32 (2022-02-02 07:08:03)

rename labelmap and frequencies to group_indices and group_counts


Patch:
diff --git a/src/MLUtils.jl b/src/MLUtils.jl
index bdb4c2f..9495ddc 100644
--- a/src/MLUtils.jl
+++ b/src/MLUtils.jl
@@ -41,7 +41,7 @@ include("randobs.jl")
 export randobs
 
 include("resample.jl")
-export labelmap, 
+export group_indices, 
        oversample,
        undersample
 
@@ -56,7 +56,7 @@ export batch,
        batchseq,
        chunk,
        flatten,
-       frequencies,
+       group_counts,
        normalise,
        stack,
        unbatch,
diff --git a/src/deprecations.jl b/src/deprecations.jl
index 8a653df..f81e6f8 100644
--- a/src/deprecations.jl
+++ b/src/deprecations.jl
@@ -3,3 +3,6 @@
 @deprecate unstack(x, dims) unstack(x; dims=dims)
 @deprecate unsqueeze(x::AbstractArray, dims::Int) unsqueeze(x; dims=dims)
 @deprecate unsqueeze(dims::Int) unsqueeze(dims=dims)
+@deprecate labelmap(x) group_indices(x)
+@deprecate frequencies(x) group_counts(x)
+
diff --git a/src/resample.jl b/src/resample.jl
index c684d51..0a1d60d 100644
--- a/src/resample.jl
+++ b/src/resample.jl
@@ -83,7 +83,7 @@ See [`ObsView`](@ref) for more information on data subsets.
 See also [`undersample`](@ref) and [`stratifiedobs`](@ref).
 """
 function oversample(data, classes; fraction=1, shuffle::Bool=true)
-    lm = labelmap(classes)
+    lm = group_indices(classes)
 
     maxcount = maximum(length, values(lm))
     fraccount = round(Int, fraction * maxcount)
@@ -180,7 +180,7 @@ See [`ObsView`](@ref) for more information on data subsets.
 See also [`oversample`](@ref) and [`stratifiedobs`](@ref).
 """
 function undersample(data, classes; shuffle::Bool=true)
-    lm = labelmap(classes)
+    lm = group_indices(classes)
     mincount = minimum(length, values(lm))
 
     inds = Int[]
@@ -194,32 +194,3 @@ function undersample(data, classes; shuffle::Bool=true)
 end
 
 undersample(data::Tuple; kws...) = undersample(data, data[end]; kws...)
-
-
-"""
-    labelmap(classes) -> Dict
-
-Computes the indices of all elements that belong to each class. 
-This information is useful for resampling strategies, such as stratified sampling
-
-```julia
-julia> true_targets = [:yes,:no,:maybe,:yes];
-
-julia> labelmap(true_targets)
-Dict{Symbol, Vector{Int64}} with 3 entries:
-  :yes   => [1, 4]
-  :maybe => [3]
-  :no    => [2]
-
-"""
-function labelmap(classes::T) where T<:AbstractVector
-    dict = Dict{eltype(T), Vector{Int}}()
-    for (idx, elem) in enumerate(classes)
-        if !haskey(dict, elem)
-            push!(dict, elem => [idx])
-        else
-            push!(dict[elem], idx)
-        end
-    end
-    return dict
-end
diff --git a/src/utils.jl b/src/utils.jl
index e215c2d..1c773e4 100644
--- a/src/utils.jl
+++ b/src/utils.jl
@@ -5,6 +5,7 @@
 
 Return `x` reshaped into an array one dimensionality higher than `x`,
 where `dims` indicates in which dimension `x` is extended.
+
 See also [`flatten`](@ref), [`stack`](@ref).
 
 # Examples
@@ -58,6 +59,8 @@ Base.show_function(io::IO, u::Base.Fix2{typeof(_unsqueeze)}, ::Bool) = print(io,
 Concatenate the given array of arrays `xs` into a single array along the
 given dimension `dims`.
 
+See also [`stack`](@ref) and [`batch`](@ref).
+
 # Examples
 
 ```jldoctest
@@ -100,6 +103,8 @@ stack(xs; dims::Int) = cat(unsqueeze.(xs; dims)...; dims)
 
 Unroll the given `xs` into an array of arrays along the given dimension `dims`.
 
+See also [`stack`](@ref) and [`unbatch`](@ref).
+
 # Examples
 
 ```jldoctest
@@ -114,9 +119,9 @@ julia> unstack([1 3 5 7; 2 4 6 8], dims=2)
 unstack(xs; dims::Int) = [copy(selectdim(xs, dims, i)) for i in 1:size(xs, dims)]
 
 """
-    chunk(xs, n)
+    chunk(x, n)
 
-Split `xs` into `n` parts.
+Split `x` into `n` parts.
 
 # Examples
 
@@ -137,27 +142,61 @@ julia> chunk(collect(1:10), 3)
 chunk(xs, n) = collect(Iterators.partition(xs, ceil(Int, length(xs)/n)))
 
 """
-    frequencies(xs)
+    group_counts(x)
 
-Count the number of times that each element of `xs` appears.
+Count the number of times that each element of `x` appears.
 
+See also [`group_indices`](@ref)
 # Examples
 
 ```jldoctest
-julia> frequencies(['a','b','b'])
+julia> group_counts(['a', 'b', 'b'])
 Dict{Char, Int64} with 2 entries:
   'a' => 1
   'b' => 2
 ```
 """
-function frequencies(xs)
-    fs = Dict{eltype(xs),Int}()
-    for x in xs
-        fs[x] = get(fs, x, 0) + 1
+function group_counts(x)
+    fs = Dict{eltype(x),Int}()
+    for a in x
+        fs[a] = get(fs, a, 0) + 1
     end
     return fs
 end
 
+"""
+    group_indices(x) -> Dict
+
+Computes the indices of elements in the vector `x` for each distinct value contained. 
+This information is useful for resampling strategies, such as stratified sampling.
+
+See also [`group_counts`](@ref).
+
+# Examples
+
+```julia
+julia> x = [:yes, :no, :maybe, :yes];
+
+julia> group_indices(x)
+Dict{Symbol, Vector{Int64}} with 3 entries:
+  :yes   => [1, 4]
+  :maybe => [3]
+  :no    => [2]
+
+"""
+function group_indices(classes::T) where T<:AbstractVector
+    dict = Dict{eltype(T), Vector{Int}}()
+    for (idx, elem) in enumerate(classes)
+        if !haskey(dict, elem)
+            push!(dict, elem => [idx])
+        else
+            push!(dict[elem], idx)
+        end
+    end
+    return dict
+end
+
+
 """
     batch(xs)
 
@@ -230,6 +269,7 @@ end
 
 Reverse of the [`batch`](@ref) operation,
 unstacking the last dimension of the array `x`.
+
 See also [`unstack`](@ref).
 
 # Examples
@@ -298,6 +338,7 @@ end
 
 Reshape arbitrarly-shaped input into a matrix-shaped output,
 preserving the size of the last dimension.
+
 See also [`unsqueeze`](@ref).
 
 # Examples
@@ -314,8 +355,9 @@ end
 """
     normalise(x; dims=ndims(x), ϵ=1e-5)
 
-Normalise `x` to mean 0 and standard deviation 1 across the dimension(s) given by `dims`.
+Normalise the array `x` to mean 0 and standard deviation 1 across the dimension(s) given by `dims`.
 Per default, `dims` is the last dimension. 
+
 `ϵ` is a small additive factor added to the denominator for numerical stability.
 """
 function normalise(x::AbstractArray; dims=ndims(x), ϵ=ofeltype(x, 1e-5))


Test patch:
diff --git a/test/utils.jl b/test/utils.jl
index f7e2e39..298b9fc 100644
--- a/test/utils.jl
+++ b/test/utils.jl
@@ -84,8 +84,8 @@ end
     @test cs[3] == [9, 10]
 end
 
-@testset "frequencies" begin
-    d = frequencies(['a','b','b'])
+@testset "group_counts" begin
+    d = group_counts(['a','b','b'])
     @test d == Dict('a' => 1, 'b' => 2)
 end