自定义损失函数:logits和targets必须具有相同的形状((?,1)与(45000,)

2024-04-25 10:14:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我的模型预测二进制分类器中的一切为0。总的来说,我们有4000个真的和41000个假的。因此,我们正在尝试做一个自定义的损失函数。你知道吗

我收到的错误是:

你知道吗(logits.get\u形状(), 目标。获得形状()))

ValueError:logits和目标必须具有相同的形状((?,1)与(45000,)

代码如下所示:

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 = match_train
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'])

初始阵列的形状为:

modelCNN = (45000, 28, 28, 1) float64
modelRNN = (45000, 93, 13) float64
labels = (45000,1) boolean

注释中的代码部分地解决了这个问题。 我现在收到一个以前没有的错误。上面写着:

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.

  File "<ipython-input-6-42327e5a4b50>", line 3, in <module>
    metrics=['accuracy'])

  File "C:\Users\Tijev\Anaconda3\envs\tfp3.6\lib\site-packages\tensorflow\python\training\checkpointable\base.py", line 442, in _method_wrapper
    method(self, *args, **kwargs)

  File "C:\Users\Tijev\Anaconda3\envs\tfp3.6\lib\site-packages\tensorflow\python\keras\engine\training.py", line 215, in compile
    loss = loss or {}

Tags: ofinputifislayerstfkerasdense