我是 tensorflow 的新手,我正在尝试建立一个具有密集翻转层的贝叶斯神经网络。我的代码如下所示:
from tensorflow.keras.models import Sequential
import tensorflow_probability as tfp
import tensorflow as tf
def train_BNN(training_data, training_labels, test_data, test_labels, layers, epochs):
bayesian_nn = Sequential()
nbr_samples, dim = training_data.shape
training_labels = training_labels.reshape((nbr_samples, 1))
training_data = tf.convert_to_tensor(training_data, tf.float32)
training_labels = tf.convert_to_tensor(training_labels, tf.float32)
for i in range(0, len(layers)):
bayesian_nn.add(tfp.layers.DenseFlipout(layers[i], activation='relu'))
bayesian_nn.add(tfp.layers.DenseFlipout(1, activation='sigmoid'))
# Define loss function
logits = bayesian_nn(training_data)
neg_log_likelihood = tf.losses.sigmoid_cross_entropy(training_labels, logits=logits)
kl = sum(bayesian_nn.losses)
loss = neg_log_likelihood + kl
# Define optimizer
train_op = tf.train.AdamOptimizer().minimize(loss)
bayesian_nn.compile(train_op, loss=loss, metrics=['accuracy'])
尝试编译网络时出现以下错误:
Traceback (most recent call last):
File "./test_script.py", line 34, in <module>
dataset[0:training,], labels[0:training], dataset[training:,], labels[training:], layers, epochs
File "/home/e/bayesian_nn.py", line 34, in train_BNN
bayesian_nn.compile(train_op, loss=loss, metrics=['accuracy'])
File "/home/e/.pyenv/versions/kmer_profiling/lib/python3.6/site-packages/tensorflow/python/training/checkpointable/base.py", line 474, in _method_wrapper
method(self, *args, **kwargs)
File "/home/e/.pyenv/versions/kmer_profiling/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 405, in compile
loss = loss or {}
File "/home/e/.pyenv/versions/kmer_profiling/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 671, in __bool__
raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. "
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.
我不知道是什么导致了这个错误......请帮助:)