我有一组简单的回归训练数据如下。我希望在TensorFlow中训练网络,并再次输入[1 0 1]
(与示例3相同)到网络中,这应该给我一个接近1的值(比如0.99)。
现在这是我的TensorFlow代码(使用Python 3)。我使用了一个线性层,然后是一个Sigmoid函数。我使用了均方损失。请注意,在最后几行中,我输入了[1 0 1]
来测试模型的预测能力。我得到的只是0.5015
,这与我的期望(即0.99
)相差甚远。
版本1:TensorFlow代码:
import tensorflow as tfimport numpy as npbatch_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.05train_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, dottraining_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])training_set_outputs = array([[0, 1, 1, 0]]).Trandom.seed(1)synaptic_weights = 2 * random.random((3, 1)) - 1for 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)。