如何将多个参数从Tensorflow概率传递到DistributionLambda层?

fdx2calv  于 2023-03-13  发布在  其他
关注(0)|答案(2)|浏览(92)

我正在使用Keras和Tensorflow概率构建一个模型,该模型应输出Gamma函数的参数(alpha和beta),而不是单个参数,如下例所示(t传递给Normal分布函数)。

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

# Build model.
model = tf.keras.Sequential([
  tf.keras.layers.Dense(1),
  tfp.layers.DistributionLambda(lambda t: tfd.Normal(loc=t, scale=1)),
])

# Do inference.
model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.05), loss=negloglik)
model.fit(x, y, epochs=500, verbose=False)

# Make predictions.
yhat = model(x_tst)

相反,我希望从两个Dense层输出alphabeta,然后将这些参数传递给Gamma分布函数。

h4cxqtbf

h4cxqtbf1#

像这样?

import tensorflow as tf
tf.enable_eager_execution()

print(tf.__version__) # 1.14.1-dev20190503

import tensorflow_probability as tfp
tfd = tfp.distributions

X = np.random.rand(4, 1).astype(np.float32)

d0 = tf.keras.layers.Dense(2)(X)
s0, s1 = tf.split(d0, 2)
dist = tfp.layers.DistributionLambda(lambda t: tfd.Gamma(t[0], t[1]))(s0, s1)

dist.sample() 
# <tf.Tensor: id=10580, shape=(2,), dtype=float32, numpy=array([1.1754944e-38, 1.3052921e-01], dtype=float32)>
vfhzx4xs

vfhzx4xs2#

d0 = tf.keras.layers.Dense(2)(X)
dist = tfp.layers.DistributionLambda(lambda t: tfd.Gamma(t[:, 0], t[:, 1]))(d0)

相关问题