首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NLP任务中单词共生矩阵的计算工具

NLP任务中单词共生矩阵的计算工具
EN

Stack Overflow用户
提问于 2017-05-11 08:21:23
回答 1查看 2.5K关注 0票数 4

我有一个15 of的文字。我需要计算出固定窗口大小的单词的共现计数,然后再对它们进行处理。例如,这是我的文字;

“福说呼,酒吧说什么?”

对于窗口大小为4的文本,若要构造共现频率的双图,输出应如下;

字1-字2-计数

福,说,1

foo,呼,1

foo,bar,1

说,呼,2

说,酒吧,2

说,说,1

哇,酒吧,1

呼,什么,1

酒吧,什么,1

说,什么,1

我已经知道有一些工具可以这样做,比如NLTK,但是它不是多线程的,所以对于大小为15 it的文本不起作用。在给定的窗口大小和速度上,有什么工具可以给我单词的共生矩阵吗?

EN

回答 1

Stack Overflow用户

发布于 2017-05-11 11:10:55

我自己也找过这样的工具,但从未找到过。我通常只是写一个脚本来完成它。下面是一个可能对您有用的有一些限制的示例:

代码语言:javascript
复制
import concurrent.futures
from collections import Counter

tokens = []

for _ in range(10):
    tokens.extend(['lazy', 'old', 'fart', 'lying', 'on', 'the', 'bed'])


def cooccurrances(idx, tokens, window_size):

    # beware this will backfire if you feed it large files (token lists)
    window = tokens[idx:idx+window_size]    
    first_token = window.pop(0)

    for second_token in window:
        yield first_token, second_token

def harvest_cooccurrances(tokens, window_size=3, n_workers=5):
    l = len(tokens)
    harvest = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=n_workers) as executor:
        future_cooccurrances = {
            executor.submit(cooccurrances, idx, tokens, window_size): idx
            for idx
            in range(l)
        }
        for future in concurrent.futures.as_completed(future_cooccurrances):
            try:
                harvest.extend(future.result())
            except Exception as exc:
                # you may want to add some logging here
                continue


    return harvest

def count(harvest):
    return [
        (first_word, second_word, count) 
        for (first_word, second_word), count 
        in Counter(harvest).items()
    ]


harvest = harvest_cooccurrances(tokens, 3, 5)
counts = count(harvest)

print(counts)

如果您只运行以下代码,您就应该看到这一点:

代码语言:javascript
复制
[('lazy', 'old', 10),
 ('lazy', 'fart', 10),
 ('fart', 'lying', 10),
 ('fart', 'on', 10),
 ('lying', 'on', 10),
 ('lying', 'the', 10),
 ('on', 'the', 10),
 ('on', 'bed', 10),
 ('old', 'fart', 10),
 ('old', 'lying', 10),
 ('the', 'bed', 10),
 ('the', 'lazy', 9),
 ('bed', 'lazy', 9),
 ('bed', 'old', 9)]

限制

  • 由于切片,此脚本不能很好地处理大型令牌列表。
  • window列表的切分在这里起作用,但是如果您打算对窗口列表片做任何事情,您应该知道这一点。
  • 您可能需要实现一些特定的东西来替换Counter对象,以防阻塞(同样是大列表限制)。

野生猜

您可能可以使用spaCy Matcher (请参阅这里)编写类似的东西,但是,我不确定这是否会奏效,因为您需要的通配符仍然有点不稳定(根据我的经验)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43910107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档