Skip to content

Instantly share code, notes, and snippets.

@antimon2
Created August 13, 2012 07:02
Show Gist options
  • Select an option

  • Save antimon2/3337609 to your computer and use it in GitHub Desktop.

Select an option

Save antimon2/3337609 to your computer and use it in GitHub Desktop.
naivebayes.rb (translated from naivebayes.py)
# -*- coding: utf-8 -*-
# morphological.rb
# original: morphological.py (http://gihyo.jp/dev/serial/01/machine-learning/0003)
require 'MeCab'
module Morphological
def split sentence
mecab = MeCab::Tagger.new
node = mecab.parseToNode sentence
result = []
until node.nil?
result << node.surface.force_encoding('UTF-8') if pos_filter(node.posid)
node = node.next
end
result
end
module_function :split
def pos_filter posid, filters = "1|2|3|4|5|9|10"
flist = filters.split(/\|/)
case posid
when 2 # 感動詞
flist.include? "3"
when 3..9 # 記号
flist.include? "13"
when 10..12 # 形容詞
flist.include? "1"
when 13..24 # 助詞
flist.include? "11"
when 25 # 助動詞
flist.include? "12"
when 26 # 接続詞
flist.include? "6"
when 27..30 # 接頭辞
flist.include? "7"
when 31..33 # 動詞
flist.include?("10")
when 34, 35 # 副詞
flist.include? "4"
when 36..67 # 名詞、一部形容動詞語幹
flist.include?("9") || flist.include?("2") && [40, 52, 64].include?(posid)
when 68 # 連体詞
flist.include? "5"
else
false
end
end
module_function :pos_filter
end
# -*- coding: utf-8 -*-
# naivebayes.rb
# original: naivebayes.py (http://gihyo.jp/dev/serial/01/machine-learning/0003)
require_relative 'morphological'
require 'set'
def get_words doc
Morphological.split(doc).map(&:downcase)
end
class NaiveBayes
def initialize
@vocabularies = Set.new
@wordcount = {}
@catcount = Hash.new {|h, cat| h[cat] = 0}
end
# 訓練フェーズ:単語のカウントアップ
def word_count_up word, cat
@wordcount[cat] ||= Hash.new {|h, word| h[word] = 0}
@wordcount[cat][word] += 1
@vocabularies << word
end
# 訓練フェーズ:カテゴリのカウントアップ
def cat_count_up cat
@catcount[cat] += 1
end
# 訓練
def train doc, cat
get_words(doc).each do |w|
word_count_up w, cat
end
cat_count_up cat
end
# 推定フェーズ:catの生起確率 P(cat)
def prior_prob cat
@catcount[cat].to_f / @catcount.values.inject(:+)
end
# 推定フェーズ:あるカテゴリの中に単語が登場した回数
def in_category word, cat
return @wordcount[cat][word] if @wordcount[cat].key? word
0
end
# 推定フェーズ:条件付き確率 P(word|cat)(補正つき)
def word_prob word, cat
#in_category(word, cat).to_f / @wordcount[cat].values.inject(:+)
#↓
(in_category(word, cat) + 1.0) / (@wordcount[cat].values.inject(:+) + @vocabularies.size)
end
# 推定フェーズ:スコア計算
def score words, cat
score = Math.log(prior_prob(cat))
words.each do |w|
score += Math.log(word_prob(w, cat))
end
score
end
# 推定フェーズ:分類
def classifier doc
best = nil # 最適なカテゴリ
max = -2147483648
words = get_words(doc)
# カテゴリ毎に確率の対数を求める
@catcount.keys.each do |cat|
prob = score(words, cat)
if prob > max
max = prob
best = cat
end
end
best
end
end
if $0 == __FILE__
nb = NaiveBayes.new
nb.train('Python(パイソン)は,オランダ人のグイド・ヴァンロッサムが作ったオープンソースのプログラミング言語。オブジェクト指向スクリプト言語の一種であり,Perlとともに欧米で広く普及している。イギリスのテレビ局 BBC が製作したコメディ番組『空飛ぶモンティパイソン』にちなんで名付けられた。Python は英語で爬虫類のニシキヘビの意味で,Python言語のマスコットやアイコンとして使われることがある。Pythonは汎用の高水準言語である。プログラマの生産性とコードの信頼性を重視して設計されており,核となるシンタックスおよびセマンティクスは必要最小限に抑えられている反面,利便性の高い大規模な標準ライブラリを備えている。Unicode による文字列操作をサポートしており,日本語処理も標準で可能である。多くのプラットフォームをサポートしており(動作するプラットフォーム),また,豊富なドキュメント,豊富なライブラリがあることから,産業界でも利用が増えつつある。', 'Python')
nb.train('Ruby(ルビー)は,まつもとゆきひろ(通称Matz)により開発されたオブジェクト指向スクリプト言語であり,従来 Perlなどのスクリプト言語が用いられてきた領域でのオブジェクト指向プログラミングを実現する。Rubyは当初1993年2月24日に生まれ, 1995年12月にfj上で発表された。名称のRubyは,プログラミング言語Perlが6月の誕生石であるPearl(真珠)と同じ発音をすることから,まつもとの同僚の誕生石(7月)のルビーを取って名付けられた。', 'Ruby')
nb.train('豊富な機械学習(きかいがくしゅう,Machine learning)とは,人工知能における研究課題の一つで,人間が自然に行っている学習能力と同様の機能をコンピュータで実現させるための技術・手法のことである。ある程度の数のサンプルデータ集合を対象に解析を行い,そのデータから有用な規則,ルール,知識表現,判断基準などを抽出する。データ集合を解析するため,統計学との関連も非常に深い。機械学習は検索エンジン,医療診断,スパムメールの検出,金融市場の予測,DNA配列の分類,音声認識や文字認識などのパターン認識,ゲーム戦略,ロボット,など幅広い分野で用いられている。応用分野の特性に応じて学習手法も適切に選択する必要があり,様々な手法が提案されている。それらの手法は, Machine Learning や IEEE Transactions on Pattern Analysis and Machine Intelligence などの学術雑誌などで発表されることが多い。', '機械学習')
##追加学習
#nb.train("ヴァンロッサム氏によって開発されました。", "Python")
#Python
words = 'ヴァンロッサム氏によって開発されました.'
puts "%s => 推定カテゴリ: %s" % [words ,nb.classifier(words)]
words = '豊富なドキュメントや豊富なライブラリがあります.'
puts "%s => 推定カテゴリ: %s" % [words ,nb.classifier(words)]
#Ruby
words = '純粋なオブジェクト指向言語です.'
puts "%s => 推定カテゴリ: %s" % [words ,nb.classifier(words)]
words = 'Rubyはまつもとゆきひろ氏(通称Matz)により開発されました.'
puts "%s => 推定カテゴリ: %s" % [words ,nb.classifier(words)]
#機械学習
words = '「機械学習 はじめよう」が始まりました.'
puts "%s => 推定カテゴリ: %s" % [words ,nb.classifier(words)]
words = '検索エンジンや画像認識に利用されています.'
puts "%s => 推定カテゴリ: %s" % [words , nb.classifier(words)]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment