Полунадзорный управляемый LDA - предопределенные темы, отличные от созданных тем - PullRequest
0 голосов
/ 02 марта 2020

Я пытаюсь сделать модель LDA под наблюдением, основанную на этом .

Однако результат, полученный мной из модели LDA, очень отличается от набора тем, которые я предопределил.

Это набор кодов, который я взял по ссылке.

def viz_model(model, modeldict):
    ntopics = model.num_topics
    # top words associated with the resulting topics
    topics = ['Topic {}: {}'.format(t,modeldict[w]) for t in range(ntopics) for w,p in model.get_topic_terms(t, topn=1)]
    terms = [modeldict[w] for w in modeldict.keys()]
    fig,ax=plt.subplots()
    ax.imshow(model.get_topics())  # plot the numpy matrix
    ax.set_xticks(modeldict.keys())  # set up the x-axis
    ax.set_xticklabels(terms, rotation=90)
    ax.set_yticks(np.arange(ntopics))  # set up the y-axis
    ax.set_yticklabels(topics)
    plt.show()

def test_eta(eta, dictionary, ntopics, print_topics=True, print_dist=True):
    np.random.seed(42) # set the random seed for repeatability
    bow = [dictionary.doc2bow(line) for line in corp] # get the bow-format lines with the set dictionary
    with (np.errstate(divide='ignore')):  # ignore divide-by-zero warnings
        model = gensim.models.ldamodel.LdaModel(
            corpus=bow, id2word=dictionary, num_topics=ntopics,
            random_state=42, chunksize=100, eta=eta,
            eval_every=-1, update_every=1,
            passes=150, alpha='auto', per_word_topics=True)
    # visuzlize the model term topics
    viz_model(model, dictionary)
    print('Perplexity: {:.2f}'.format(model.log_perplexity(bow)))
    if print_topics:
        # display the top terms for each topic
        for topic in range(ntopics):
            print('Topic {}: {}'.format(topic, [dictionary[w] for w,p in model.get_topic_terms(topic, topn=3)]))
    if print_dist:
        # display the topic probabilities for each document
        for line,bag in zip(txt,bow):
            doc_topics = ['({}, {:.1%})'.format(topic, prob) for topic,prob in model.get_document_topics(bag)]
            print('{} {}'.format(line, doc_topics))
    return model

def create_eta(priors, etadict, ntopics):
    eta = np.full(shape=(ntopics, len(etadict)), fill_value=1) # create a (ntopics, nterms) matrix and fill with 1
    for word, topic in priors.items(): # for each word in the list of priors
        keyindex = [index for index,term in etadict.items() if term==word] # look up the word in the dictionary
        if (len(keyindex)>0): # if it's in the dictionary
            eta[topic,keyindex[0]] = 1e7  # put a large number in there
    eta = np.divide(eta, eta.sum(axis=0)) # normalize so that the probabilities sum to 1 over all topics
    return eta

У меня есть набор отзывов, которые я просмотрел в Интернете, и набор предопределенных тем.

seed = {
    'delivery':0, 'fast':0, 'arrive':0, 'slow':0,'condition':0, 'day':0,'come':0, 'receive':0, 'prompt':0, 'pack':0, 'wrap':0, 'package':0, 'arrive':0,
    'colour':1, 'color':1, 'shade':1, 'pigment':1,
    'stick':2, 'oil':2, 'lightweight':2, 'gentle':2,'fresh':2, 'sensitive':2, 'sticky':2, 'oily':2, 'skin':2, 'apply':2,'last':2,"lasting":2,
    'manufacture':3,'expiry':3, 'date':3, 'year':3,
    'promotion':4,'deal':4,'sale':4,'free':4,'freebie':4,'sample':4,'worth':4,'price':4, 'discount':4
}

Результат, который я получил из модели, сильно отличается от моего набора тем, которые я определил ранее. ,

Perplexity: -4.08
Topic 0: ['feel', 'use', 'dry', 'apply', 'easy', 'last', 'would', 'smooth', 'try', 'make']
Topic 1: ['good', 'receive', 'try', 'fast', 'buy', 'order', 'love', 'use', 'look', 'first']
Topic 2: ['buy', 'get', 'free', 'deliver', 'worth', 'take', 'come', 'try', 'happy', 'different']
Topic 3: ['fast', 'receive', 'free', 'come', 'thank', 'pack', 'cheap', 'great', 'nice', 'arrive']
Topic 4: ['remove', 'use', 'make', 'micellar', 'garni', 'sensitive', 'gentle', 'try', 'clean', 'feel']

Что я здесь не так делаю и что я могу сделать, чтобы увеличить вероятность появления моих предопределенных ключевых слов в темах, созданных моделью?

...