通过matplotlib生成困惑度和一致性图时,出现以下的乱码情况

将代码进行以下修改:

from matplotlib.font_manager import FontProperties
# 绘制困惑度曲线
x = list(range(1, n_max_topics+1))
font_path = "/home/jovyan/work/font/SimHei.ttf"  # 替换为实际路径
font = FontProperties(fname=font_path)
plt.rcParams['font.sans-serif'] = ['SimHei'] 
plt.figure(figsize=(12, 5))

plt.subplot(1, 2, 1)
plt.plot(x, plexs, marker='o')
plt.title("困惑度随主题数量的变化趋势", fontproperties=font)
plt.xlabel("主题数", fontproperties=font)
plt.ylabel("困惑度(越低越好)", fontproperties=font)

# 绘制Coherence曲线
plt.subplot(1, 2, 2)
plt.plot(x, coherence_values, marker='o', color='orange')
plt.title("主题一致性随主题数的变化", fontproperties=font)
plt.xlabel("主题数", fontproperties=font)
plt.ylabel("一致性(越高越好)", fontproperties=font)
# plt.xticks(fontproperties=font)  # X轴刻度
# plt.yticks(fontproperties=font)  # Y轴刻度
plt.tight_layout()
plt.show()

# 找到最佳主题数
best_index = np.argmax(coherence_values)
best_topic_num = x[best_index]
print(f"最佳主题数: {best_topic_num} (Coherence Score: {coherence_values[best_index]:.4f})")

# 使用最佳主题数重新训练模型
best_lda = LatentDirichletAllocation(
    n_components=best_topic_num, 
    max_iter=300,
    learning_method='batch',
    learning_decay=0.7,
    random_state=42
)
best_lda.fit(tf_train)

评论交流

文章目录