1. 程式人生 > >簡單馬爾可夫模型的實現(簡單的機器學習)

簡單馬爾可夫模型的實現(簡單的機器學習)

自然語言 index 馬爾科夫 ref item model not 次數 read

馬爾可夫模型(Markov Model)是一種統計模型,廣泛應用在語音識別,詞性自動標註,音字轉換,概率文法等各個自然語言處理等應用領域。經過長期發展,尤其是在語音識別中的成功應用,使它成為一種通用的統計工具。

以下利用一篇英文演講來實現簡單得文字生成器,結果其實是一個胡言亂語得結果,但我們可以通過這個類型粗略理解機器學習,首先英文演講文章的鏈接:http://pythonscraping.com/files/inaugurationSpeech.txt

以及我上一篇處理該文章的博客鏈接:http://www.cnblogs.com/ybf-yyj/p/7399149.html

以下以生成100個單詞的馬爾科夫鏈為例:

#-*- coding:utf-8 -*-
from urllib2 import urlopen
from random import randint

#統計所有單詞出現的次數總和
def wordListSum(wordList):
    sum=0
    for word,value in wordList.items():
        print word,value
        sum+=value
    return sum

def retrieveRandomWord(wordList):
    #在1到所有單詞出現總和之間選著一個數字,保證每次輸出句子不一樣
randIndex=randint(1,wordListSum(wordList)) #通過randIndex隨機選擇一個字母返回 for word,value in wordList.items(): randIndex-=value if randIndex<=0: return word def buildWordDic(text): #清洗\n和 " text=text.replace("\n"," ") text=text.replace("\"","") #保證標點符號和前面的單詞在一起,不被剔除
punctuation=[,,.,;,:] for symbol in punctuation: text=text.replace(symbol," "+symbol+" ") #切割文章 words=text.split(" ") #除去空單詞 words=[word for word in words if word !=""] #定義一個總詞典 wordDict={} for i in range(1,len(words)): #為新單詞再創一個新詞典 # 比如句子為:How do you do. if words[i-1] not in wordDict: #結果應該為:{‘How‘:{},‘do‘:{}} wordDict[words[i-1]]={} #將下一個單詞加入前一個單詞的詞典中 if words[i] not in wordDict[words[i - 1]]: # 結果應該為:{‘How‘:{‘do‘:0},‘do‘:{‘you‘:0,‘.‘:0}} wordDict[words[i-1]][words[i]]=0 # 結果應該為:{‘How‘:{‘do‘:1},‘do‘:{‘you‘:1,‘.‘:1}} wordDict[words[i - 1]][words[i]]=wordDict[words[i-1]][words[i]]+1 return wordDict text=str(urlopen(http://pythonscraping.com/files/inaugurationSpeech.txt).read().decode(utf-8)) wordDict=buildWordDic(text) length=100 chain=‘‘ #隨便選擇一個單詞開頭 currentword=I for i in range(0,length): chain +=currentword+ currentword=str(retrieveRandomWord(wordDict[currentword])) print(chain)

簡單馬爾可夫模型的實現(簡單的機器學習)