前情提要
在学习NLP的新手教程Bag of Words Meets Bags of Popcorn这个比赛的Overview的教程里有一个把每篇文本切分成按句划分的单词list的预处理过程,原文的代码是这样的:
sentences = [] # Initialize an empty list of sentences
print "Parsing sentences from training set"
for review in train["review"]:
sentences += review_to_sentences(review, tokenizer)
print "Parsing sentences from unlabeled set"
for review in unlabeled_train["review"]:
sentences += review_to_sentences(review, tokenizer)
运行之后会花费长达五分钟的时间完成对75000篇电影测评文段预处理的过程,非常难等·。.|||
而且整个过程中可以看到kaggle kernel提供的四颗cpu只有最高120%的占用,所以想到通过创建多个进程来提速,节省预处理环节的时间。借助multiprocessing这个自带的库,写出来是这样的:
import multiprocessing
def fillup(dataset):
count = 0
sentences1 = []
for i in dataset["review"]:
sentences1 += review_to_sentences(i,tokenizer) #review_to_sentences()为预处理函数
count += 1
print(count)
print("com")
return sentences1
pool = multiprocessing.Pool(2)
sets = [train,unlabeled_train]
result = pool.map(fillup,sets)
在pool里创建的两个进程分别用来处理train和unlabeled_train这两个数据集
然后一运行我的chrome就直接卡死无响应了·。.|||
经过反复排查发现是循环内的print(count)的原因……推测是两个进程同时往notebook的输入框塞东西,造成了某些未知的性能问题,考虑到Overview里面也没提到可以多进程,只是让人在屏幕前傻等几分钟,可能kernels的前端开发也没想到这个问题。。。
去掉fillup里面的print(count)后上文代码就可以正常运行了。cpu占用稳定在200%,只花了三分钟左右。
之后我转换了一下思路,重写了fillup这里的代码,改成了读入一个文段输出一个句子组成的list,然后直接map到数据集上,用Pool同时运行四个进程。
import multiprocessing
def element_fillup(data):
sentence2 = review_to_sentences(data,tokenizer) #review_to_sentences()为预处理函数
return sentence2
pool = multiprocessing.Pool(4)
result_ele1 = []
result_ele2 = []
result_ele1 = pool.map(element_fillup,train['review'])
result_ele2 = pool.map(element_fillup,train['review'])
print("com")
这下子cpu占用直接起飞了:
只用了一分23秒就完成了75000个文段的预处理,对比原来要等五分钟,效率提升很明显
最后把得到的list合并然后重新merge一下就得到和Overview里的代码一样的结果了·。.
result_ele = result_ele1 + result_ele2
result = []
for i in result_ele:
result += i #合并每个文段产生的句子list
result[0]
'''
Output:['with',
'all',
'this',
'stuff',
'going',
'down',
'at',
'the',
'moment',
'with',
'mj',
'i',
've',
'started',
'listening',
'to',
'his',
'music',
'watching',
'the',
'odd',
'documentary',
'here',
'and',
'there',
'watched',
'the',
'wiz',
'and',
'watched',
'moonwalker',
'again']
'''
2020-09-10 23:03:56 星期四
发表评论