【问题标题】:get next word from bigram model on max probability从最大概率的二元模型中获取下一个单词
【发布时间】:2018-09-21 12:50:56
【问题描述】:

我想使用带有二元组的 nltk 生成十四行诗。我已经生成了二元组并计算了每个二元组的概率,并像这样存储在默认字典中。

[('"Let', defaultdict(<function <lambda>.<locals>.<lambda> at0x1a17f98bf8>, 
{'the': 0.2857142857142857, 'dainty': 
0.14285714285714285, 'it': 0.14285714285714285, 'those': 
0.14285714285714285, 'me': 0.14285714285714285, 'us': 
0.14285714285714285}))]

给出每个单词出现在let之后的概率。像这样,我的语料库有二元模型。现在我想生成 4 行十四行诗,每行 15 个单词。我已经尝试过这段代码,但它不起作用。

def generate_sonnet(word):
lines = 4
words= 15
for i in range(lines):
    line = ()
    for j in range(words):
   #I am selecting max probability but not that word. How I can select that word which has max probability of occurring with word?
        nword = float(max(model[word].values()))
        word += nword
        
word = random.choice(poetrylist)
generate_sonnet(word)

我选择一个随机单词并将其传递给我的函数。我想使用二元组加入 15 个单词,当 1 行完成时,接下来的 3 行应该完成。

【问题讨论】:

    标签: python nltk defaultdict language-model


    【解决方案1】:

    这里有一个简单的代码 sn-p 来展示这个任务是如何实现的(用一种非常幼稚的方法)

    bigram1 = {'Let' : {'the': 0.2857142857142857, 'dainty':
    0.14285714285714285, 'it': 0.14285714285714285, 'those':
    0.14285714285714285, 'me': 0.14285714285714285, 'us':
    0.14285714285714285}}
    
    bigram2 = {'the' : {'dogs' : 0.4, 'it' : 0.2, 'a' : 0.2, 'b': 0.2}}
    bigram3 = {'dogs' : {'out' : 0.6, 'it' : 0.2, 'jj' : 0.2}}
    
    model = {}
    model.update(bigram1)
    model.update(bigram2)
    model.update(bigram3)
    
    sentence = []
    
    iterations = 3
    word = 'Let'
    sentence.append(word)
    
    for _ in range(iterations):
        max_value = 0
        for k, v in model[word].iteritems():
            if v >= max_value:
                word = k
                max_value = v
        sentence.append(word)
    
    
    print(" ".join(sentence)) 
    

    输出

    Let the dogs out
    

    代码以非常简单的方式编写,这是用于理解建议的玩具示例

    记住,在遇到的第一个单词中取的单词是最大值 值因此这个模型是确定性的,考虑添加随机 从一组具有相同最大值的单词中进行选择的方法 价值

    我建议像这样按概率对单词进行采样

    dist = {'the': 0.2857142857142857, 'dainty':
    0.14285714285714285, 'it': 0.14285714285714285, 'those':
    0.14285714285714285, 'me': 0.14285714285714285, 'us':
    0.14285714285714285}
    
    words = dist.keys()
    probabilities = dist.values()
    numpy.random.choice(words, p=probabilities)
    

    这将根据给定的分布每次给你“随机”字

    smt 像这样(草稿

    for _ in range(iterations):
        word = np.random.choice(model[word].keys(), p=model[word].values())
    

    【讨论】:

    • 你能把新代码放到之前的代码中吗?我不知道它应该放在哪里。
    猜你喜欢
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多