根据 Python 的主题从文本中提取关键短语

Extracting Key-Phrases from text based on the Topic with Python

我有一个包含 3 列的大型数据集,列是文本、短语和主题。 我想找到一种方法来根据主题提取关键短语(短语列)。 Key-Phrase 可以是文本值的一部分,也可以是整个文本值。

import pandas as pd


text = ["great game with a lot of amazing goals from both teams",
        "goalkeepers from both teams made misteke",
        "he won all four grand slam championchips",
        "the best player from three-point line",
        "Novak Djokovic is the best player of all time",
        "amazing slam dunks from the best players",
        "he deserved yellow-card for this foul",
        "free throw points"]

phrase = ["goals", "goalkeepers", "grand slam championchips", "three-point line", "Novak Djokovic", "slam dunks", "yellow-card", "free throw points"]

topic = ["football", "football", "tennis", "basketball", "tennis", "basketball", "football", "basketball"]

df = pd.DataFrame({"text":text,
                   "phrase":phrase,
                   "topic":topic})

print(df.text)
print(df.phrase)

我很难找到执行此类操作的路径,因为我的数据集中有超过 50000 行和大约 48000 个短语的唯一值,以及 3 个不同的主题。

我想构建一个包含所有足球、篮球和网球主题的数据集并不是最好的解决方案。所以我正在考虑为此制作某种 ML 模型,但这又意味着我将有 2 个特征(文本和主题)和一个结果(短语),但我将有超过 48000 个不同的 类在我的结果中,这不是一个好方法。

我正在考虑使用文本列作为特征并应用分类模型来寻找情绪。之后我可以使用预测情绪来提取关键特征,但我不知道如何提取它们。

还有一个问题是,当我尝试使用 CountVectorizerTfidfTransformer 与随机森林、决策树或任何其他分类算法对情绪进行分类时,我的准确率只有 66%,而且如果我使用 TextBlob 进行情绪分析,准确率为 66%。

有什么帮助吗?

您似乎希望按主题对短文本进行分组。您将不得不以一种或另一种方式标记数据。您可以考虑多种编码:

词袋,通过计算词汇表中每个词的出现频率来分类。

TF-IDF:做上面的事情,但使出现在更多条目中的词不那么重要

n_grams / bigrams / trigrams 本质上是词袋方法,但也保持每个词周围的一些上下文。所以你会有每个单词的编码,但你也会有 "great_game"、"game_with" 和 "great_game_with" 等的标记

Orthogonal Sparse Bigrams (OSB)s 还可以创建将单词分开的特征,例如 "great__with"

这些选项中的任何一个都可能是您的数据集的理想选择(最后两个可能是您的最佳选择)。如果这些选项中的 none 个有效,您还可以尝试其他几个选项:


首先你可以使用词嵌入。这些是每个词的向量表示,与单热编码不同,它们本质上包含词义。您可以将一个句子中的单词加在一起,得到一个新向量,其中包含该句子的大致含义,然后可以对其进行解码。

您还可以将词嵌入与双向 LSTM 一起使用。这是计算量最大的选项,但如果您的其他选项不起作用,这可能是一个不错的选择。 biLSTM 试图通过查看单词周围的上下文来解释句子,以尝试理解该单词在该上下文中的含义。

希望对您有所帮助

我想你要找的东西在 NLP 中叫做 "Topic modeling"。 您应该尝试使用 LDA 进行主题建模。这是最简单的应用方法之一。 也正如@Mike 提到的,将单词转换为向量有很多方法。您应该首先尝试简单的方法,例如计数向量化器,然后逐渐转向诸如 word-2-vect 或 glove 之类的方法。

我附上了一些将 LDA 应用于语料库的链接。 1. https://towardsdatascience.com/nlp-extracting-the-main-topics-from-your-dataset-using-lda-in-minutes-21486f5aa925 2. https://www.machinelearningplus.com/nlp/topic-modeling-visualization-how-to-present-results-lda-models/

看起来这里使用 Latent Dirichlet allocation model, which is an example of what are known as topic models.

是个不错的方法

A LDA 是一个无监督模型,它在一组观察中找到相似的组,然后您可以使用它为每个观察分配一个 topic。在这里,我将介绍通过使用 text 列中的句子训练模型来解决此问题的可能方法。尽管在这种情况下 phrases 具有足够的代表性并包含模型捕获的必要信息,但它们也可能是训练模型的良好(可能更好)候选者,尽管您最好通过以下方式进行判断你自己。

在训练模型之前,您需要应用一些预处理步骤,包括标记句子、删除停用词、词形还原和词干提取。为此,您可以使用 nltk:

from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import lda
from sklearn.feature_extraction.text import CountVectorizer

ignore = set(stopwords.words('english'))
stemmer = WordNetLemmatizer()
text = []
for sentence in df.text:
    words = word_tokenize(sentence)
    stemmed = []
    for word in words:
        if word not in ignore:
            stemmed.append(stemmer.lemmatize(word))
    text.append(' '.join(stemmed))

现在我们有更合适的语料库来训练模型:

print(text)

['great game lot amazing goal team',
 'goalkeeper team made misteke',
 'four grand slam championchips',
 'best player three-point line',
 'Novak Djokovic best player time',
 'amazing slam dunk best player',
 'deserved yellow-card foul',
 'free throw point']

然后我们可以通过 CountVectorizer 将文本转换为标记计数矩阵,这是 LDA 期望的输入:

vec = CountVectorizer(analyzer='word', ngram_range=(1,1))
X = vec.fit_transform(text)

请注意,您可以使用 ngram 参数来指定要考虑训练模型的 n-gram 范围。例如,通过设置 ngram_range=(1,2),您最终会得到包含所有单个单词以及每个句子中的 2-grams 的特征,这是一个用 ngram_range=(1,2) 训练 CountVectorizer 的示例:

vec.get_feature_names()
['amazing',
 'amazing goal',
 'amazing slam',
 'best',
 'best player',
 ....

使用 n-grams 的优点是您还可以找到 Key-Phrases 而不仅仅是单个单词。

然后我们可以用你想要的任意数量的主题来训练LDA,在这种情况下我只会选择3个主题(注意这与topics 列),您可以将其视为您提到的 Key-Phrases - 或 words 在这种情况下。这里我将使用 lda, though there are several options such as gensim。 每个主题都会关联一组来自其训练词汇的单词,每个单词都有一个 分数 来衡量单词在主题中的相关性。

model = lda.LDA(n_topics=3, random_state=1)
model.fit(X)

通过topic_word_,我们现在可以获得与每个主题相关的分数。我们可以使用 argsort 对分数向量进行排序,并用它来索引特征名称向量,我们可以通过 vec.get_feature_names:

获得
topic_word = model.topic_word_

vocab = vec.get_feature_names()
n_top_words = 3

for i, topic_dist in enumerate(topic_word):
    topic_words = np.array(vocab)[np.argsort(topic_dist)][:-(n_top_words+1):-1]
    print('Topic {}: {}'.format(i, ' '.join(topic_words)))

Topic 0: best player point
Topic 1: amazing team slam
Topic 2: yellow novak card

在这种情况下,打印的结果并不能真正代表什么,因为模型已经用问题中的样本进行了训练,但是您应该看到更清晰和有意义的主题通过使用整个语料库进行训练。

另请注意,对于此示例,我使用了整个词汇表来训练模型。但是,在您的情况下,似乎更有意义的是根据您已有的不同 topics 将文本列分成组,然后 在每个组上训练一个单独的模型 .但希望这能让您对如何进行有一个好主意。