0
我正在尝试学习Tensorflow。我正在做一个基本的例子 - 为方程y = x + 0.1建模,使用神经网络进行训练,然后进行预测。我实际上是采用S形方法(不理想),所以不使用标准的softmax/relu方式(这对我不起作用)。代码运行,但答案是错误的:批处理中的所有预测给出几乎相同的答案,如y_true = [[0.356],[0.356],[0.356],[0.356]],对于输入= [[0.1,0.2, 0.3,0.4]]。我究竟做错了什么?代码如下:Tensorflow-使用神经网络估计基本线性方程
import tensorflow as tf
import numpy as np
epochs = 1000
# For equation y = b + 0.1, sample data below
myImportedDatax_np = np.array([[.1],[.2],[.3],[.4]],dtype=float)
myImportedDatay_np = np.array([[.2],[.3],[.4],[.5]],dtype=float)
c = tf.constant(0.1, name='c')
b = tf.placeholder(tf.float32, [None, 1], name='b')
y = tf.add(b, c, name='y')
y_true = tf.placeholder(tf.float32, [None, 1], name='y_true')
W1 = tf.Variable(tf.random_normal([1, 3], stddev=0.03), name='W1')
b1 = tf.Variable(tf.random_normal([3]), name='b1')
W2 = tf.Variable(tf.random_normal([3, 1], stddev=0.03), name='W2')
b2 = tf.Variable(tf.random_normal([1]), name='b2')
hidden_out = tf.add(tf.matmul(b, W1), b1)
hidden_out = tf.sigmoid(hidden_out)
y_ = tf.sigmoid(tf.add(tf.matmul(hidden_out, W2), b2))
cost = tf.reduce_mean(tf.square(y_ - y_true))
optimiser = tf.train.GradientDescentOptimizer(0.005).minimize(cost)
init_op = tf.initialize_all_variables()
with tf.Session() as sess:
# initialise the variables
sess.run(init_op)
for epoch in range(epochs):
_, cost_now = sess.run([optimiser, cost], {b: myImportedDatax_np, y_true: myImportedDatay_np})
print("Predicted values are:")
print(sess.run(y_, {b: myImportedDatax_np}))
添加的代码中答案 –
太棒了,它的工作原理。如你所说,巨大的差异在于大量的时代以及学习速度的提高。如果我在sigmoid中添加输出,结果可能相当不真实。 –