【发布时间】:2019-11-12 15:56:58
【问题描述】:
上下文
关于如何使用 gensim 和流数据训练 Word2Vec 存在几个问题。无论如何,这些问题并没有解决流不能使用多个工作线程的问题,因为没有数组可以在线程之间拆分。
因此,我想创建一个为 gensim 提供此类功能的生成器。我的结果如下:
from gensim.models import Word2Vec as w2v
#The data is stored in a python-list and unsplitted.
#It's too much data to store it splitted, so I have to do the split while streaming.
data = ['this is document one', 'this is document two', ...]
#Now the generator-class
import threading
class dataGenerator:
"""
Generator for batch-tokenization.
"""
def __init__(self, data: list, batch_size:int = 40):
"""Initialize generator and pass data."""
self.data = data
self.batch_size = batch_size
self.lock = threading.Lock()
def __len__(self):
"""Get total number of batches."""
return int(np.ceil(len(self.data) / float(self.batch_size)))
def __iter__(self) -> list([]):
"""
Iterator-wrapper for generator-functionality (since generators cannot be used directly).
Allows for data-streaming.
"""
for idx in range(len(self)):
yield self[idx]
def __getitem__(self, idx):
#Make multithreading thread-safe
with self.lock:
# Returns current batch by slicing data.
return [arr.split(" ") for arr in self.data[idx * self.batch_size : (idx + 1) * self.batch_size]]
#And now do the training
model = w2v(
sentences=dataGenerator(data),
size=300,
window=5,
min_count=1,
workers=4
)
这会导致错误
TypeError: unhashable type: 'list'
由于dataGenerator(data) 如果我只生成一个拆分文档就可以工作,我假设 gensims word2vec 将生成器包装在一个额外的列表中。在这种情况下,__iter__ 看起来像:
def __iter__(self) -> list:
"""
Iterator-wrapper for generator-functionality (since generators cannot be used directly.
Allows for data-streaming.
"""
for text in self.data:
yield text.split(" ")
因此,我的批次也会被包装成类似 [[['this', '...'], ['this', '...']], [[...], [...]]] (=> list of list of list) 之类的东西,gensim 无法处理。
我的问题:
我可以“流”传递批次以使用多个工人吗? 如何相应地更改我的代码?
【问题讨论】:
标签: python nlp batch-processing gensim word2vec