gpt4 book ai didi

python - 加速 Python NLP 文本解析

转载 作者:行者123 更新时间:2023-11-30 22:19:02 25 4
gpt4 key购买 nike

我有一个由大字符串组成的数据集(从大约 300 个 pptx 文件中提取的文本)。通过使用 pandas apply,我对每个字符串执行“平均”函数,平均查找每个单词对应的单词向量,将其与另一个向量相乘并返回平均相关性。

但是,在大字符串上迭代和应用该函数需要花费大量时间,我想知道可以采取哪些方法来加速以下代码:

#retrieve word vector from words df
def vec(w):
return words.at[w]

#calculates the cosine distance between two vectors
def cosine_dist(a,b):
codi = 1 - spatial.distance.cosine(a, b)
return codi

#calculate the average cosine distance of the whole string and a given word vector
v_search = vec("test")
def Average(v_search, tobe_parsed):
word_total = 0
mean = 0
for word in tobe_parsed.split():
try: #word exists
cd = cosine_dist(vec(word), v_search)
mean += cd
word_total += 1

except: #word does not exists
pass

average = mean / word_total
return(average)
df['average'] = df['text'].apply(lambda x: average(x))

我一直在研究编写代码的替代方法(例如 df.loc -> df.at)、cython 和多线程,但我的时间有限,所以我不想在更少的事情上浪费太多时间有效的方法。

提前致谢

最佳答案

您需要利用矢量化和 numpy 广播。让 pandas 返回单词索引列表,使用它们来索引词汇表数组并创建单词向量矩阵(行数等于单词数),然后使用广播来计算余弦距离并计算其平均值。

关于python - 加速 Python NLP 文本解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49219454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com