TopicModel:如何通过主题模型"topic"查询文档?
TopicModel: How to query documents by topic model "topic"?
下面我创建了一个完整的可重现示例来计算给定 DataFrame 的主题模型。
import numpy as np
import pandas as pd
data = pd.DataFrame({'Body': ['Here goes one example sentence that is generic',
'My car drives really fast and I have no brakes',
'Your car is slow and needs no brakes',
'Your and my vehicle are both not as fast as the airplane']})
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(lowercase = True, analyzer = 'word')
data_vectorized = vectorizer.fit_transform(data.Body)
lda_model = LatentDirichletAllocation(n_components=4,
learning_method='online',
random_state=0,
verbose=1)
lda_topic_matrix = lda_model.fit_transform(data_vectorized)
问题:如何按主题过滤文档?如果是这样,文档可以有多个主题标签,还是需要一个阈值?
最后,我喜欢用“1”标记每个文档,这取决于它是否具有高负载的主题 2 和主题 3,否则为“0”。
lda_topic_matrix
包含文档属于特定 topic/tag 的概率分布。在人类中,这意味着每一行总和为 1,而每个索引处的值是该文档属于特定主题的概率。因此,每个文档确实具有所有主题标签,但程度不同。如果您有 4 个主题,则所有标签均等的文档将在 lda_topic_matrix
中有一个对应的行,类似于
[0.25, 0.25, 0.25, 0.25]
。并且只有一个主题(“0”)的文档行将变成 [0.97, 0.01, 0.01, 0.01]
并且具有两个主题(“1”和“2”)的文档将有一个分布 [0.01, 0.54, 0.44, 0.01]
所以最简单的做法就是select概率最高的题目,看是2
还是3
:
main_topic_of_document = np.argmax(lda_topic_matrix, axis=1)
tagged = ((main_topic_of_document==2) | (main_topic_of_document==3)).astype(np.int64)
This article 很好地解释了 LDA 的内部机制。
下面我创建了一个完整的可重现示例来计算给定 DataFrame 的主题模型。
import numpy as np
import pandas as pd
data = pd.DataFrame({'Body': ['Here goes one example sentence that is generic',
'My car drives really fast and I have no brakes',
'Your car is slow and needs no brakes',
'Your and my vehicle are both not as fast as the airplane']})
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(lowercase = True, analyzer = 'word')
data_vectorized = vectorizer.fit_transform(data.Body)
lda_model = LatentDirichletAllocation(n_components=4,
learning_method='online',
random_state=0,
verbose=1)
lda_topic_matrix = lda_model.fit_transform(data_vectorized)
问题:如何按主题过滤文档?如果是这样,文档可以有多个主题标签,还是需要一个阈值?
最后,我喜欢用“1”标记每个文档,这取决于它是否具有高负载的主题 2 和主题 3,否则为“0”。
lda_topic_matrix
包含文档属于特定 topic/tag 的概率分布。在人类中,这意味着每一行总和为 1,而每个索引处的值是该文档属于特定主题的概率。因此,每个文档确实具有所有主题标签,但程度不同。如果您有 4 个主题,则所有标签均等的文档将在 lda_topic_matrix
中有一个对应的行,类似于
[0.25, 0.25, 0.25, 0.25]
。并且只有一个主题(“0”)的文档行将变成 [0.97, 0.01, 0.01, 0.01]
并且具有两个主题(“1”和“2”)的文档将有一个分布 [0.01, 0.54, 0.44, 0.01]
所以最简单的做法就是select概率最高的题目,看是2
还是3
:
main_topic_of_document = np.argmax(lda_topic_matrix, axis=1)
tagged = ((main_topic_of_document==2) | (main_topic_of_document==3)).astype(np.int64)
This article 很好地解释了 LDA 的内部机制。