Sagemaker LDA主题模型-如何访问已训练模型的参数?还有一种简单的方法来捕获连贯性

时间:2019-02-28 11:37:28

标签: python lda amazon-sagemaker

我是Sagemaker的新手,并且正在运行一些测试来比较NTM和LDA在AWS上与LDA槌和本机Gensim LDA模型相比的性能。

我想检查Sagemaker上训练有素的模型,并研究诸如单词对每个主题贡献最大的东西。并获得模型一致性的度量。

通过下载输出文件解压缩并解压缩以显示3个文件params,symbol.json和meta.json,我已经能够成功地在Sagemaker上成功获得对NTM的每个主题贡献最大的单词。

但是,当我尝试对LDA执行相同的过程时,未解压缩的输出文件无法解压缩。

与NTM相比,也许我缺少LDA或应该对LDA做一些不同的事情,但是我却找不到任何文档。还有,有人找到一种计算模型一致性的简单方法吗?

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

This SageMaker notebook深入探讨了LDA的科学细节,还演示了如何检查模型工件。具体来说,如何获得Dirichlet先验alpha和主题词分布矩阵beta的估计。您可以在标题为“检查训练好的模型” 的部分中找到说明。为了方便起见,我将在此处复制相关代码:

import tarfile
import mxnet as mx

# extract the tarball
tarflie_fname = FILENAME_PREFIX + 'model.tar.gz' # wherever the tarball is located
with tarfile.open(tarfile_fname) as tar:
    tar.extractall()

# obtain the model file (should be the only file starting with "model_")
model_list = [
    fname
    for fname in os.listdir(FILENAME_PREFIX)
    if fname.startswith('model_')
]
model_fname = model_list[0]

# load the contents of the model file into MXNet arrays
alpha, beta = mx.ndarray.load(model_fname)

那应该为您获取模型数据。请注意,存储在beta行中的主题没有按任何特定顺序显示。

答案 1 :(得分:0)

关于一致性,sagemaker AFAIK中没有默认实现。

您可以像这样实现自己的指标:

from itertools import combinations
from sklearn.metrics.pairwise import cosine_similarity

def calculate_coherence(topic_vectors):
    similarity_sum = 0.0
    num_combinations = 0
    for pair in combinations(topic_vectors, 2):
        similarity = cosine_similarity([pair[0]], [pair[1]])
        similarity_sum = similarity_sum + similarity
        num_combinations = num_combinations + 1
    return float(similarity_sum / num_combinations)

并获得真实模型的一致性,例如:

print(calculate_coherence(beta.asnumpy()))

一些直观的一致性测试,如下所示:

predictions = [[0.0, 0.0, 0.0],
               [0.0, 1.0, 0.0],
               [0.0, 0.0, 1.0],
               [1.0, 0.0, 0.0]]

assert calculate_coherence(predictions) == 0.0, "Expected incoherent"

predictions = [[0.0, 1.0, 1.0],
               [0.0, 1.0, 1.0],
               [0.0, 1.0, 1.0],
               [0.0, 1.0, 1.0]]

assert calculate_coherence(predictions) == 1.0, "Expected coherent"

predictions = [[0.0, 0.0, 1.0],
               [0.0, 0.0, 1.0],
               [1.0, 0.0, 0.0],
               [1.0, 0.0, 0.0],
               [0.0, 1.0, 0.0],
               [0.0, 1.0, 0.0]]
assert calculate_coherence(predictions) == 0.2, "Expected partially coherent"

更多阅读:

相关问题