Skip to main content
 首页 » 编程设计

python之变量 tf.Variable 在 TensorFlow Probability 中的梯度为 'None'

2024年09月03日25fff_TT

我在 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 
) 

但是,我在尝试使用 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 
) 

我收到以下值错误:

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 have a gradient defined (i.e. are differentiable).  
Common ops without gradient: K.argmax, K.round, K.eval. 

我进行了一些谷歌搜索,并查看了 TFP 文档,但不知所措,所以我想分享这个问题。我错过了一些明显的东西吗?

提前致谢。

请您参考如下方法:

我想这是因为您使用的是 TensorFlow 2,是吗?它还没有得到完全支持。如果是这样,降级到 1.14 应该可以正常工作。