Created
June 22, 2010 09:24
-
-
Save showyou/448232 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! -*- coding:utf-8 -*- | |
| import random | |
| import numpy as np | |
| def p(str): | |
| print str | |
| pass | |
| def p2(str): | |
| print str, | |
| pass | |
| class HMM(): | |
| def __init__(self): | |
| # 状態 | |
| self.state = [ "A", "B", "C", "D", "E","$"] | |
| # 状態遷移確率 | |
| self.trans = [ | |
| [ 0, 5, 1, 3, 0, 0], #An1 | |
| [ 1, 0, 1, 1, 1, 1], #An2 | |
| [ 1, 0, 0, 1, 1, 1], | |
| [ 1, 0, 1, 1, 1, 1], | |
| [ 0, 0, 2, 1, 1, 0], | |
| [ 0, 0, 0, 0, 0, 1] | |
| ] | |
| # 出力文字 | |
| self.outStrings = [ "天使", "ちゃん", "マジ", "!", "ユイにゃん","$"] | |
| self.outProbabilities = [ | |
| [ 1, 0, 0, 0, 0, 0 ], | |
| [ 0, 1, 0, 0, 0, 0 ], | |
| [ 0, 0, 1, 0, 0, 0 ], | |
| [ 0, 0, 0, 1, 0, 0 ], | |
| [ 0, 0, 0, 0, 1, 0 ], | |
| [ 0, 0, 0, 0, 0, 1 ], | |
| ] | |
| self.position = self.outPosition = 0 | |
| # 文字列を生成して、次の候補を探す | |
| def generateState(self): | |
| self.position = self.generate(self.trans) | |
| # 次の単語を状態から引っ張ってくる | |
| def generateWord(self): | |
| self.outPosition = self.generate(self.outProbabilities) | |
| def generate(self, prob): | |
| nextCandidates = prob[self.position] | |
| #print nextCandidates | |
| cands = [] | |
| probs = [] | |
| for i in range(len(nextCandidates)): | |
| if nextCandidates[i] >= 1: | |
| cands.append(i) | |
| probs.append(nextCandidates[i]) | |
| probs = np.array(probs, dtype=float) | |
| probs /= sum(probs) | |
| return self.choiseNextCandidate(cands, probs) | |
| # 割合に応じて次の候補を選択します | |
| def choiseNextCandidate(self, cands, probs): | |
| p2(cands) | |
| p2(probs) | |
| n = np.random.multinomial(1, probs).argmax() | |
| p2(cands[n]) | |
| return cands[n] | |
| def getState(self): | |
| return self.state[self.position] | |
| def getOutStrings(self): | |
| return self.outStrings[self.outPosition] | |
| from collections import defaultdict | |
| # choiseNextCandidate がだいたい割合通りかのテスト | |
| def testChoiseNextCandidate_Probability(): | |
| testData = [1,2,3] | |
| probs = np.array([1,2, 3], dtype=float) | |
| probs /= sum(probs) | |
| result = defaultdict(int) | |
| for i in xrange(100): | |
| n = HMM().choiseNextCandidate(testData, probs) | |
| result[n] += 1 | |
| p(result) | |
| #testChoiseNextCandidate_Probability() | |
| answer = [] | |
| a = HMM() | |
| s = a.getState() | |
| p("現在の状態 出力候補 出力確率 出力選択 遷移候補 遷移確率 遷移選択") | |
| while s != '$': | |
| p2(s) | |
| a.generateWord() | |
| o = a.getOutStrings() | |
| answer.append(o) | |
| a.generateState() | |
| s = a.getState() | |
| p("") | |
| p("".join(answer)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment