2016-09-11 60 views
1

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

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的最后一个维度可以是任何正整数,因此分布可以是多项式

样本需要在Tensorflow计算图中有效生成。我知道如何使用numpy使用函数apply_along_axisnumpy.random.multinomial来做到这一点。

回答

3

您可以在这里使用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]) 
0

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