ぼざクリ タグ広場 https://hub.nizika.monster
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

29 lines
838 B

  1. namespace :post_similarity do
  2. desc '関聯投稿テーブル作成'
  3. task calc: :environment do
  4. dot = -> a, b { (a.keys & b.keys).sum { |k| a[k] * b[k] } }
  5. norm = -> v { Math.sqrt(v.values.sum { |e| e * e }) }
  6. cos = -> a, b do
  7. na = norm.(a)
  8. nb = norm.(b)
  9. if na.zero? || nb.zero?
  10. 0.0
  11. else
  12. dot.(a, b) / na / nb
  13. end
  14. end
  15. posts = Post.includes(:tags).to_a
  16. posts.each_with_index do |post, i|
  17. existence_of_tags = post.tags.index_with(1)
  18. ((i + 1)...posts.size).each do |j|
  19. target_post = posts[j]
  20. existence_of_target_tags = target_post.tags.index_with(1)
  21. PostSimilarity.find_or_initialize_by(post:, target_post:).tap { |ps|
  22. ps.cos = cos.(existence_of_tags, existence_of_target_tags)
  23. }.save!
  24. end
  25. end
  26. end
  27. end