bha*_*udi 3 python multithreading machine-learning feature-extraction
我是 Python 和机器学习的初学者。我正在尝试重现countvectorizer()使用多线程的代码。我正在使用 yelp 数据集使用LogisticRegression. 这是我到目前为止所写的:
代码片段:
from multiprocessing.dummy import Pool as ThreadPool
from threading import Thread, current_thread
from functools import partial
data = df['text']
rev = df['stars']
y = []
def product_helper(args):
return featureExtraction(*args)
def featureExtraction(p,t):
temp = [0] * len(bag_of_words)
for word in p.split():
if word in bag_of_words:
temp[bag_of_words.index(word)] += 1
return temp
# function to be mapped over
def calculateParallel(threads):
pool = ThreadPool(threads)
job_args = [(item_a, rev[i]) for i, item_a in enumerate(data)]
l = pool.map(product_helper,job_args)
pool.close()
pool.join()
return l
temp_X = calculateParallel(12)
Run Code Online (Sandbox Code Playgroud)
这只是代码的一部分。
解释:
df['text']拥有所有评论和df['stars']评级(1 到 5)。我正在尝试temp_X使用多线程查找字数向量。bag_of_words是一些常用词的列表。
题:
如果没有多线程,我能够temp_X在大约 24 分钟内计算出100k 评论大小的数据集,上面的代码需要 33 分钟。我的机器有 128GB 的 DRAM 和 12 个内核(6 个具有超线程的物理内核,即每个内核的线程数=2)。
我在这里做错了什么?
你的整个代码似乎CPU Bound而不是IO Bound。你只是在使用threads那些在GIL如此有效地运行一个线程加上开销的情况下。它只在一个核心上运行。要在多个核心上运行,请使用
用
import multiprocessing
pool = multiprocessing.Pool()
l = pool.map_async(product_helper,job_args)
Run Code Online (Sandbox Code Playgroud)
from multiprocessing.dummy import Pool as ThreadPool 只是thread模块的包装器。它仅使用one core而不是更多。