【问题标题】:Logistic regression with {-1,1} labels in Tensorflow 2TensorFlow 2 中带有 {-1,1} 标签的逻辑回归
【发布时间】:2021-12-10 11:52:32
【问题描述】:

我正在尝试使用 Tensorflow 实现逻辑回归。我假设我有 {-1, 1} 形式的标签。所以,我已经实现了决策函数和损失函数

def cross_entropy(y_pred, y_true):
  return tf.reduce_mean(tf.math.log(1 + tf.math.exp(- y_true * y_pred[:, 0] ))) + tf.nn.l2_loss(W)`

def logistic_regression(x):
  return tf.matmul(x, W) + b

  

这是正确的吗?损失为nan

【问题讨论】:

  • Tensorflow 对于逻辑回归来说太过分了。我建议使用 sklearn 之类的东西。也许我不理解您的问题,您是否真的在使用神经网络并且您想使用值在 -1 和 1 之间的响应变量?

标签: python tensorflow machine-learning logistic-regression


【解决方案1】:

这是一个选项,


def logistic_regression(x):
    # Apply softmax to normalize the logits to a probability distribution.
    return tf.nn.softmax(tf.matmul(x, W) + b)

def cross_entropy(y_pred, y_true):

    # Encode label to a one hot vector.
    y_true = tf.one_hot(y_true, depth=num_classes)
    # Clip prediction values to avoid log(0) error.
    y_pred = tf.clip_by_value(y_pred, 1e-9, 1.)

    # Compute cross-entropy.
    return tf.reduce_mean(-tf.reduce_sum(y_true * tf.math.log(y_pred)))

看看这个完整的实现 https://builtin.com/data-science/guide-logistic-regression-tensorflow-20

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 2020-07-04
    • 2019-04-04
    相关资源
    最近更新 更多