TargetEncoder: fit throws "unable to check bounds for indices of type Missing" when a categorical feature contains missing values

オープン 初心者向け
#107 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
76/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発

調査の方向性

src/encoders/target_encoding/target_encoding.jlから始め、特に報告された173行目付近のfeature_mapperコードを確認し、各カテゴリ水準のマスクをどのように構築しているかを追ってください。欠損した特徴量の値が水準ごとの統計量にどう影響するべきかを確認し、その後、target encoderのテストを実行して欠損値のテストを追加してください。報告された分類と回帰のケースでfitが成功するか、欠損値がサポートされない場合に文書化された明確なエラーを返せば完了です。

索引モデルが issue の本文から書いたものです。

説明

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 (dev at d3e3db3)
  • MLJBase v1.15.3, CategoricalArrays v1.1.1
  • Julia 1.13.3
主要言語
Julia
スター
1
フォーク
5
平均マージ
1日 20分
マージ済み PR(30日)
7

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

JuliaAI/MLJTransforms.jl のほかの issue

JuliaAI/MLJTransforms.jl の issue をすべて見る

似ている issue

Julia の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。