我不太了解这个马尔可夫...需要两个词的前缀,后缀保存了它们的列表并随机单词?

    /* Copyright (C) 1999 Lucent Technologies */
/* Excerpted from 'The Practice of Programming' */
/* by Brian W. Kernighan and Rob Pike */

#include <time.h>
#include <iostream>
#include <string>
#include <deque>
#include <map>
#include <vector>

using namespace std;

const int  NPREF = 2;
const char NONWORD[] = "\n";    // cannot appear as real line: we remove newlines
const int  MAXGEN = 10000; // maximum words generated

typedef deque<string> Prefix;

map<Prefix, vector<string> > statetab; // prefix -> suffixes

void        build(Prefix&, istream&);
void        generate(int nwords);
void        add(Prefix&, const string&);

// markov main: markov-chain random text generation
int main(void)
{
    int nwords = MAXGEN;
    Prefix prefix;  // current input prefix

    srand(time(NULL));
    for (int i = 0; i < NPREF; i++)
        add(prefix, NONWORD);
    build(prefix, cin);
    add(prefix, NONWORD);
    generate(nwords);
    return 0;
}

// build: read input words, build state table
void build(Prefix& prefix, istream& in)
{
    string buf;

    while (in >> buf)
        add(prefix, buf);
}

// add: add word to suffix deque, update prefix
void add(Prefix& prefix, const string& s)
{
    if (prefix.size() == NPREF) {
        statetab[prefix].push_back(s);
        prefix.pop_front();
    }
    prefix.push_back(s);
}

// generate: produce output, one word per line
void generate(int nwords)
{
    Prefix prefix;
    int i;

    for (i = 0; i < NPREF; i++)
        add(prefix, NONWORD);
    for (i = 0; i < nwords; i++) {
        vector<string>& suf = statetab[prefix];
        const string& w = suf[rand() % suf.size()];
        if (w == NONWORD)
            break;
        cout << w << "\n";
        prefix.pop_front(); // advance
        prefix.push_back(w);
    }
}
有帮助吗?

解决方案

根据维基百科的说法,马尔可夫链是一个随机过程,下一个状态取决于先前的状态。这很难理解,所以我会尝试更好地解释它:

您正在看的东西似乎是生成基于文本的马尔可夫链的程序。从本质上讲,算法如下:

  1. 将文本主体分为令牌(单词,标点符号)。
  2. 构建频率表。这是一个数据结构,对于文本中的每个单词,您都有一个条目(键)。该键映射到另一个数据结构,该数据结构基本上是遵循此单词(键)及其频率的所有单词的列表。
  3. 生成马尔可夫链。为此,您选择一个起点(从频率表中的键),然后随机选择另一个状态要转到(下一个单词)。您选择的下一个单词取决于其频率(因此有些单词比其他单词更可能)。之后,您将此新词用作钥匙并重新开始。

例如,如果您查看此解决方案的第一句话,则可以提出以下频率表:

According: to(100%)
to:        Wikipedia(100%)
Wikipedia: ,(100%)
a:         Markov(50%), random(50%)
Markov:    Chain(100%)
Chain:     is(100%)
is:        a(33%), dependent(33%), ...(33%)
random:    process(100%)
process:   with(100%)
.
.
.
better:    :(100%)

从本质上讲,从一个状态到另一种状态的状态过渡是基于概率的。在基于文本的马尔可夫链的情况下,过渡概率基于所选单词之后单词的频率。因此,选定的单词表示先前的状态,频率表或单词表示(可能的)连续状态。如果您知道先前的状态(这是获得正确的频率表),则可以找到连续的状态,因此这符合连续状态取决于先前状态的定义。

无耻的插头 - 我写了一个程序以在Perl中进行此操作。你可以阅读 这里.

其他提示

马尔可夫连锁店是州机器,州过渡是概率。

字:鸡肉;可能的下一个单词:10% - IS; 30% - 是; 50% - 腿; 10% - 运行;

然后,您只需随机选择下一个单词或通过一些轮盘赌轮选择。您可以从一些输入文本中获得这些概率。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top