Compare commits

...

1 Commits
main ... #92

Author SHA1 Message Date
  みてるぞ 138550bf02 #92 1 week ago
2 changed files with 32 additions and 0 deletions
Split View
  1. +4
    -0
      backend/app/models/tag_similarity.rb
  2. +28
    -0
      backend/lib/tasks/calc_tag_similarities.rake

+ 4
- 0
backend/app/models/tag_similarity.rb View File

@@ -0,0 +1,4 @@
class TagSimilarity < ApplicationRecord
belongs_to :tag, class_name: 'Tag', foreign_key: 'tag_id'
belongs_to :target_tag, class_name: 'Tag', foreign_key: 'target_tag_id'
end

+ 28
- 0
backend/lib/tasks/calc_tag_similarities.rake View File

@@ -0,0 +1,28 @@
namespace :tag_similarity do
desc '関聯タグ・テーブル作成'
task calc: :environment do
dot = -> a, b { (a.keys & b.keys).sum { |k| a[k] * b[k] } }
norm = -> v { Math.sqrt(v.values.sum { |e| e * e }) }
cos = -> a, b do
na = norm.(a)
nb = norm.(b)
if na.zero? || nb.zero?
0.0
else
dot.(a, b) / na / nb
end
end

tags = Tag.includes(:posts).to_a
tags.each_with_index do |tag, i|
existence_of_posts = tag.posts.index_with(1)
((i + 1)...tags.size).each do |j|
target_tag = tags[j]
existence_of_target_posts = target_tag.posts.index_with(1)
TagSimilarity.find_or_initialize_by(tag:, target_tag:).tap { |ts|
ts.cos = cos.(existence_of_posts, existence_of_target_posts)
}.save!
end
end
end
end

Loading…
Cancel
Save