我收到以下异常
TypeError: An op outside of the function building code is being passed
a "Graph" tensor. It is possible to have Graph tensors
leak out of the function building context by including a
tf.init_scope in your function building code.
For example, the following function will fail:
@tf.function
def has_init_scope():
my_constant = tf.constant(1.)
with tf.init_scope():
added = my_constant * 2
The graph tensor has name: conv2d_flipout/divergence_kernel:0
Run Code Online (Sandbox Code Playgroud)
这也引发了以下异常
tensorflow.python.eager.core._SymbolicException: Inputs to eager execution function cannot be Keras symbolic tensors, but found [<tf.Tensor …Run Code Online (Sandbox Code Playgroud) python tensorflow python-3.7 tensorflow-probability tensorflow2.0
我正在运行使用Tensorflow概率实现的贝叶斯神经网络的示例代码.我的问题是关于用于变分推理的-ELBO损失的实现.-ELBO等于两个项的总和,即在代码中实现的'neg_log_likelihood'和'kl'.我很难理解'kl'术语的实现.
以下是模型的定义方式:
with tf.name_scope("bayesian_neural_net", values=[images]):
neural_net = tf.keras.Sequential()
for units in FLAGS.layer_sizes:
layer = tfp.layers.DenseFlipout(
units,
activation=FLAGS.activation)
neural_net.add(layer)
neural_net.add(tfp.layers.DenseFlipout(10))
logits = neural_net(images)
labels_distribution = tfd.Categorical(logits=logits)
Run Code Online (Sandbox Code Playgroud)
以下是"kl"术语的定义:
kl = sum(neural_net.losses) / mnist_data.train.num_examples
Run Code Online (Sandbox Code Playgroud)
我不确定'neural_net.losses'在这里返回什么,因为没有为'neural_net'定义的损失函数.显然,'neural_net.losses'会返回一些值,但我不知道返回值的含义是什么.对此有何评论?
我的猜测是L2规范,但我不确定.如果是这种情况,我们仍然遗漏了一些东西.根据VAE论文附录B,作者在先验标准正常时得出KL术语.它原来是非常接近的变参数,除了有额外的日志方差术语和常数项的L2规范.对此有何评论?
我在 TFP 中构建基本 BNN 时遇到问题。一般来说,我是 TFP 和 BNN 的新手,所以如果我错过了一些简单的东西,我深表歉意。
我可以通过执行以下操作在 Tensorflow 中训练一个基本的神经网络:
model = keras.Sequential([
keras.layers.Dense(units=100, activation='relu'),
keras.layers.Dense(units=50, activation='relu'),
keras.layers.Dense(units=5, activation='softmax')
])
model.compile(optimizer=optimizer,
loss=tf.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(
training_data.repeat(),
epochs=100,
steps_per_epoch=(X_train.shape[0]//1024),
validation_data=test_data.repeat(),
validation_steps=2
)
Run Code Online (Sandbox Code Playgroud)
但是,我在尝试使用 tfp DenseFlipout 层实现类似的架构时遇到了麻烦:
model = keras.Sequential([
tfp.layers.DenseFlipout(units=100, activation='relu'),
tfp.layers.DenseFlipout(units=10, activation='relu'),
tfp.layers.DenseFlipout(units=5, activation='softmax')
])
model.compile(optimizer=optimizer,
loss=tf.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(
training_data.repeat(),
epochs=100,
steps_per_epoch=(X_train.shape[0]//1024),
validation_data=test_data.repeat(),
validation_steps=2
)
Run Code Online (Sandbox Code Playgroud)
我收到以下值错误:
ValueError:
Variable <tf.Variable 'sequential_11/dense_flipout_15/kernel_posterior_loc:0'
shape=(175, 100) dtype=float32> has `None` for gradient.
Please make sure that all of your ops …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用TensorFlow概率的Nelder-Mead优化器实现高斯拟合:tfp.optimizer.nelder_mead_minimize()。它不会收敛,同时scipy.optimizer.minimize()可以在不到1秒的计算时间内提供良好的结果。我可能做错了什么,但我不知道是什么?有人可以帮我吗?
我在用 :
python 3.7.3
tensorflow-probability 0.8
tensorflow 2.0
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
import matplotlib as plt
# Define the gaussian model : y = 1/(sigma * sqrt(2 pi)) * exp(- (x-mu)²/(2*sigma²))
pi = np.pi
def model(x, theta):
y = 1/(theta[1]*tf.sqrt(2*pi)) * tf.exp(-(x-theta[0])**2 /(2*theta[1]**2))
return y
# Define the loss (least mean square)
def loss_function(theta, y, x, callback=False, n_iterations=1):
global n_epochs_cb
loss = tf.losses.mean_squared_error(y, model(x, theta))
if …Run Code Online (Sandbox Code Playgroud) 我需要使用 Tensorflow 和 Tensorflow_Probability。通过以下命令安装后:conda install tensorflow-probabilityor pip install --upgrade tensorflow-probability,我在笔记本中运行它:
import tensorflow_probability as tfp
Run Code Online (Sandbox Code Playgroud)
但它返回此错误:
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-8-41494c8c96ff> in <module>
----> 1 import tensorflow_probability as tfp
ModuleNotFoundError: No module named 'tensorflow_probability'.
Run Code Online (Sandbox Code Playgroud)
结果
pip list
Run Code Online (Sandbox Code Playgroud)
如下(相关部分):
tblib 1.3.2
tensorboard 1.13.1
tensorflow 1.13.1
tensorflow-estimator 1.13.0
tensorflow-probability 0.7.0
termcolor 1.1.0
terminado 0.8.1
testpath 0.4.2
tfp-nightly 0.8.0.dev20190708
Theano 1.0.4
toolz 0.9.0
Run Code Online (Sandbox Code Playgroud)
谁能帮我解决这个问题(我使用的是 Win 10)?
我正在尝试使用 TensorFlow 和 TensorFlow Probability 实现期望最大化算法。它运行得很好,直到我尝试实现缺失数据(数据可以在某些随机维度中包含 NaN 值)。
问题是,由于缺少数据,我无法再将所有操作作为向量运算进行,我必须使用索引和 for 循环,如下所示:
# Here we iterate through all the data samples
for i in range(n):
# x_i is the sample i
x_i = tf.expand_dims(x[:, i], 1)
gamma.append(estimate_gamma(x_i, pi, norm, ber))
est_x_n_i = []
est_xx_n_i = []
est_x_b_i = []
for j in range(k):
mu_k = norm.mean()[j, :]
sigma_k = norm.covariance()[j, :, :]
rho_k = ber.mean()[j, :]
est_x_n_i.append(estimate_x_norm(x_i[:d, :], mu_k, sigma_k))
est_xx_n_i.append(estimate_xx_norm(x_i[:d, :], mu_k, sigma_k))
est_x_b_i.append(estimate_x_ber(x_i[d:, :], rho_k))
est_x_n.append(tf.convert_to_tensor(est_x_n_i))
est_xx_n.append(tf.convert_to_tensor(est_xx_n_i))
est_x_b.append(tf.convert_to_tensor(est_x_b_i))
Run Code Online (Sandbox Code Playgroud)
我发现这些操作效率并不高。虽然第一个样本每个样本花费的时间大约不到 …
我在 Keras 序列中使用 Tensorflow 概率层。但是,将模型保存为 json 然后加载它会引发异常。我用来custom_objects加载自定义图层。这是重现错误的简约代码。
import tensorflow_probability as tfp
tfk = tf.keras
tfkl = tf.keras.layers
tfpl = tfp.layers
original_dim = 20
latent_dim = 2
model = tfk.Sequential([
tfkl.InputLayer(input_shape=original_dim),
tfkl.Dense(10, activation=tf.nn.leaky_relu),
tfkl.Dense(tfpl.MultivariateNormalTriL.params_size(latent_dim), activation=None),
tfpl.MultivariateNormalTriL(latent_dim)
])
model_json = model.to_json()
with open("model.json", "w") as json_file:
json_file.write(model_json)
loaded_model = tfk.models.model_from_json(
open('model.json').read(),
custom_objects={
'leaky_relu': tf.nn.leaky_relu,
'MultivariateNormalTriL': tfpl.MultivariateNormalTriL
}
)
Run Code Online (Sandbox Code Playgroud)
我得到以下异常:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-26-bbbeffd9e4be> in <module>
3 custom_objects={
4 'leaky_relu': tf.nn.leaky_relu,
----> 5 'MultivariateNormalTriL': tfpl.MultivariateNormalTriL
6 } …Run Code Online (Sandbox Code Playgroud) 我想知道如何训练多元贝叶斯结构时间序列 (BSTS) 模型,该模型使用 Tensorflow Probability 自动对数百个输入时间序列执行特征选择。
TF -Probability BSTS 博客文章展示了如何在单个输入特征中包含季节性影响:
...
temp_effect = sts.LinearRegression(
design_matrix=tf.reshape(temp - np.mean(temp),
(-1, 1)), name='temp_effect')
...
model = sts.Sum([..., temp_effect,...],
observed_time_series=observed_time_series)
Run Code Online (Sandbox Code Playgroud)
但是当有多个输入时间序列时怎么办?
通读文档后,似乎对于很多输入,SparseLinearRegression 会更好,这是有道理的,但我应该如何调整我的代码?
LinearRegression 和 SparseLinearRegression 方法的文档建议使用design_matrix=tf.stack([series1, series2], axis=-1), weights_prior_scale=0.1),但由于这与 TF-Probability 自己的博客文章使用它的方式不同,我不确定这是否是最好的方法。
我应该在design_matrix单个 SparseLinearRegression 中添加所有(数百个)输入特征,还是应该为每个特征添加单独的 LinearRegression,然后将sts.Sum()它们全部组合到模型中?虽然我想要可视化每个特征的影响的功能,但我最感兴趣的是让模型自动执行特征选择并为我可以访问的其余特征生成权重。
python time-series linear-regression tensorflow tensorflow-probability
来自 Pytorch-Pyro 的网站:
我们很高兴地宣布发布 NumPyro,这是一个 NumPy 支持的 Pyro,使用 JAX 进行自动微分和 JIT 编译,HMC 和 NUTS 的速度提高了 100 倍以上!
我的问题:
额外的:
pytorch pyro.ai probabilistic-programming tensorflow-probability numpyro
我有一个简单的模型,当前输出一个数值,我已对其进行了调整,改为使用 TFP(平均值 + 标准差)输出分布,这样我就可以了解模型对预测的置信度。
model = tf.keras.Sequential([
tf.keras.layers.Dense(10, input_shape=[len(df.columns),], activation='relu'), # Should only be one input, so [1,]
tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(2 * len(target.columns)), # there are 2 outputs, so we want a mean + standard deviation for EACH of the outputs
tfp.layers.DistributionLambda(
lambda t: tfd.Normal(loc=t[..., :1],
scale=1e-3 + tf.math.softplus(0.05 * t[...,1:]))
)
])
Run Code Online (Sandbox Code Playgroud)
当前 2 个 Dense 输出指向输出分布的平均值 + 标准差。
在我的真实数据集中,我尝试根据输入数据预测两个数值。如何使模型输出两个分布?我认为最终的密集层需要 4 个节点(2 个均值和 2 个标准差),但我不确定如何使其与分布 Lambda 一起正常工作。我希望有一个模型可以预测这一点,而不必为每个目标输出训练一个模型。
编辑:我创建了这个合作,让人们更容易地看到我的意思。我稍微简化了这个例子,希望它能更清楚地说明我想要完成的事情:
https://colab.research.google.com/drive/1Wlucked4V0z-Bm_ql8XJnOJL0Gm4EwnE?usp=sharing
我无法理解 Tensorflow 概率中的双射器。如何使用它们。
standard_gumbel = tfd.TransformedDistribution(
distribution=tfd.Exponential(rate=1.),
bijector=tfb.Chain([
tfb.Affine(
scale_identity_multiplier=-1.,
event_ndims=0),
tfb.Invert(tfb.Exp()),
]))
Run Code Online (Sandbox Code Playgroud) 我想在 TensorFlow 中生成随机整数,但我不知道应该使用哪个命令。特别是,我想从一个统一的随机变量中生成,该变量的值为 {1, 2, 3, 4}。我试图查看其中包含的发行版,tensorflow_probability但没有找到。
在此先感谢您的帮助。
tensorflow ×9
python ×7
keras ×3
numpyro ×1
pyro.ai ×1
python-3.7 ×1
pytorch ×1
random ×1
time-series ×1