【问题标题】:How to print out the prediction probabilities in Tensorflow如何在 Tensorflow 中打印出预测概率
【发布时间】:2018-11-21 16:11:14
【问题描述】:

我是新来的 tf.我已经使用 tensorflow 训练了一个编码器 - 解码器。该程序将一个单词作为输入并打印出它的音素。

例如:Hello World -> ['h', 'E', 'l', '"', '@U', '', 'w', '"', '3`', 'r ', '5', 'd']

我想访问每个所选音素的预测概率。

在预测部分,我使用的代码如下:

def predict(words, sess):

    if len(words) > hp.batch_size:
        after = predict(words[hp.batch_size:], sess)
        words = words[:hp.batch_size]

    else:
        after = []
    x = np.zeros((len(words), hp.maxlen), np.int32)  # 0: <PAD>
    for i, w in enumerate(words):
        for j, g in enumerate((w + "E")[:hp.maxlen]):
            x[i][j] = g2idx.get(g, 2)         


    preds = np.zeros((len(x), hp.maxlen), np.int32)
    for j in range(hp.maxlen):

        xpreds = sess.run(graph.preds, {graph.x: x, graph.y: preds})
        preds[:, j] = xpreds[:, j]

提前谢谢你!

我的主要问题是这些概率“隐藏”在哪里以及如何访问它们。例如,单词“Hello”中的字母“o”与音素“@U”映射。我想知道“@U”被选为理想音素的概率有多大。

【问题讨论】:

  • 你能正确格式化代码吗?不确定代码块中的所有内容是否都应该在 predict 函数中。你有什么尝试打印出概率?试图确定这是否是一个重复的问题,或者是否还有更多问题
  • 感谢您的回答。实际上,我已经尝试了一些在网上找到的东西。我已经尝试过 np.argmax、tf.argmax、tf.nn.top_k 和其他命令。问题的一部分是即使上面的命令产生了一些东西,也存在访问和读取数据的问题。主要是因为它们是张量
  • 我使用的代码基于:github.com/Kyubyong/g2p 我所做的更改主要是在预处理上,以便使用我自己的数据。但心始终如一。我使用 train.py 来训练我的模型,并使用 g2p.py 进行预测。兴趣点位于 g2p.py 的第 85 行。我必须找到一种方法来利用“ _preds = sess.run(graph.preds, {graph.x: x, graph.y: preds}) ”中的信息,不仅可以进行预测,还可以打印每个预测的概率

标签: python tensorflow


【解决方案1】:

在讨论之后,我想我可以指出应该更改代码的地方。 在 train.py 中,第 104 行:

self.preds = tf.to_int32(tf.argmax(logits, -1))

他们将 preds 变量分配给概率最高的索引。 为了得到softmax预测,你可以修改代码如下:

self.preds = tf.nn.softmax(logits)

我认为应该这样做。

如何查看概率:

preds = np.zeros((len(x), hp.maxlen), np.float32)
for j in range(hp.maxlen):
    xpreds = sess.run(graph.preds, {graph.x: x, graph.y: preds})
    # print shape of output -> batch_size, max_length,number_of_output_options
    print(xpreds.shape)
    # print all predictions of the first output
    print(xpreds[0, 0])
    # print the probabilty of the network prediction
    print(xpreds[0, 0, np.argmax(xpreds[0][0])])
    # preds[:, j] = _preds[:, j]     Need to accumulate the results according to the correct output shape

【讨论】:

  • 感谢您的回答。我按照您的建议更改了代码,现在我正在重新训练我的模型。关于在我使用 g2p.py 脚本时如何访问概率的任何想法,以便在我用作输入的每个数据上找到它们?提前谢谢你
  • 进行此更改后,在运行 xpreds = sess.run(graph.preds, {graph.x: x, graph.y: preds}) 后,xpreds 将包含概率。打印到控制台并检查。
  • 顺便说一句,你不需要重新训练。你可以使用你已经拥有的最新检查点
  • 非常感谢。最后一个问题(我希望是最后一个)。正如您在上面在 train.py 中提出的那样,我将“tf.to_int32”替换为“tf.nn.softmax”。之后我运行 g2p.py 并发生 ValueError:ValueError:无法将输入数组从形状(97)广播到形状(1)。我应该使用其他操作来使我的脚本正确运行吗?提前谢谢你
  • 错误在这里: preds[:, j] = xpreds[:, j] 首先你可以在 session.run 之后执行 print(xpreds.shape) 来查看你现在得到的形状.您还可以 print(xpreds[0]) 查看您现在得到的概率。我会编辑答案
猜你喜欢
  • 2016-02-07
  • 2018-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多