首页 > 解决方案 > Tensorflow 混合两种多元分布

问题描述

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

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

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

标签: pythontensorflowtensorflow-probability

解决方案


试试这是否能解决您的问题

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>>

推荐阅读