2

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

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) 不兼容

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

4

2 回答 2

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>>
于 2019-03-21T18:56:33.113 回答
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>
于 2020-03-18T14:23:04.870 回答