我使用 BERTopic 在 Google Colab 上创建的主题模型绘制了 术语分数下降。功能很棒。工作整洁!但我需要添加一个图例。
topic_model.visualize_term_rank()
函数中未指定该参数。只能调整图形标题、宽度、高度、对数变换和要绘制的主题。
术语分数下降函数输出一个绘图,并且基于 tmtoolkit。所以我尝试在那里调整它。但我无法在colab中加载tmtoolkit。尝试通过
import tmtoolkit
和from tmtoolkit import topicmod
将参考中的内容修补在一起。我发现另一个使用 tmtoolkit 的 colab 文件,但它给了我同样的错误。 Colab 找不到 tmtoolkit。所以不是我的文件有问题,但似乎是一个普遍问题?
另一个解决方案是更新绘图。但如何呢?在import plotly.graph_objects as go
import plotly.express as px
labels = topic_model.topic_labels_
fig = model.visualize_term_rank(title = 'Topic Coherence', custom_labels = True)
fig.update_legends(patch = labels)
fig
这会引发以下错误。
TypeError: object of type 'int' has no len()
这是什么意思?对我来说,无法计算整数变量的长度似乎不合逻辑。当我省略行
fig.update_legends(patch = labels)
时,它会生成图形,但没有我需要的图例。
fig['data']
包含散点轨迹列表,每个主题一个。检查源代码还显示,每个跟踪都是使用空的
name
创建的,并且主题标签设置为
hovertext
,因此您可以执行以下操作:
fig = model.visualize_term_rank(title = 'Topic Coherence', custom_labels = True)
for trace in fig['data']:
topic_label = trace['hovertext']
# The trace name appears as the legend item for that trace.
trace['name'] = topic_label
# Whether or not the item corresponding to this trace is shown in the legend.
trace['showlegend'] = True
# You could also override the color for the given topic, eg. something like
# trace['line']['color'] = _topic_color(topic_label)
# And the most important obviously
fig.update_layout(showlegend=True)