【问题标题】:Binary Logistic Regression - do we need to one_hot encode label?二元逻辑回归 - 我们需要 one_hot 编码标签吗?
【发布时间】:2020-04-19 04:10:44
【问题描述】:

我有一个逻辑回归模型,我参考这个link

标签是一个布尔值(0 或 1 作为值)。

在这种情况下我们需要对标签进行 one_hot 编码吗?

问的原因:我使用下面的函数来找到 cross_entropy 并且损失总是为零。

def cross_entropy(y_true, y_pred):
    y_true = tf.one_hot([y_true.numpy()], 2)
    print(y_pred)
    print(y_true)
    loss_row = tf.nn.softmax_cross_entropy_with_logits(labels=y_true, logits=y_pred)
    print('Loss')
    print(loss_row)
    return tf.reduce_mean(loss_row)

编辑:- 渐变将 [None,None] 作为返回值(用于以下代码)。

def grad(x, y):
with tf.GradientTape() as tape:
    y_pred = logistic_regression(x)
    loss_val = cross_entropy(y, y_pred)       
return tape.gradient(loss_val, [w, b])

示例值

loss_val => tf.Tensor(307700.47, shape=(), dtype=float32)

w => tf.Variable 'Variable:0' shape=(171, 1) dtype=float32, numpy= 数组([[ 0.7456649 ], [-0.35111237],[-0.6848465 ],[ 0.22605407]]

b => tf.Variable 'Variable:0' shape=(1,) dtype=float32, numpy=array([1.1982833], dtype=float32)

【问题讨论】:

  • 在二元逻辑回归的情况下,您不需要 one_hot 编码。一般用于多项逻辑回归。
  • 在参考中,fashion_mnist 数据集有 10 个标签(即 0-9),因此它需要 one_hot 编码,而在您的情况下它只有两个标签(例如:是:1 或否:0 或反之亦然),因此不需要 one_hot 编码。

标签: tensorflow machine-learning label one-hot-encoding


【解决方案1】:

在二元逻辑回归的情况下,您不需要 one_hot 编码。一般用于多项逻辑回归。

【讨论】:

  • 但是当我这样做时,“sigmoid_cross_entropy_with_logits”返回零。
【解决方案2】:

如果你在做普通(二元)逻辑回归(带有 0/1 标签),那么使用损失函数tf.nn.sigmoid_cross_entropy_with_logits()

如果您要进行多类逻辑回归(也称为 softmax 回归或多项逻辑回归),那么您有两种选择:

  1. 以 1-hot 格式定义您的标签(例如 [1, 0, 0][0, 1, 0]、...)并使用损失函数 tf.nn.softmax_cross_entropy_with_logits()

  2. 将标签定义为单个整数(例如 1、2、3、...)并使用损失函数 tf.nn.sparse_softmax_cross_entropy_with_logits()

对于后两者,您可以在这个 StackOverflow 问题中找到更多信息:

What's the difference between sparse_softmax_cross_entropy_with_logits and softmax_cross_entropy_with_logits?

【讨论】:

  • tf.nn.softmax_cross_entropy_with_logits() 的值为零。你能告诉我可能是什么问题吗?
  • 您的数据可能不是您期望的形式。打印出它们的形状、类型和值,并确保它们是函数调用所期望的。将形状、类型和值与 TensorFlow 教程中的示例进行比较。
  • 谢谢。现在损失函数正在使用 tf.nn.sigmoid_cross_entropy_with_logits(),现在返回 tape.gradient(loss_val, [w, b]) 正在返回 [None, None]
  • 关注这里的例子:github.com/nlintz/TensorFlow-Tutorials/blob/master/… 其实这个 github repo 有很多好的 TensorFlow 例子。
猜你喜欢
  • 1970-01-01
  • 2016-05-10
  • 1970-01-01
  • 2013-12-20
  • 2017-11-02
  • 2020-08-01
  • 1970-01-01
  • 2014-04-24
  • 1970-01-01
相关资源
最近更新 更多