首页 文章

从轴上的Tensorflow中的张量采样

提问于
浏览
2

我有一个形状 (2,5,2) 的矩阵 L . 沿最后一个轴的值形成概率分布 . 我想采样另一个形状为 (2, 5) 的矩阵 S ,其中每个条目都是以下整数之一: 0, 1 . 例如,

L = [[[0.1, 0.9],[0.2, 0.8],[0.3, 0.7],[0.5, 0.5],[0.6, 0.4]],
     [[0.5, 0.5],[0.9, 0.1],[0.7, 0.3],[0.9, 0.1],[0.1, 0.9]]]

其中一个样本可能是,

S = [[1, 1, 1, 0, 1],
     [1, 1, 1, 0, 1]]

在上面的例子中,分布是二项式的 . 但是,通常, L 的最后一个维度可以是任何正整数,因此分布可以是 multinomial .

需要在Tensorflow计算图中有效地生成样本 . 我知道如何使用函数 apply_along_axisnumpy.random.multinomial 使用numpy .

2 回答

  • 0

    你可以在这里使用tf.multinomial() .

    您首先需要重塑输入张量以塑造 [-1, N] (其中 NL 的最后一个维度):

    # L has shape [2, 5, 2]
    L = tf.constant([[[0.1, 0.9],[0.2, 0.8],[0.3, 0.7],[0.5, 0.5],[0.6, 0.4]],
                     [[0.5, 0.5],[0.9, 0.1],[0.7, 0.3],[0.9, 0.1],[0.1, 0.9]]])
    
    dims = L.get_shape().as_list()
    N = dims[-1]  # here N = 2
    
    logits = tf.reshape(L, [-1, N])  # shape [10, 2]
    

    现在我们可以将函数 tf.multinomial() 应用于 logits

    samples = tf.multinomial(logits, 1)
    # We reshape to match the initial shape minus the last dimension
    res = tf.reshape(samples, dims[:-1])
    
  • 5

    使用tf.multinomial()时要小心 . 函数的输入应该是logits而不是概率分布 . 但是,在您的示例中,最后一个轴是概率分布 .

相关问题