python - Tensorflow - tf.nn.weighted_cross_entropy_with_logits - logits 和目标必须具有相同的形状

标签 python tensorflow machine-learning

我刚刚开始在我正在进行的项目中使用tensorflow。该程序旨在成为一个输入为 12 个特征的二元分类器。输出是正常患者或患有疾病的患者。这种疾病的患病率相当低,因此我的数据集非常不平衡,有 502 个正常对照样本,只有 38 个患病患者。因此,我尝试使用 tf.nn.weighted_cross_entropy_with_logits 作为我的成本函数。

该代码基于官方tensorflow文档中的iris自定义估计器,并使用tf.losses.sparse_softmax_cross_entropy作为成本函数。但是,当我更改为 weighted_cross_entropy_with_logits 时,出现形状错误,并且我不知道如何解决此问题。

ValueError: logits and targets must have the same shape ((?, 2) vs (?,))

我已经搜索过,类似的问题已经通过重新调整标签来解决 - 我尝试这样做但没有成功(并且不明白为什么tf.losses.sparse_softmax_cross_entropy工作正常并且加权版本才不是)。

我的完整代码在这里 https://gist.github.com/revacious/83142573700c17b8d26a4a1b84b0dff7

谢谢!

最佳答案

使用非稀疏交叉熵函数,您需要对标签进行 one-hot 编码,以便它们与您的 logits 具有相同的形状:

loss = tf.nn.weighted_cross_entropy_with_logits(tf.one_hot(labels, 2), logits, pos_weight)

注意tf.losses.sparse_softmax_cross_entropy还允许一个权重参数,尽管它的含义略有不同(它只是一个样本权重)。等效的公式应该是:

loss = tf.losses.sparse_softmax_cross_entropy(labels, logits,
                                              weights=pos_weight * labels + (1 - labels))

关于python - Tensorflow - tf.nn.weighted_cross_entropy_with_logits - logits 和目标必须具有相同的形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55168906/

相关文章:

python - 如何快速获取使用 PyCharm 和 Pytorch 的文档

python - 使用 bash 或 python 基于空格/制表符的字符串解析行

python - 混合 asyncio 和 Kivy : How to start the asyncio loop and the Kivy application at the same time?

tensorflow - Tensorflow 中是否有与 PyTorch 的 RandomResizedCrop 等效的功能?

tensorflow - CNN 的模型架构设计

node.js - Brain js 用于顺序时间预测

python - 在anaconda3中安装opencv

python - 如果行不满足使用 pandas 的条件,如何删除行

python - 使用 3D 张量的最后一个维度中的索引索引 4D 张量的最后一个维度

python - 如何使用占位符分配 tf.Variables?