Сценарий Gensim LDA Multicore Python работает слишком медленно - PullRequest
0 голосов
/ 30 января 2019

Я запускаю следующий скрипт на большом наборе данных (около 100 000 элементов).В настоящее время исполнение является недопустимо медленным, вероятно, для его завершения потребуется, по крайней мере, месяц (без преувеличения).Очевидно, я бы хотел, чтобы он работал быстрее.

Я добавил комментарий к выделению, которое, по моему мнению, является узким местом.Я написал свои собственные функции базы данных, которые импортируются.

Любая помощь приветствуется!

# -*- coding: utf-8 -*-
import database
from gensim import corpora, models, similarities, matutils
from gensim.models.ldamulticore import LdaMulticore
import pandas as pd
from sklearn import preprocessing



def getTopFiveSimilarAuthors(author, authors, ldamodel, dictionary):
    vec_bow = dictionary.doc2bow([researcher['full_proposal_text']])
    vec_lda = ldamodel[vec_bow]

    # normalization
    try:
        vec_lda = preprocessing.normalize(vec_lda)
    except:
        pass

    similar_authors = []

    for index, other_author in authors.iterrows():
        if(other_author['id'] != author['id']):
            other_vec_bow = dictionary.doc2bow([other_author['full_proposal_text']])

            other_vec_lda = ldamodel[other_vec_bow]
            # normalization
            try:
                other_vec_lda = preprocessing.normalize(vec_lda)
            except:
                pass

            sim = matutils.cossim(vec_lda, other_vec_lda)
            similar_authors.append({'id': other_author['id'], 'cosim': sim})
    similar_authors = sorted(similar_authors, key=lambda k: k['cosim'], reverse=True)
    return similar_authors[:5]


def get_top_five_similar(author, authors, ldamodel, dictionary):
    top_five_similar_authors = getTopFiveSimilarAuthors(author, authors, ldamodel, dictionary)
    database.insert_top_five_similar_authors(author['id'], top_five_similar_authors, cursor)

connection = database.connect()
authors = []
authors = pd.read_sql("SELECT id, full_text FROM author WHERE full_text IS NOT NULL;", connection)

# create the dictionary
dictionary = corpora.Dictionary([authors["full_text"].tolist()])

# create the corpus/ldamodel
author_text = []

for text in author_text['full_text'].tolist():
    word_list = []
    for word in text:
        word_list.append(word)
        author_text.append(word_list)

corpus = [dictionary.doc2bow(text) for text in author_text]
ldamodel = LdaMulticore(corpus, num_topics=50, id2word = dictionary, workers=30)

#BOTTLENECK: the script hangs after this point. 
authors.apply(lambda x: get_top_five_similar(x, authors, ldamodel, dictionary), axis=1)

1 Ответ

0 голосов
/ 30 января 2019

Я заметил эти проблемы в вашем коде ... но я не уверен, что они являются причиной медленного выполнения .. этот цикл здесь бесполезен, он никогда не запускается:

 for text in author_text['full_text'].tolist():
      word_list = []
      for word in text:
         word_list.append(word)
         author_text.append(word_list)

также тамнет необходимости зацикливать слова текста, достаточно использовать для него функцию разделения, и это будет список слов, обрезая авторов courser ..

попробуйте написать это так: first:

all_authors_text = []
for author in authors:
    all_authors_text.append(author['full_text'].split())

и после этого составляют словарь:

dictionary = corpora.Dictionary(all_authors_text)
...