Tensorflow混合两个多元分布

时间:2019-03-21 16:46:49

标签: python tensorflow tensorflow-probability

我想在张量流中混合两个多元分布。例如:

import tensorflow_probability as tfp
import tensorflow as tf
import numpy as np
tfd = tfp.distributions

#mean,var,pi have the same shape(3,4).
mean = tf.convert_to_tensor(np.arange(12.0).reshape(3,4))
var = mean
dist = tfd.Normal(loc=mean,scale=var)
pi = tf.ones_like(mean)
mix = tfd.Mixture(cat = tfd.Categorical(probs=[pi,1-pi]),components=[dist,dist])

但是,出现以下错误:

  

ValueError:尺寸2和尺寸3不兼容

     

ValueError:形状(2、3)和(3、4)不兼容

我可以在张量流中混合两个多元分布吗?

2 个答案:

答案 0 :(得分:1)

尝试一下是否可以解决您的问题

import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions 

#mean,var,pi have the same shape(3,4).
mean = tf.convert_to_tensor(np.arange(12.0).reshape(3,4))
var = mean
dist = tfd.Normal(loc=-1., scale=0.1)

pi = tf.transpose(tf.ones_like(mean))

mix = tfd.Mixture(cat = tfd.Categorical(probs=[pi/3,
                                               pi/3,
                                               pi/3]), 
                  components=[tfd.Normal(loc=mean,scale=var), 
                              tfd.Normal(loc=mean,scale=var), 
                              tfd.Normal(loc=mean,scale=var)]
                 )

mix.event_shape_tensor

输出

<bound method Distribution.event_shape_tensor of <tfp.distributions.Mixture 'Mixture_11/' batch_shape=(3, 4) event_shape=() dtype=float64>>

答案 1 :(得分:0)

诀窍在于,类别数量必须是概率中的最后一个维度,此代码对我有用:

在:

mix = tfd.Mixture(cat = tfd.Categorical(probs=tf.stack([pi,1-pi],axis=-1)),components=[dist,dist])
mix

出局:

<tfp.distributions.Mixture 'Mixture' batch_shape=[3, 4] event_shape=[] dtype=float64>