TargetEncoder: fit throws "unable to check bounds for indices of type Missing" when a categorical feature contains missing values
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 2/5
- Tiempo estimado
- 1-3 horas
- Aptitud para principiantes
- 76/100
- Tipo de issue
- Error
- Claridad
- Bien especificado
- Estado de actividad
- Activo
- Área
- machine-learning
Línea de trabajo
Empieza por src/encoders/target_encoding/target_encoding.jl, en especial por el código de feature_mapper cerca de la línea 173 indicada, y sigue cómo construye la máscara para cada nivel categórico. Comprueba cómo deberían afectar los valores de características ausentes a las estadísticas por nivel; después, ejecuta las pruebas del target encoder y añade cobertura para los valores ausentes. Se considera terminado cuando el ajuste se completa correctamente para los casos de clasificación y regresión indicados, o devuelve el error claro documentado si no se admiten valores ausentes.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
TargetEncoder can't be fit on a categorical feature that contains missing. Fit fails with ArgumentError: unable to check bounds for indices of type Missing, and this happens for binary classification, multiclass and regression targets alike. The machine type checks pass (the column is Union{Missing, Multiclass{3}}, which generic_fit selects for encoding), so the error comes from inside fit.
using MLJTransforms, MLJBase, CategoricalArrays
X = (color = categorical(["red", "green", missing, "blue", "red", "green"]), x = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
schema(X) |> println # color is Union{Missing, Multiclass{3}}
y_bin = categorical(["a", "b", "a", "b", "a", "b"])
y_reg = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
for (task, y) in (("binary", y_bin), ("regression", y_reg))
try
MLJTransforms.target_encoder_fit(X, y)
catch e
println("target_encoder_fit, $task: ", sprint(showerror, e))
end
end
# through a machine
mach = machine(TargetEncoder(), X, y_bin)
try
fit!(mach, verbosity = 0)
catch e
println("fit!(mach): ", sprint(showerror, e))
end
# training on rows without missing works, and transform then propagates missing fine
keep = .!ismissing.(X.color)
Xclean = (color = X.color[keep], x = X.x[keep])
mach2 = fit!(machine(TargetEncoder(), Xclean, y_bin[keep]), verbosity = 0)
println("transform after clean fit: ", transform(mach2, X))
# the mask used in feature_mapper
println(X.color .== "red")
Output:
ScientificTypes.Schema{(:color, :x), Tuple{Union{Missing, Multiclass{3}}, Continuous}, Tuple{Union{Missing, CategoricalValue{String, UInt32}}, Float64}}(nothing, nothing, nothing)
target_encoder_fit, binary: ArgumentError: unable to check bounds for indices of type Missing
target_encoder_fit, regression: ArgumentError: unable to check bounds for indices of type Missing
┌ Error: Problem fitting the machine machine(TargetEncoder(features = Symbol[], …), …).
└ @ MLJBase ~/.julia/packages/MLJBase/CIZ7f/src/machines.jl:758
[ Info: Running type checks...
[ Info: Type checks okay.
fit!(mach): ArgumentError: unable to check bounds for indices of type Missing
transform after clean fit: (color = Union{Missing, Float64}[1.0, 0.0, missing, 0.0, 1.0, 0.0], x = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
Union{Missing, Bool}[1, 0, missing, 0, 1, 0]
(A multiclass target, e.g. categorical(["a", "b", "c", "b", "a", "c"]), gives the same error.)
Top of the stack trace:
ArgumentError: unable to check bounds for indices of type Missing
Stacktrace:
[1] checkindex(::Type{Bool}, inds::Base.OneTo{Int64}, i::Missing)
@ Base ./abstractarray.jl:754
...
[5] getindex
@ ~/.julia/packages/CategoricalArrays/pvykx/src/array.jl:743 [inlined]
[6] (::MLJTransforms.var"#feature_mapper#28"{...})(col::CategoricalVector{Union{Missing, String}, UInt32, String, CategoricalValue{String, UInt32}, Missing}, name::Symbol)
@ MLJTransforms src/encoders/target_encoding/target_encoding.jl:173
[7] generic_fit(...)
@ MLJTransforms src/generic.jl:91
...
[9] target_encoder_fit(...)
@ MLJTransforms src/encoders/target_encoding/target_encoding.jl:209
Cause
generic_fit selects columns whose element scitype is Union{Missing, Multiclass} (or Union{Missing, OrderedFactor}) for encoding (src/generic.jl#L84-L91). The target encoder's feature_mapper then collects the targets for each level with:
targets_for_level = y[col.==level]
(src/encoders/target_encoding/target_encoding.jl#L171-L173)
When col has a missing, col .== level is a Vector{Union{Missing, Bool}} (last line of the output above), and that can't be used as a logical index, so getindex throws. Something like y[isequal.(col, level)] (or coalesce.(col .== level, false)) would just leave the missing rows out of every level's statistics; I checked that both give [1.0, 5.0] for "red" on the column above. The priors (mean(y) / class frequencies) would still be computed over all rows, which seems reasonable, and as shown above transform already passes missing through via recode.
This is related to #106 but a separate code path: #106 is ContrastEncoder failing in transform (the multi-column hcat branch of generic_transform), while here TargetEncoder fails earlier, in fit, because of the boolean mask. FrequencyEncoder, OrdinalEncoder, CardinalityReducer and MissingnessEncoder all fit and transform the same X without errors.
Expected
Fit should either skip missing when computing the per-level statistics (so the encoded column is Union{Missing, Float64} like the other single-column encoders), or throw a clear error saying TargetEncoder doesn't support missing values in features and pointing to MissingnessEncoder/FillImputer.
Versions
- MLJTransforms v0.2.4 (
devat d3e3db3) - MLJBase v1.15.3, CategoricalArrays v1.1.1
- Julia 1.13.3
- Lenguaje dominante
- Julia
- Estrellas
- 1
- Forks
- 5
- Merge medio
- 1 d 20 min
- PR fusionados (30 d)
- 7
Preparar el entorno
Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de JuliaAI/MLJTransforms.jl
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 90/100
JuliaAI/MLJTransforms.jl#108 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 3/5 1-2 días Aptitud para principiantes 72/100
JuliaAI/MLJTransforms.jl#106 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 3/5 Medio día Aptitud para principiantes 66/100
JuliaAI/MLJTransforms.jl#105 ·
Los mantenedores suelen responder en 1 día
-
Add a `Transformer` wrapper for models that supervised that transformQuizá libre de nuevo @ablaom la tomó hace 240 días y no hay ningún pull request abierto. Abiertoenhancement
JuliaAI/MLJTransforms.jl#52 · 3 comentarios · 1 asignado ·
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 4/5 3-5 días Aptitud para principiantes 35/100
JuliaAI/MLJTransforms.jl#39 · 1 comentario ·
Los mantenedores suelen responder en 1 día
Todos los issues de JuliaAI/MLJTransforms.jl
Issues similares
-
The entrypoint deletes its manifest runfiles tree at exit even under TEST_TMPDIRPosiblemente ocupada @TrapsterDK la tomó hoy. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 88/100
periareon/rules_julia#64 ·
Los mantenedores suelen responder en 1 día
-
tagbot-manual
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
-
Add to "Why Wren.jl"Abierto
Dificultad 1/5 Menos de una hora Aptitud para principiantes 82/100
JuliaBayes/Wren.jl#370 · 3 comentarios · 2 reacciones ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 74/100
JuliaGPU/GemmKernels.jl#232 ·
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100