要为BERTopic添加词项得分下降的图例,可以使用以下代码示例:
import matplotlib.pyplot as plt
import seaborn as sns
from bertopic import BERTopic
def plot_word_scores(topic_model, topic_id):
# 获取特定主题的词项得分
word_scores = topic_model.get_topic(topic_id)[1]
# 提取词项和得分
words = [word for word, _ in word_scores]
scores = [score for _, score in word_scores]
# 创建绘图
plt.figure(figsize=(10, 6))
sns.barplot(x=scores, y=words, color='blue')
plt.xlabel("Word Score")
plt.ylabel("Word")
plt.title(f"Word Scores for Topic {topic_id}")
plt.show()
# 创建BERTopic模型
topic_model = BERTopic()
topics, _ = topic_model.fit_transform(documents)
# 绘制特定主题的词项得分下降图例
topic_id = 0 # 要绘制图例的主题ID
plot_word_scores(topic_model, topic_id)
上述代码首先导入了需要的库,然后定义了一个plot_word_scores
函数,该函数接受一个BERTopic模型和一个主题ID作为输入,并绘制特定主题的词项得分下降图例。
在函数内部,我们首先使用get_topic
方法获取特定主题的词项得分。然后,我们将词项和得分分别提取到两个列表中。接下来,我们使用seaborn
库的barplot
函数创建条形图,其中词项在y轴上,得分在x轴上。最后,我们添加标签和标题,并使用plt.show()
显示图例。
最后,我们通过创建BERTopic模型并使用fit_transform
方法对文档进行拟合,然后调用plot_word_scores
函数来绘制特定主题的词项得分下降图例。