我试图使用“梯度下降算法”来训练我的数据,以最小化成本值,
而且奇怪的是,根据步骤数得出的结果也有所不同。
下面是我的训练代码:
import tensorflow as tf
X = tf.placeholder(tf.float32, shape=[None, 2], name="X")
Y = tf.placeholder(tf.float32, shape=[None, 1], name="Y")
W = tf.Variable(tf.random_normal([2, 1]), name="weight")
b = tf.Variable(tf.random_normal([1]), name="bias")
hypo = tf.sigmoid(tf.matmul(X, W) +b)
cost = -tf.reduce_mean(Y*(tf.log*(hypo)) + (1-Y)*(tf.log(1-hypo)))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-3)
train = optimizer.minimize(cost)
#### Saving model
SAVER_DIR = "model"
saver = tf.train.Saver()
checkpoint_path = os.path.join(SAVER_DIR, "model")
ckpt = tf.train.get_checkpoint_state(SAVER_DIR)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for step in range(4201):
cost_val, hy_val, _ = sess.run([cost, hypo, train], feed_dict={X:x_data, Y=y_data})
saver.save(sess, checkpoint_path, global_step=step)
并恢复模型:
saver = tf.train.import_meta_graph('./model/model-4200.meta')
saver.restore(sess,'./model/model-4200')
result = sess.run(hypo, feed_dict={X: x_data_test})
fig, ax = plt.subplots()
ax.plot(Julian_test,y_data_test,'ro-') # Correct answer. all items are one of the two:0 or 1.
ax.plot(Julian_test,result,'bo-') # Result of training. Predict answer within
plt.show() # sigmoid function, so all items are in range of 0 ~ 1.
如图所示,乙状结肠的结果是相反的。
但是,当我将步数更改为 5000 时,(在上面的代码中,我只更改了步数。)
结果正确显示。
我不明白为什么会有所不同。我错过了什么?确实需要帮助!
答案 0 :(得分:1)
通过增加允许您的tensorflow代码/模型多次查看数据的步骤,从而使它能够学习更多有关数据的见解。并概括其表示形式。
E 假设您给模型提供了2000步,并在2000步结束时找到了最小值,并且模型在那里停了下来。但是,如果模型到目前为止找到的最低成本不是全局最低值,那我们就不能说了,因为我们将其限制为2000步。因此,假设您将步数增加到20000,然后模型又找到另一个最小值,可以给出更准确的结果。
但是,您需要确保模型不会过度拟合,即提供训练数据的准确性,而不是验证集的准确性。 (因此,请确保不要将数字步数增加太多)。