標籤:ini around oid 引用 update min 基於 上下文無關文法 weight
前言
演算法來自國外大牛的一篇部落格:點擊此處可查看
演算法不涉及任何人工智慧領域知識,僅僅是針對上下文無關文法提出的產生句子的思路。
上下文無關文法
上下文無關文法僅與句子結構有關,與上下文語意無關。
屬性|單詞
--|--
S |NP VP
NP |Det N / Det N
NP |I / he / she / Joe
VP |V NP / VP
Det |a / the / my / his
N |elephant / cat / jeans / suit
V |kicked / followed / shot
上面是一個上下文無關文法規則的例子,S代表一個句子,從S開始,逐漸遞迴填充單詞,便可以產生一個句子。
基本實現
import randomfrom collections import defaultdictclass CFG(object): def __init__(self): self.prod = defaultdict(list) # 預設dict值為list,對於空索引值對來說 def add_prod(self, lhs, rhs): """ Add production to the grammar. 'rhs' can be several productions separated by '|'. Each production is a sequence of symbols separated by whitespace. Usage: grammar.add_prod('NT', 'VP PP') grammar.add_prod('Digit', '1|2|3|4') """ prods = rhs.split('|') # 按照|分割 for prod in prods: self.prod[lhs].append(tuple(prod.split())) # 預設split按空格進行分割,但是這裡的分割是產生一個元組,整體添加到prod裡 def gen_random(self, symbol): """ Generate a random sentence from the grammar, starting with the given symbol. """ sentence = '' # select one production of this symbol randomly rand_prod = random.choice(self.prod[symbol]) # 從符號列表中隨機播放一個片語 for sym in rand_prod: #遍曆片語中的單詞 # for non-terminals, recurse if sym in self.prod: #如果這個位置的單詞並不是一個確切的單詞,而是一個詞法結構,那麼遞迴選擇相應的合格單詞 sentence += self.gen_random(sym) else: sentence += sym + ' ' #如果已經是一個確切的單詞,那麼直接連接到句子上即可 return sentencecfg1 = CFG()cfg1.add_prod('S', 'NP VP')cfg1.add_prod('NP', 'Det N | Det N')cfg1.add_prod('NP', 'I | he | she | Joe')cfg1.add_prod('VP', 'V NP | VP')cfg1.add_prod('Det', 'a | the | my | his')cfg1.add_prod('N', 'elephant | cat | jeans | suit')cfg1.add_prod('V', 'kicked | followed | shot')for i in range(10): print(cfg1.gen_random('S'))
這裡給出了一個基於Python的基本實現,通過遞迴填充單詞即可。
上下文無關文法導致無法終止的問題
上面的演算法很簡單,可以看起來很棒。但實際上存在一個問題,容易導致無法終止的問題。
屬性|運算式
--|--
EXPR|TERM + EXPR
EXPR|TERM - EXPR
EXPR|TERM
TERM|FACTOR * TERM
TERM|FACTOR / TERM
TERM|FACTOR
FACTOR|ID // NUM // ( EXPR )
ID|x // y // z // w
NUM|0//1//2//3//4//5//6//7//8//9
例如上面一個產生算數運算式的例子,上面的規則都符合正常的數學知識,但是在產生運算式的過程中產生了不能終結的問題。EXPR->TERM + EXPR->TERM + EXPR,類似這樣的無限迴圈。
解決無法終止問題
破解無法終止的問題,可以採用機率產生演算法。
這裡引用了作者原文中的圖,由於TERM-EXPR的祖先已經使用過這個運算式,那麼此時這個運算式的產生機率會相應地降低,例中的降低因子是0.5,也就是說使用過一次,那麼下一次使用這個運算式的機率只有原來的50%。
上述演算法使用代碼實現如下
import randomfrom collections import defaultdict# 機率選擇演算法def weighted_choice(weights): rnd = random.random() * sum(weights) for i, w in enumerate(weights): rnd -= w if rnd < 0: return iclass CFG(object): def __init__(self): self.prod = defaultdict(list) # 預設dict值為list,對於空索引值對來說 def add_prod(self, lhs, rhs): """ Add production to the grammar. 'rhs' can be several productions separated by '|'. Each production is a sequence of symbols separated by whitespace. Usage: grammar.add_prod('NT', 'VP PP') grammar.add_prod('Digit', '1|2|3|4') """ prods = rhs.split('|') # 按照|分割 for prod in prods: self.prod[lhs].append(tuple(prod.split())) # 預設split按空格進行分割,但是這裡的分割是產生一個元組,整體添加到prod裡 def gen_random_convergent(self, symbol, cfactor=0.25, pcount=defaultdict(int) ): """ Generate a random sentence from the grammar, starting with the given symbol. Uses a convergent algorithm - productions that have already appeared in the derivation on each branch have a smaller chance to be selected. cfactor - controls how tight the convergence is. 0 < cfactor < 1.0 pcount is used internally by the recursive calls to pass on the productions that have been used in the branch. """ sentence = '' # The possible productions of this symbol are weighted # by their appearance in the branch that has led to this # symbol in the derivation # weights = [] for prod in self.prod[symbol]: # 對於滿足某個要求的所有運算式,計算相應的產生機率 if prod in pcount: weights.append(cfactor ** (pcount[prod])) # 對於父節點已經引用過的運算式,此處需要根據因子減小產生機率 else: weights.append(1.0) # rand_prod = self.prod[symbol][weighted_choice(weights)] # 根據機率選擇新產生的運算式 # pcount is a single object (created in the first call to # this method) that's being passed around into recursive # calls to count how many times productions have been # used. # Before recursive calls the count is updated, and after # the sentence for this call is ready, it is rolled-back # to avoid modifying the parent's pcount. # pcount[rand_prod] += 1 for sym in rand_prod: # for non-terminals, recurse if sym in self.prod: # 如果不是一個確切的單詞,那麼遞迴填充運算式 sentence += self.gen_random_convergent( sym, cfactor=cfactor, pcount=pcount) else: sentence += sym + ' ' # 如果是一個確切的單詞,那麼直接添加到句子後面即可 # backtracking: clear the modification to pcount pcount[rand_prod] -= 1 # 由於pcount是引用傳值,因此需要恢複原來狀態 return sentencecfg1 = CFG()cfg1.add_prod('S', 'NP VP')cfg1.add_prod('NP', 'Det N | Det N')cfg1.add_prod('NP', 'I | he | she | Joe')cfg1.add_prod('VP', 'V NP | VP')cfg1.add_prod('Det', 'a | the | my | his')cfg1.add_prod('N', 'elephant | cat | jeans | suit')cfg1.add_prod('V', 'kicked | followed | shot')for i in range(10): print(cfg1.gen_random_convergent('S'))cfg2 = CFG()cfg2.add_prod('EXPR', 'TERM + EXPR')cfg2.add_prod('EXPR', 'TERM - EXPR')cfg2.add_prod('EXPR', 'TERM')cfg2.add_prod('TERM', 'FACTOR * TERM')cfg2.add_prod('TERM', 'FACTOR / TERM')cfg2.add_prod('TERM', 'FACTOR')cfg2.add_prod('FACTOR', 'ID | NUM | ( EXPR )')cfg2.add_prod('ID', 'x | y | z | w')cfg2.add_prod('NUM', '0|1|2|3|4|5|6|7|8|9')for i in range(10): print(cfg2.gen_random_convergent('EXPR'))
小結
通過遞迴,可以很容易地實現基於上下文無關文法產生句子的演算法。但是需要注意的是,普通演算法會導致無法終止的問題,針對這個問題,有人提出了基於機率的句子產生演算法,很好地解決了無法終止的問題。
基於上下文無關文法的句子產生演算法