【问题标题】:Speeding up Python NLP text parsing加速 Python NLP 文本解析
【发布时间】:2018-03-11 11:24:49
【问题描述】:

我有一个由大字符串组成的数据集(从大约 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 和多线程,但我的时间有限,所以我不想浪费太多时间在 less有效的方法。

提前致谢

【问题讨论】:

    标签: python string performance parsing


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      非常感谢 vumaasha!这确实是要走的路(速度从〜15分钟增加到〜7秒!:o)

      基本上代码已经改写为:

      def Average(v_search,text):
              wordvec_matrix = words.loc[text.split()]
              return np.sum(cos_cdist(wordvec_matrix,v_search))/wordvec_matrix.shape[0]
      df['average'] = df['text'].apply(lambda x: average(x))
      

      【讨论】:

      • 你也可以使用 np.mean
      • 显然.. :s 谢谢 vumaasha
      猜你喜欢
      • 2022-12-18
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      相关资源
      最近更新 更多