【问题标题】:Custom Loss Function: logits and targets must have the same shape ((?, 1) vs (45000,))自定义损失函数:logits 和目标必须具有相同的形状 ((?, 1) vs (45000,))
【发布时间】:2019-10-15 10:47:35
【问题描述】:

我的模型将二进制分类器中的所有内容都预测为 0。我们总共有 4000 个真值和 41000 个假值。因此,我们正在尝试制作自定义损失函数。

我收到的错误是:

(logits.get_shape(), targets.get_shape()))

ValueError: logits 和 targets 必须具有相同的形状 ((?, 1) vs (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

问题已通过 cmets 中的代码部分解决。 我现在收到一个以前没有的错误。它说:

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 {}

【问题讨论】:

    标签: python tensorflow machine-learning


    【解决方案1】:

    将标签重塑为 2D 张量。

    targets = np.asarray(match_train).astype('float32').reshape((-1,1))
    

    来源:Tensorflow estimator ValueError: logits and labels must have the same shape ((?, 1) vs (?,))

    【讨论】:

    • 这似乎部分工作。我现在收到另一个错误。我编辑了我的帖子。你能看看那个吗?这是我在创建自定义损失函数之前没有遇到的错误。
    • 您应该为此打开一个单独的问题,而不是修改您提出的问题,因为您现在询问的是另一个错误。一般来说,问题似乎是将 Numpy/Python 与 Tensorflow 混合在一起。 stackoverflow.com/questions/49177169/… 这可能有助于您了解问题,但除此之外,我强烈建议您在谷歌上搜索错误并查看出现的情况。 Stackoverflow 鼓励在提问之前尝试查找资料,以减少冗余。祝你好运!
    猜你喜欢
    • 2021-10-18
    • 2019-05-22
    • 2018-06-29
    • 2021-09-16
    • 2021-08-27
    • 2019-02-23
    • 2021-10-22
    • 1970-01-01
    • 2021-09-19
    相关资源
    最近更新 更多