gpt4 book ai didi

python - 为什么简单回归的 TensorFlow 结果与其输入相差甚远?

转载 作者:行者123 更新时间:2023-11-30 09:32:49 25 4
gpt4 key购买 nike

我有一个简单的回归训练数据,如下所示。我想在 TensorFlow 中训练网络,然后再次在网络中输入 [1 0 1] (与示例 3 相同),这应该会给出接近 1 的值(比如 0.99)。

enter image description here

现在这是我的 TensorFlow 代码(Python 3)。我使用了线性层,然后使用了 Sigmoid。我用的是均方损失。请注意,在最后几行中,我输入了 [1 0 1] 来测试模型的预测能力。我只得到了 0.5015,这与我的预期相去甚远(即 0.99)。

版本 1:TensorFlow 代码:

import tensorflow as tf
import numpy as np

batch_xs=np.array([[0,0,1],[1,1,1],[1,0,1],[0,1,1]])
batch_ys=np.array([[0],[1],[1],[0]])

x = tf.placeholder(tf.float32, [None, 3])
W = tf.Variable(tf.zeros([3, 1]))
b = tf.Variable(tf.zeros([1]))

y = tf.nn.sigmoid(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 1])

mean_square_loss = tf.reduce_mean(tf.square(y_ - y))

learning_rate = 0.05

train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(mean_square_loss)
sess = tf.Session()
tf.global_variables_initializer().run(session=sess)

sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

x0=np.array([[1.,0.,1.]])
x0=np.float32(x0)
y0=tf.nn.sigmoid(tf.matmul(x0,W) + b)

print('%.15f' % sess.run(y0))

为什么结果与预期值相差甚远?如果我只使用 Numpy 而不是 TensorFlow,下面的 9 行代码可以实现 0.9936 的输出。

版本 2:Numpy 代码:

from numpy import exp, array, random, dot
training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
training_set_outputs = array([[0, 1, 1, 0]]).T
random.seed(1)
synaptic_weights = 2 * random.random((3, 1)) - 1
for iteration in range(10000):
output = 1 / (1 + exp(-(dot(training_set_inputs, synaptic_weights))))
synaptic_weights += dot(training_set_inputs.T, (training_set_outputs - output) * output * (1 - output))
print(1 / (1 + exp(-(dot(array([1, 0, 1]), synaptic_weights)))))

如何修复版本 1 中的 TensorFlow 代码以使结果接近 0.99?非常感谢!

最佳答案

在您的 tensorflow 代码中 sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) 更新/训练您的权重。请注意,您仅以 0.05 的学习率运行一次。但在你的 numpy 代码中,你运行 10000 次迭代,这相当于执行

for i in range(10000):
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

结果应该是 0.95 左右。如果你将学习率增加到 1,就像在 numpy 代码上完成的那样,你应该得到预期的行为 (0.99)。

关于python - 为什么简单回归的 TensorFlow 结果与其输入相差甚远?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51446438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com