逻辑回归的损失函数在Tensorflow中 – 公式和Tensorflow函数结果不匹配

我在Tensorflow中尝试进行逻辑回归,使用了两种成本函数:

dim = train_X.shape[1]X = tf.placeholder(tf.float32, shape=(None, dim))y = tf.placeholder(tf.float32, shape=(None,1))W = tf.Variable(tf.zeros(shape=(dim,1)))b = tf.Variable(tf.zeros([1]))y_pred = tf.nn.sigmoid(tf.add(tf.matmul(X,W), b)) # 使用matmul进行矩阵乘法。 x.shape(768,8) w.shape(8,1)cost = tf.reduce_mean(tf.add(-tf.multiply(y, tf.log(y_pred)), -tf.multiply(1-y, tf.log(1-y_pred))))cost2 = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=y_pred, labels=y))train = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)train2 = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost2)

尽管我理解这两种成本函数应该给出相同的结果,但它们却给出了不同的结果。

session = tf.Session()session.run(init)print(session.run(cost, feed_dict={X:train_X, y:train_y}))print(session.run(cost2, feed_dict={X:train_X, y:train_y}))

能否有人解释为什么会发生这种情况,以及我应该做哪些更改才能使它们显示相同的结果?


回答:

对于cost2变量的预测变量应该是:

y_pred2 = tf.add(tf.matmul(X,W2), b2)

因为tf.nn.sigmoid_cross_entropy_with_logits已经包含了sigmoid函数。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注