質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

1回答

865閲覧

ナイーブベイズ分類について

Mr_K

総合スコア28

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2019/03/17 16:31

naivebayesを行いたいのですが構文に誤りがあるみたいでどう直せばよいかわかりません。実行ファイルはnaivebayes.pyで中に出てくるmorphological.pyも挙げておきます。わかる方教えてください

python

1#morphological.py 2 3# -*- coding: utf-8 -*- 4''' 5Created on 2010/07/21 6 7@author: iori_o 8''' 9import urllib 10import urllib2 11from BeautifulSoup import BeautifulSoup 12 13appid = 'Yahoo!デベロッパーズネットワークのアプリケーションIDを入力して下さい' 14pageurl = "http://jlp.yahooapis.jp/MAService/V1/parse" 15 16# Yahoo!形態素解析の結果をリストで返す 17def split(sentence, appid=appid, results="ma", filter="1|2|3|4|5|9|10"): 18 sentence = sentence.encode("utf-8") 19 params = urllib.urlencode({'appid':appid, 'results':results, 'filter':filter, 'sentence':sentence}) 20 results = urllib2.urlopen(pageurl, params) 21 soup = BeautifulSoup(results.read()) 22 23 return [w.surface.string for w in soup.ma_result.word_list] 24

python

1#naivebayes.py 2# -*- coding: utf-8 -*- 3import math 4import sys 5 6#yahoo!形態素解析 7import morphological 8 9def getwords(doc): 10 words = [s.lower() for s in morphological.split(doc)] 11 return tuple(w for w in words) 12 13class NaiveBayes: 14 def __init__(self): 15 self.vocabularies = set() # 単語の集合 16 self.wordcount = {} # {category : { words : n, ...}} 17 self.catcount = {} # {category : n} 18 19 def wordcountup(self, word, cat): 20 self.wordcount.setdefault(cat, {}) 21 self.wordcount[cat].setdefault(word, 0) 22 self.wordcount[cat][word] += 1 23 self.vocabularies.add(word) 24 25 def catcountup(self, cat): 26 self.catcount.setdefault(cat, 0) 27 self.catcount[cat] += 1 28 29 def train(self, doc, cat): 30 word = getwords(doc) 31 for w in word: 32 self.wordcountup(w, cat) 33 self.catcountup(cat) 34 35 def classifier(self, doc): 36 best = None # 最適なカテゴリ 37 max = -sys.maxint 38 word = getwords(doc) 39 40 # カテゴリ毎に確率の対数を求める 41 for cat in self.catcount.keys(): 42 prob = self.score(word, cat) 43 if prob > max: 44 max = prob 45 best = cat 46 47 return best 48 49 def score(self, word, cat): 50 score = math.log(self.priorprob(cat)) 51 for w in word: 52 score += math.log(self.wordprob(w, cat)) 53 return score 54 55 def priorprob(self, cat): 56 return float(self.catcount[cat]) / sum(self.catcount.values()) 57 58 def incategory(self, word, cat): 59 #あるカテゴリの中に単語が登場した回数を返す 60 if word in self.wordcount[cat]: 61 return float(self.wordcount[cat][word]) 62 return 0.0 63 64 def wordprob(self, word, cat): 65 # P(word|cat)が生起する確率を求める 66 prob = \ 67 (self.incategory(word, cat) + 1.0) / \ 68 (sum(self.wordcount[cat].values()) + \ 69 len(self.vocabularies) * 1.0) 70 return prob 71 72if __name__ == "__main__": 73 nb = NaiveBayes() 74 75 76 nb.train(u'''Python(パイソン)は、オランダ人のグイド・ヴァンロッサムが作ったオープンソースのプログラミング言語。 77オブジェクト指向スクリプト言語の一種であり、Perlとともに欧米で広く普及している。イギリスのテレビ局 BBC が製作したコメディ番組『空飛ぶモンティパイソン』にちなんで名付けられた。 78Pythonは英語で爬虫類のニシキヘビの意味で、Python言語のマスコットやアイコンとして使われることがある。Pythonは汎用の高水準言語である。プログラマの生産性とコードの信頼性を重視して設計されており、核となるシンタックスおよびセマンティクスは必要最小限に抑えられている反面、利便性の高い大規模な標準ライブラリを備えている。 79Unicodeによる文字列操作をサポートしており、日本語処理も標準で可能である。 多くのプラットフォームをサポートしており(動作するプラットフォーム)、また、豊富なドキュメント、豊富なライブラリがあることから、産業界でも利用が増えつつある。''', 'Python') 80 81 nb.train(u'''Ruby(ルビー)は、まつもとゆきひろ(通称Matz)により開発されたオブジェクト指向スクリプト言語であり、従来Perlなどのスクリプト言語が用いられてきた領域でのオブジェクト指向プログラミングを実現する。Rubyは当初1993年2月24日に生まれ、1995年12月にfj上で発表された。名称のRubyは、プログラミング言語Perlが6月の誕生石であるPearl(真珠)と同じ発音をすることから、まつもとの同僚の誕生石(7月)のルビーを取って名付けられた。''', 'Ruby') 82 83 nb.train(u'''豊富な機械学習(きかいがくしゅう、Machine learning)とは、人工知能における研究課題の一つで、人間が自然に行っている学習能力と同様の機能をコンピュータで実現させるための技術・手法のことである。 ある程度の数のサンプルデータ集合を対象に解析を行い、そのデータから有用な規則、ルール、知識表現、判断基準などを抽出する。 データ集合を解析するため、統計学との関連も非常に深い。 84機械学習は検索エンジン、医療診断、スパムメールの検出、金融市場の予測、DNA配列の分類、音声認識や文字認識などのパターン認識、ゲーム戦略、ロボット、など幅広い分野で用いられている。応用分野の特性に応じて学習手法も適切に選択する必要があり、様々な手法が提案されている。それらの手法は、Machine Learning や IEEE Transactions on Pattern Analysis and Machine Intelligence などの学術雑誌などで発表されることが多い。''', u'機械学習') 85 86#Python 87words = u'ヴァンロッサム氏によって開発されました.' 88print u'%s => 推定カテゴリ: %s' % (words ,nb.classifier(words)) 89 90words = u'豊富なドキュメントや豊富なライブラリがあります.' 91print u'%s => 推定カテゴリ: %s' % (words ,nb.classifier(words)) 92 93#Ruby 94words = u'純粋なオブジェクト指向言語です.' 95print u'%s => 推定カテゴリ: %s' % (words ,nb.classifier(words)) 96 97words = u'Rubyはまつもとゆきひろ氏(通称Matz)により開発されました.' 98print u'%s => 推定カテゴリ: %s' % (words ,nb.classifier(words)) 99 100#機械学習 101words = u'「機械学習 はじめよう」が始まりました.' 102print u'%s => 推定カテゴリ: %s' % (words ,nb.classifier(words)) 103 104words = u'検索エンジンや画像認識に利用されています.' 105print u'%s => 推定カテゴリ: %s' % (words , nb.classifier(words)) 106

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

python2のコードのようなので、python3でそのまま実行はできません。

書き直せば実行できるとは思いますが、2010年に書かれたものだと、さすがに古いので、新し目のものを探してはいかがですか・・・

投稿2019/03/17 16:36

hayataka2049

総合スコア30933

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問