Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Don't let the classifier pick categories with too few examples (#5702)

Marcin9407935ea868
diff --git a/app/models/family/bayes_categorizer.rb b/app/models/family/bayes_categorizer.rb
index 468878621c..51f9129b44 100644
--- a/app/models/family/bayes_categorizer.rb
+++ b/app/models/family/bayes_categorizer.rb
@@ -65,10 +65,17 @@ class Family::BayesCategorizer
def classify(transaction)
category_id, confidence = probabilities(transaction).max_by { |_, probability| probability }
return nil if category_id.nil? || confidence < settings.threshold
+ return nil unless pickable?(category_id)
[ category_id, confidence ]
end
+ # Whether the category has enough training transactions to be picked
+ # (settings.min_category_examples); the evaluation applies the same rule.
+ def pickable?(category_id)
+ class_models.dig(category_id, :docs).to_i >= settings.min_category_examples
+ end
+
# { category_id => softmax score } over every trained category; empty when
# the model isn't trained yet or nothing about the transaction is known.
def probabilities(transaction)
diff --git a/app/models/family/bayes_evaluation.rb b/app/models/family/bayes_evaluation.rb
index f92d150001..523998adee 100644
--- a/app/models/family/bayes_evaluation.rb
+++ b/app/models/family/bayes_evaluation.rb
@@ -458,7 +458,10 @@ class Family::BayesEvaluation
test_transactions(categorizer, start).map do |transaction|
probabilities = categorizer.probabilities(transaction)
category_id, confidence = probabilities.max_by { |_, probability| probability }
- [ confidence, category_id == transaction.category_id, transaction.category_id, category_id, probabilities.presence || uniform ]
+ # A category the classifier would never pick is no answer, as in production;
+ # its scores still count towards the AUC.
+ category_id, confidence = nil, nil if category_id && !categorizer.pickable?(category_id)
+ [ confidence, category_id.present? && category_id == transaction.category_id, transaction.category_id, category_id, probabilities.presence || uniform ]
end
end
diff --git a/app/models/family/bayes_settings.rb b/app/models/family/bayes_settings.rb
index 0757b03c8f..4e9fa0ca7f 100644
--- a/app/models/family/bayes_settings.rb
+++ b/app/models/family/bayes_settings.rb
@@ -62,6 +62,10 @@ class Family::BayesSettings
# Classifier (the Category classifier rule)
threshold: 0.7,
+ # A category with fewer training transactions than this is never picked:
+ # with so few words, anything it has seen scores high there, so it would
+ # win unfamiliar transactions with a confident-looking score.
+ min_category_examples: 5,
lock_results: false
}.freeze
@@ -79,6 +83,7 @@ class Family::BayesSettings
similar_self_grace_days: 1..3650,
max_training_transactions: 100..20_000,
threshold: 0.05..0.99,
+ min_category_examples: 1..100,
spread_margin: 0.0..0.9,
smoothing: 0.001..10.0,
similar_threshold: 0.5..0.99,
diff --git a/app/views/settings/classifiers/_classifier.html.erb b/app/views/settings/classifiers/_classifier.html.erb
index d90f3abe77..f1d96bb68b 100644
--- a/app/views/settings/classifiers/_classifier.html.erb
+++ b/app/views/settings/classifiers/_classifier.html.erb
@@ -8,6 +8,9 @@
<%= render "settings/classifiers/number", key: :threshold, settings: settings,
attrs: { step: 0.01 },
label: t(".threshold"), hint: t(".threshold_hint") %>
+ <%= render "settings/classifiers/number", key: :min_category_examples, settings: settings,
+ attrs: { step: 1 },
+ label: t(".min_category_examples"), hint: t(".min_category_examples_hint") %>
<%= render "settings/classifiers/toggle", key: :lock_results, settings: settings, label: t(".lock_results"), hint: t(".lock_results_hint") %>
<% end %>
</div>
diff --git a/config/locales/views/settings/classifiers/en.yml b/config/locales/views/settings/classifiers/en.yml
index 602f3bd4eb..bbdb030d44 100644
--- a/config/locales/views/settings/classifiers/en.yml
+++ b/config/locales/views/settings/classifiers/en.yml
@@ -31,6 +31,8 @@ en:
rule_hint: The Category classifier rule, on and off with it in Rules. It categorizes uncategorized transactions in your rule order, after each sync; what it isn't sure about is left for an Auto-categorize rule.
threshold: Threshold
threshold_hint: Lowest score Bayes acts on (0.05–0.99). Lower categorizes more, with more mistakes.
+ min_category_examples: Fewest examples per category
+ min_category_examples_hint: A category is only picked once this many of your transactions have it (1–100). A category with very few examples otherwise wins unfamiliar transactions with a high score.
clear_locks:
success: Bayes' locks are being cleared. This may take a few moments.
evaluation:
diff --git a/test/models/family/bayes_categorizer_test.rb b/test/models/family/bayes_categorizer_test.rb
index 15449f7040..8eb7db240f 100644
--- a/test/models/family/bayes_categorizer_test.rb
+++ b/test/models/family/bayes_categorizer_test.rb
@@ -51,6 +51,20 @@ class Family::BayesCategorizerTest < ActiveSupport::TestCase
Family::BayesCategorizer.new(@family, settings: Family::BayesSettings.new(TUNED.merge(changes)))
end
+ # A category with a handful of transactions has so few words that any word it
+ # has seen scores far higher there than in a large category: it would win
+ # unfamiliar transactions, overconfidently, until it has enough examples.
+ test "a category with fewer examples than the minimum is never picked" do
+ train_two_categories
+ food = @family.categories.create!(name: "Food")
+ 3.times { create_transaction(account: @account, name: "Przelew na telefon BLIK", category: food) }
+ categorizer = Family::BayesCategorizer.new(@family, settings: Family::BayesSettings.new)
+ transaction = create_transaction(account: @account, name: "Przelew na telefon BLIK Paypal").transaction
+
+ assert_nil categorizer.classify(transaction)
+ assert_equal food.id, Family::BayesCategorizer.new(@family, settings: Family::BayesSettings.new(min_category_examples: 3)).classify(transaction)&.first
+ end
+
test "the defaults are the original model: add-1 multinomial, uniform prior, merchant name as words" do
train_two_categories
categorizer = Family::BayesCategorizer.new(@family, settings: Family::BayesSettings.new)
diff --git a/test/models/family/bayes_evaluation_test.rb b/test/models/family/bayes_evaluation_test.rb
index b193172b7d..e01bf86074 100644
--- a/test/models/family/bayes_evaluation_test.rb
+++ b/test/models/family/bayes_evaluation_test.rb
@@ -37,6 +37,23 @@ class Family::BayesEvaluationTest < ActiveSupport::TestCase
assert_nil result["best"]
end
+ # The classifier never picks a category with fewer examples than the minimum,
+ # so the evaluation mustn't count it as an answer either.
+ test "a pick of a category below the minimum of examples counts as no answer" do
+ tea = @family.categories.create!(name: "Tea")
+ 2.times { create_transaction(account: @account, name: "Twinings Tea", category: tea, date: Date.new(2026, 1, 15)) }
+ create_transaction(account: @account, name: "Twinings Tea", category: tea, date: Date.new(2026, 9, 3))
+
+ result = Family::BayesEvaluation.new(@family, today: @today).run!
+
+ at_threshold = result.dig("current", "sweep").find { |row| row["threshold"] == 0.4 }
+ assert_equal({ "threshold" => 0.4, "right" => 0, "wrong" => 0 }, at_threshold)
+
+ @family.update_bayes_settings!(min_category_examples: 2)
+ lowered = Family::BayesEvaluation.new(@family, today: @today).run!
+ assert_equal 1, lowered.dig("current", "sweep").find { |row| row["threshold"] == 0.4 }["right"]
+ end
+
test "scores the matcher on the same months, by similarity and number agreeing" do
netflix = @family.merchants.create!(name: "Netflix")
hulu = @family.merchants.create!(name: "Hulu")