我试图将How to use a MultiVariateNormal distribution in the latest version of Tensorflow中给出的示例推广为二维正态分布,但批次不止一个。当我运行以下命令时:
from tensorflow_probability import distributions as tfd
import tensorflow as tf
tf.compat.v1.enable_eager_execution()
mu = [[1, 2],
[-1,-2]]
cov = [[1, 3./5],
[3./5, 2]]
cov = [cov, cov] # for demonstration purpose, use same cov for both batches
mvn = tfd.MultivariateNormalFullCovariance(
loc=mu,
covariance_matrix=cov)
# generate the pdf
X, Y = tf.meshgrid(tf.range(-3, 3, 0.1), tf.range(-3, 3, 0.1))
idx = tf.concat([tf.reshape(X, [-1, 1]), tf.reshape(Y,[-1,1])], axis =1)
prob = tf.reshape(mvn.prob(idx), tf.shape(X))
出现不兼容的形状错误:
tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [3600,2] vs. [2,2] [Op:Sub] name: MultivariateNormalFullCovariance/log_prob/affine_linear_operator/inverse/sub/
我对文档(https://www.tensorflow.org/api_docs/python/tf/contrib/distributions/MultivariateNormalFullCovariance)的理解是,要计算pdf,需要一个[n_observation,n_dimensions]张量(在本示例中就是这种情况:idx.shape
= {{1} }。我数学错了吗?
答案 0 :(得分:0)
由于60x60不能针对idx
的{{1}}进行广播,因此您需要在倒数第二个mvn.batch_shape
张量中添加批处理轴。
(2,)
输出:
# TF/TFP Imports
!pip install --quiet tfp-nightly tf-nightly
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
import tensorflow_probability as tfp
tfd = tfp.distributions
mu = [[1, 2],
[-1, -2]]
cov = [[1, 3./5],
[3./5, 2]]
cov = [cov, cov] # for demonstration purpose, use same cov for both batches
mvn = tfd.MultivariateNormalFullCovariance(
loc=mu, covariance_matrix=cov)
print(mvn.batch_shape, mvn.event_shape)
# generate the pdf
X, Y = tf.meshgrid(tf.range(-3, 3, 0.1), tf.range(-3, 3, 0.1))
print(X.shape)
idx = tf.stack([X, Y], axis=-1)[..., tf.newaxis, :]
print(idx.shape)
probs = mvn.prob(idx)
print(probs.shape)