自然言語処理の勉強をしています。参考サイトを元に複数値でcos類似度を計算し、値をソートして返したいのですが、やりたい事に対してのコードイメージが沸かず、どなたか指針やヒントをいただければと思い投稿しました。
やりたい事
1:文章を引き渡す(文章はN個)
("Bootstrap","Ruby O Rails","Bootstrapで画像スライダー","Bootstrapでモーダル")
2:下記3つの組み合わせで解析
"Bootstrap"と"Ruby O Rails"
"Bootstrap"と"Bootstrapで画像スライダー"
"Bootstrap"と,"Bootstrapでモーダル"
4:cos類似度を算出
5:返り値でcos類似度が高い組み合わせをソートして返す
2次元配列や繰り返し処理などを利用するかと思いますが、処理に対しての何の処理が必要かのイメージがついておりません。
どなたかご助力いただけると大変大変助かります。
require 'natto' require 'matrix' module CosSimilarity def calculate(text1, text2) a1 = break_up(text1) a2 = break_up(text2) uniq_words = (a1 + a2).uniq f1 = make_flags(uniq_words, a1) f2 = make_flags(uniq_words, a2) v1 = Vector.elements(f1, copy = true) v2 = Vector.elements(f2, copy = true) return v2.inner_product(v1)/(v1.norm() * v2.norm()) end def break_up(text) arr = Array.new nm = Natto::MeCab.new nm.parse(text) do |n| surface = n.surface feature = n.feature.split(',') # 品詞が名刺、かつ記号っぽくなければ採用 if feature.first == "名詞" && feature.last != '*' arr.push(surface) end end arr end def make_flags(uniq_words, elements) frags = [] uniq_words.each do |word| flag = elements.include?(word) == true ? 1 : 0 frags.push(flag) end frags end end CosSimilarity.calculate("Bootstrap","Ruby O Rails")
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/05/26 04:44