The personal finance app for everyone (by everyone)
Ruby
feat(categorization): try naive Bayes before the LLM (#3465)
Nate Mendese9e8d2c2d3de
diff --git a/app/models/data_enrichment.rb b/app/models/data_enrichment.rbindex 6af743c145..d15b92548c 100644--- a/app/models/data_enrichment.rb+++ b/app/models/data_enrichment.rb@@ -19,6 +19,7 @@ class DataEnrichment < ApplicationRecordibkr: "ibkr",questrade: "questrade",redbark: "redbark",- trade_republic: "trade_republic"+ trade_republic: "trade_republic",+ bayes: "bayes"}enddiff --git a/app/models/family.rb b/app/models/family.rbindex f4a3ff765c..01ee5381a0 100644--- a/app/models/family.rb+++ b/app/models/family.rb@@ -363,7 +363,15 @@ class Family < ApplicationRecordenddef auto_categorize_transactions(transaction_ids)- AutoCategorizer.new(self, transaction_ids: transaction_ids).auto_categorize+ bayes_result = Family::BayesCategorizer.new(self).classify_and_apply(transaction_ids)+ remaining_ids = Array(transaction_ids) - bayes_result.categorized_ids++ # Bayes handled everything with sufficient confidence — skip the LLM+ # categorizer entirely (including its no-provider error contract).+ return bayes_result.modified_count if bayes_result.categorized_ids.any? && remaining_ids.empty?++ llm_modified_count = AutoCategorizer.new(self, transaction_ids: remaining_ids).auto_categorize+ bayes_result.modified_count + llm_modified_countenddef auto_detect_transaction_merchants_later(transactions, rule_run_id: nil)diff --git a/app/models/family/bayes_categorizer.rb b/app/models/family/bayes_categorizer.rbnew file mode 100644index 0000000000..1bc416df57--- /dev/null+++ b/app/models/family/bayes_categorizer.rb@@ -0,0 +1,139 @@+# Naive-Bayes transaction categorizer.+#+# Trains a multinomial naive-Bayes model (Laplace add-1 smoothing) on the+# family's already-categorized transactions, then classifies uncategorized+# ones from the same token signals the LLM categorizer uses+# (entry name + notes + merchant name). Unlike AutoCategorizer it needs no+# provider — pure Ruby, trained on the fly and memoized per instance.+class Family::BayesCategorizer+ CONFIDENCE_THRESHOLD = 0.7+ MIN_TRAINING_TRANSACTIONS = 20+ MIN_CATEGORIES = 2+ # The whole training set is held in memory, so cap it rather than loading a+ # long-lived family's entire history on every categorization run. The most+ # recent transactions are also the most representative of current spending.+ MAX_TRAINING_TRANSACTIONS = 5_000++ # categorized_ids: transaction ids the model labeled at/above threshold+ # (regardless of whether the write actually changed anything).+ # modified_count: how many of those writes changed the category.+ Result = Data.define(:categorized_ids, :modified_count)++ def initialize(family)+ @family = family+ end++ # Guard: refuse to classify until there's a real signal to train on.+ def enough_training_data?+ training_transactions.size >= MIN_TRAINING_TRANSACTIONS &&+ training_transactions.map(&:category_id).uniq.size >= MIN_CATEGORIES+ end++ # Returns [category_id, confidence] for the argmax category, or nil when+ # the model isn't trained yet or no category clears the confidence+ # threshold (below threshold = no confident answer).+ def classify(transaction)+ return nil unless enough_training_data?++ log_scores = log_scores_for(tokens_for(transaction))+ return nil if log_scores.empty?++ category_id, _score = log_scores.max_by { |_, score| score }+ confidence = softmax(log_scores.values).max+ return nil if confidence < CONFIDENCE_THRESHOLD++ [ category_id, confidence ]+ end++ # Labels every uncategorized, enrichable transaction in transaction_ids+ # whose argmax confidence clears the threshold. No-op (empty Result) when+ # the training guard fails.+ def classify_and_apply(transaction_ids)+ return Result.new(categorized_ids: [], modified_count: 0) unless enough_training_data?++ categorized_ids = []+ modified_count = 0++ family.transactions+ .where(id: transaction_ids, category_id: nil)+ .enrichable(:category_id)+ .includes(:category, :merchant, :entry)+ .find_each do |transaction|+ category_id, _confidence = classify(transaction)+ next if category_id.nil?++ categorized_ids << transaction.id+ was_modified = transaction.enrich_attribute(:category_id, category_id, source: "bayes")+ modified_count += 1 if was_modified+ end++ Result.new(categorized_ids: categorized_ids, modified_count: modified_count)+ end++ private+ attr_reader :family++ # Same signal composition as AutoCategorizer#transactions_input, so the+ # two categorizers agree on what text a transaction speaks.+ def tokens_for(transaction)+ [ transaction.entry&.name, transaction.entry&.notes, transaction.merchant&.name ]+ .compact+ .join(" ")+ .downcase+ .scan(/[a-z0-9]+/)+ end++ def training_transactions+ @training_transactions ||= family.transactions+ .where.not(category_id: nil)+ .includes(:category, :merchant, :entry)+ .order(created_at: :desc)+ .limit(MAX_TRAINING_TRANSACTIONS)+ .to_a+ end++ # Per-category token-count models: { category_id => { total:, counts: } }.+ def class_models+ @class_models ||= training_transactions.group_by(&:category_id).transform_values do |txns|+ counts = Hash.new(0)+ txns.each { |txn| tokens_for(txn).each { |token| counts[token] += 1 } }+ { total: counts.values.sum, counts: counts }+ end+ end++ def vocabulary+ @vocabulary ||= Set.new(class_models.values.flat_map { |model| model[:counts].keys })+ end++ # Multinomial NB log-score per category with Laplace add-1 smoothing and+ # a uniform prior (constant across classes, so it drops out of softmax).+ # log(P(c)) + Σ_tokens log((count_t + 1) / (total + |V|))+ def log_scores_for(tokens)+ # Score only tokens the model has actually seen. An unknown token's+ # smoothed likelihood is 1/(total_c + |V|), which varies with the class's+ # own token count, so keeping them would let a wholly novel description+ # accumulate confidence for whichever category simply has the smallest+ # corpus. Dropping them leaves nothing to score, which is the honest+ # answer: no known signal, no classification, fall through to the LLM.+ known_tokens = tokens.select { |token| vocabulary.include?(token) }+ return {} if known_tokens.empty? || class_models.empty?++ denominator = vocabulary.size+ class_models.each_with_object({}) do |(category_id, model), scores|+ score = Math.log(1.0 / class_models.size)+ score += known_tokens.sum do |token|+ count = model[:counts][token] || 0+ Math.log((count + 1).to_f / (model[:total] + denominator))+ end+ scores[category_id] = score+ end+ end++ # Numerically stable softmax over the log-scores.+ def softmax(scores)+ max = scores.max+ exps = scores.map { |score| Math.exp(score - max) }+ sum = exps.sum+ exps.map { |exp| exp / sum }+ end+enddiff --git a/test/models/family/auto_categorize_transactions_test.rb b/test/models/family/auto_categorize_transactions_test.rbnew file mode 100644index 0000000000..ecaf74365f--- /dev/null+++ b/test/models/family/auto_categorize_transactions_test.rb@@ -0,0 +1,84 @@+require "test_helper"++class Family::AutoCategorizeTransactionsTest < ActiveSupport::TestCase+ include EntriesTestHelper, ProviderTestHelper++ setup do+ # Fresh family: fixture families carry categorized transactions that+ # would pollute the Bayes training set.+ @family = Family.create!(name: "Bayes Entry Family")+ @account = @family.accounts.create!(name: "Entry test", balance: 100, currency: "USD", accountable: Depository.new)+ @coffee = @family.categories.create!(name: "Coffee")+ @groceries = @family.categories.create!(name: "Groceries")+ @llm_provider = mock+ end++ # 10 coffee + 10 groceries = 20 categorized txns over 2 categories, so the+ # Bayes training guard passes (same hand-worked setup as BayesCategorizerTest).+ def train_two_categories+ 10.times { create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee) }+ 10.times { create_transaction(account: @account, name: "Safeway Groceries", category: @groceries) }+ end++ test "bayes handles everything: LLM provider never touched" do+ train_two_categories+ Provider::Registry.expects(:preferred_llm_provider).never++ txn = create_transaction(account: @account, name: "Starbucks Coffee").transaction++ assert_difference "DataEnrichment.count", 1 do+ assert_equal 1, @family.auto_categorize_transactions([ txn.id ])+ end+ assert_equal @coffee, txn.reload.category+ assert_equal "bayes", txn.data_enrichments.find_by(attribute_name: "category_id").source+ end++ test "bayes handles nothing: raises without LLM provider, same contract as today" do+ # No training data → Bayes no-ops; no LLM provider configured → raises.+ txn = create_transaction(account: @account, name: "Something new").transaction++ error = assert_raises(Family::AutoCategorizer::Error) do+ @family.auto_categorize_transactions([ txn.id ])+ end+ assert_equal "No LLM provider for auto-categorization", error.message+ assert_nil txn.reload.category+ end++ test "bayes handles nothing but LLM available: LLM gets all ids and count is unchanged" do+ Provider::Registry.stubs(:preferred_llm_provider).returns(@llm_provider)++ txn = create_transaction(account: @account, name: "Novel Shop").transaction+ test_category = @family.categories.create!(name: "Test category")++ @llm_provider.expects(:auto_categorize).returns(provider_success_response([+ AutoCategorization.new(transaction_id: txn.id, category_name: test_category.name)+ ])).once++ assert_difference "DataEnrichment.count", 1 do+ assert_equal 1, @family.auto_categorize_transactions([ txn.id ])+ end+ assert_equal test_category, txn.reload.category+ end++ test "bayes handles some, LLM handles the rest: modified_count sums" do+ train_two_categories+ Provider::Registry.stubs(:preferred_llm_provider).returns(@llm_provider)++ bayes_txn = create_transaction(account: @account, name: "Starbucks Coffee").transaction+ llm_txn = create_transaction(account: @account, name: "Novel Shop").transaction+ test_category = @family.categories.create!(name: "Test category")++ @llm_provider.expects(:auto_categorize).returns(provider_success_response([+ AutoCategorization.new(transaction_id: llm_txn.id, category_name: test_category.name)+ ])).once++ assert_difference "DataEnrichment.count", 2 do+ assert_equal 2, @family.auto_categorize_transactions([ bayes_txn.id, llm_txn.id ])+ end+ assert_equal @coffee, bayes_txn.reload.category+ assert_equal test_category, llm_txn.reload.category+ end++ private+ AutoCategorization = Provider::LlmConcept::AutoCategorization+enddiff --git a/test/models/family/bayes_categorizer_test.rb b/test/models/family/bayes_categorizer_test.rbnew file mode 100644index 0000000000..6170d4045e--- /dev/null+++ b/test/models/family/bayes_categorizer_test.rb@@ -0,0 +1,165 @@+require "test_helper"++class Family::BayesCategorizerTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ # Fresh family: fixture families carry categorized transactions (e.g.+ # dylan_family's "Starbucks"/"Amazon" → Food & Drink) that would pollute+ # the training set and break the hand-worked 2-category math below.+ @family = Family.create!(name: "Bayes Family")+ @account = @family.accounts.create!(name: "Bayes test", balance: 100, currency: "USD", accountable: Depository.new)+ @coffee = @family.categories.create!(name: "Coffee")+ @groceries = @family.categories.create!(name: "Groceries")+ @starbucks = @family.merchants.create!(name: "Starbucks")+ @safeway = @family.merchants.create!(name: "Safeway")+ end++ # 10 coffee + 10 groceries = 20 categorized txns over 2 categories, so the+ # training guard passes. Vocabulary = { starbucks, coffee, safeway,+ # groceries }, |V| = 4. Each class has 20 total tokens (10 txns x 2).+ def train_two_categories+ 10.times { create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee) }+ 10.times { create_transaction(account: @account, name: "Safeway Groceries", category: @groceries) }+ end++ test "no-op before enough training data" do+ categorizer = Family::BayesCategorizer.new(@family)++ assert_not categorizer.enough_training_data?++ 5.times { create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee) }++ assert_not categorizer.enough_training_data?+ uncategorized = create_transaction(account: @account, name: "Starbucks Coffee")++ assert_nil categorizer.classify(uncategorized.transaction)+ assert_difference "DataEnrichment.count", 0 do+ result = categorizer.classify_and_apply([ uncategorized.transaction.id ])+ assert_equal [], result.categorized_ids+ assert_equal 0, result.modified_count+ end+ assert_nil uncategorized.transaction.reload.category+ end++ test "separable merchants classify above threshold with hand-worked confidence" do+ train_two_categories+ categorizer = Family::BayesCategorizer.new(@family)+ assert categorizer.enough_training_data?++ txn = create_transaction(account: @account, name: "Starbucks Coffee")++ category_id, confidence = categorizer.classify(txn.transaction)++ assert_equal @coffee.id, category_id++ # Hand-worked multinomial NB, Laplace add-1, uniform prior:+ # P(coffee) = 0.5, total tokens = 20, |V| = 4+ # score_coffee = ln(0.5) + ln(11/24) + ln(11/24) ≈ -2.2535+ # score_other = ln(0.5) + ln(1/24) + ln(1/24) ≈ -7.0493+ # softmax(coffee) = 1 / (1 + e^(score_other - score_coffee))+ # = 1 / (1 + e^-4.7958) ≈ 0.9918+ assert_in_delta 0.9918, confidence, 0.001+ assert_operator confidence, :>=, Family::BayesCategorizer::CONFIDENCE_THRESHOLD+ end++ test "wholly novel tokens stay unclassified even when class corpora are lopsided" do+ # The symmetric fixture above cannot catch this: with equal token totals an+ # unknown token contributes the same smoothed likelihood to every class and+ # the bias cancels. Give one class a much larger corpus and an unseen+ # description would otherwise land on the smaller class with high+ # confidence, purely because 1/(total + |V|) is larger there.+ 10.times { create_transaction(account: @account, name: "Starbucks Coffee", category: @coffee) }+ 10.times do+ create_transaction(+ account: @account,+ name: "Safeway Groceries Produce Dairy Bakery Deli Frozen Pantry",+ category: @groceries+ )+ end++ categorizer = Family::BayesCategorizer.new(@family)+ assert categorizer.enough_training_data?++ novel = create_transaction(account: @account, name: "Zzyzx Blorptronics")++ assert_nil categorizer.classify(novel.transaction),+ "a description with no known tokens must not be classified from corpus-size bias alone"+ end++ test "training data with no usable tokens classifies nothing" do+ # Degenerate corpus: every training transaction tokenizes to nothing, so the+ # vocabulary is empty. Scoring against a zero-sized vocabulary would divide+ # by a zero token total and produce Infinity, whose softmax is NaN — and NaN+ # fails every comparison, so a threshold check cannot reject it. Guard is+ # that an empty vocabulary leaves no known tokens to score at all.+ 10.times { create_transaction(account: @account, name: "---", category: @coffee) }+ 10.times { create_transaction(account: @account, name: "...", category: @groceries) }++ categorizer = Family::BayesCategorizer.new(@family)+ assert categorizer.enough_training_data?++ txn = create_transaction(account: @account, name: "Starbucks Coffee")++ assert_nil categorizer.classify(txn.transaction)+ assert_difference "DataEnrichment.count", 0 do+ result = categorizer.classify_and_apply([ txn.transaction.id ])+ assert_equal [], result.categorized_ids+ end+ assert_nil txn.transaction.reload.category+ end++ test "novel merchant below threshold is left alone" do+ train_two_categories+ categorizer = Family::BayesCategorizer.new(@family)++ novel = create_transaction(account: @account, name: "New Shop", merchant: @family.merchants.create!(name: "Unknown Emporium"))++ assert_nil categorizer.classify(novel.transaction)+ assert_difference "DataEnrichment.count", 0 do+ result = categorizer.classify_and_apply([ novel.transaction.id ])+ assert_equal [], result.categorized_ids+ assert_equal 0, result.modified_count+ end+ assert_nil novel.transaction.reload.category+ end++ test "mixed case and merchant signals classify and modified_count sums correctly" do+ train_two_categories+ categorizer = Family::BayesCategorizer.new(@family)++ # Same tokens as "starbucks coffee" — downcase normalization.+ txn1 = create_transaction(account: @account, name: "STARBUCKS Coffee")+ # Name is generic but the merchant name carries the signal.+ txn2 = create_transaction(account: @account, name: "Purchase", merchant: @starbucks)+ # Already categorized → outside scope, must not be counted.+ txn3 = create_transaction(account: @account, name: "Safeway Groceries", category: @groceries)++ assert_difference "DataEnrichment.count", 2 do+ result = categorizer.classify_and_apply([ txn1.transaction.id, txn2.transaction.id, txn3.transaction.id ])+ assert_equal [ txn1.transaction.id, txn2.transaction.id ].sort, result.categorized_ids.sort+ assert_equal 2, result.modified_count+ end++ assert_equal @coffee, txn1.transaction.reload.category+ assert_equal @coffee, txn2.transaction.reload.category+ assert_equal @groceries, txn3.transaction.reload.category++ enrichment = txn1.transaction.data_enrichments.find_by(attribute_name: "category_id")+ assert_equal "bayes", enrichment.source+ end++ test "classify_and_apply returns categorized_ids and modified_count separately" do+ train_two_categories+ categorizer = Family::BayesCategorizer.new(@family)++ # A transaction whose category is already the predicted one is out of the+ # nil-category scope entirely — filtered before enrichment.+ txn = create_transaction(account: @account, name: "Starbucks Coffee")++ result = categorizer.classify_and_apply([ txn.transaction.id ])+ assert_kind_of Family::BayesCategorizer::Result, result+ assert_equal [ txn.transaction.id ], result.categorized_ids+ assert_equal 1, result.modified_count+ end+end