我在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函数。