自定义损失函数:不允许将“ tf.Tensor”用作Python“ bool”

时间:2019-05-31 08:30:36

标签: 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 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)且具有布尔值的数组。我知道不允许使用布尔,但我想我将其转换回张量,如下所示:

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

0 个答案:

没有答案