Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
自定义丢失函数:不允许将'tf.Tensor'用作Python'bool'_Python_Tensorflow - Fatal编程技术网

自定义丢失函数:不允许将'tf.Tensor'用作Python'bool'

自定义丢失函数:不允许将'tf.Tensor'用作Python'bool',python,tensorflow,Python,Tensorflow,在实现自定义损失函数时,我遇到以下错误: 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

在实现自定义损失函数时,我遇到以下错误:

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.
我的自定义损失函数如下所示:

""" now combine the layers """
combined = tf.keras.layers.concatenate([modelRNN.output, modelCNN.output])

final_dense = tf.keras.layers.Dense(10, activation='relu')(combined) #ff kijken of dit slim is
final_dense = tf.keras.layers.Dense(1, activation='sigmoid')(final_dense)

final_model = tf.keras.Model(inputs=[modelCNN.input, modelRNN.input], outputs=final_dense)

targets = np.asarray(match_train).astype('float32').reshape((-1,1))
targets = tf.convert_to_tensor(targets, np.float32)
logits = final_dense
pos_weight = (45000 - 4539) / 4539


custom_loss = tf.nn.weighted_cross_entropy_with_logits(
    targets,
    logits,
    pos_weight,
    )


final_model.compile(optimizer='adam',
                    loss=custom_loss,
                    metrics=['accuracy'])

final_model.fit([MNIST_train, RNN_train], match_train, epochs=1, batch_size=100)
目标数据是一个具有布尔值的形状(45000,1)的数组。我知道bool是不允许的,但我想我把它转换成了一个张量:

targets = tf.convert_to_tensor(targets, np.float32)

请首先查看文档,目标和logit必须具有相同的类型,shapeI检查类型()是否相同,目标和logit都是张量。我还检查了形状,因为我事先收到了一个错误。这也应该是可行的。最后,我将原始match_train数据集中的所有布尔值转换为0和1。我不理解不允许使用张量作为布尔值的错误。哪里有布尔值?错误消息没有说您有布尔值。“我不理解不允许使用张量作为布尔值的错误。”这意味着您在需要布尔值的位置传递了张量。请首先查看文档,目标和logit必须具有相同的类型,shapeI检查类型()是否相同,目标和logit都是张量。我还检查了形状,因为我事先收到了一个错误。这也应该是可行的。最后,我将原始match_train数据集中的所有布尔值转换为0和1。我不理解不允许使用张量作为布尔值的错误。哪里有布尔值?错误消息没有说明您有布尔值。“我不理解不允许使用张量作为布尔值的错误。”这意味着您在需要布尔值的地方传递了张量。