TensorFlow / TFLearn LinearRegressor以非常高的损失停止



我正在使用Tensorflow 1.2,这是代码:

import tensorflow as tf
import tensorflow.contrib.layers as layers
import numpy as np
import tensorflow.contrib.learn as tflearn
tf.logging.set_verbosity(tf.logging.INFO)
# Naturally this is a very simple straight line
# of y = -x + 10
train_x = np.asarray([0., 1., 2., 3., 4., 5.])
train_y = np.asarray([10., 9., 8., 7., 6., 5.])
test_x = np.asarray([10., 11., 12.])
test_y = np.asarray([0., -1., -2.])
input_fn_train = tflearn.io.numpy_input_fn({"x": train_x}, train_y, num_epochs=1000)
input_fn_test = tflearn.io.numpy_input_fn({"x": test_x}, test_y, num_epochs=1000)
validation_monitor = tflearn.monitors.ValidationMonitor(
input_fn=input_fn_test,
every_n_steps=10)
fts = [layers.real_valued_column('x')]
estimator = tflearn.LinearRegressor(feature_columns=fts)
estimator.fit(input_fn=input_fn_train,
steps=1000,
monitors=[validation_monitor])
print(estimator.evaluate(input_fn=input_fn_test))

它按预期运行。正在发生的事情是,训练在步骤 47 停止,损失值非常高:

INFO:tensorflow:Starting evaluation at 2017-06-18-20:52:10
INFO:tensorflow:Finished evaluation at 2017-06-18-20:52:10
INFO:tensorflow:Saving dict for global step 1: global_step = 1, loss = 12.5318
INFO:tensorflow:Validation (step 10): global_step = 1, loss = 12.5318
INFO:tensorflow:Saving checkpoints for 47 into    
INFO:tensorflow:Loss for final step: 19.3527.
INFO:tensorflow:Starting evaluation at 2017-06-18-20:52:11
INFO:tensorflow:Restoring parameters from   
INFO:tensorflow:Finished evaluation at 2017-06-18-20:52:11
INFO:tensorflow:Saving dict for global step 47: global_step = 47, loss = 271.831
{'global_step': 47, 'loss': 271.83133}

我完全不明白的几件事(诚然,我是 TF 中的一个彻头彻尾的菜鸟):

  1. 为什么步骤 10 的损失小于步骤 47 的损失?
  2. 为什么TF决定在之后停止培训?
  3. 为什么"INFO:tensorflow:最后一步的损失:19.3527"和步骤47的损失不匹配?

我已经使用原版TensorFlow构建了这个算法,它按预期工作,但我真的无法掌握LinearRegressor在这里想要从我这里得到什么。

这里有一些(部分)问题的答案。可能无法解决您的所有问题,但希望能为您提供更多见解。

  1. 为什么TF决定在之后停止训练? 这与以下事实有关:您已设置 num_epochs=1000,并且numpy_input_fn的默认batch_size为 128(请参阅 https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/learn_io/numpy_io.py)。 num_epochs=1000 表示 fit 方法最多遍历数据 1000 次(或 1000 步,以先发生者为准)。这就是为什么适合天花板(1000 * 6/128)=47步的原因。将batch_size设置为 6(训练数据集的大小)或 num_epochs=None 将为您提供更合理的结果(我建议将batch_size设置为最多 6,因为在单个步骤中多次循环使用训练样本可能没有多大意义)

  2. 为什么步骤 10 的损失小于步骤 47 的损失? 损失可能不会减少有几个不同的原因。 a. 不计算每一步完全相同数据的损失。例如,如果您的样本大小为 100,而您的batch_size为 32,则每一步您都将计算下一批大小为 32 的损失(这种情况会循环进行) b.您的学习率太高,因此损失会反弹。为了解决这个问题,也许可以尝试降低学习率,甚至尝试使用不同的优化器。我相信默认情况下,LinearRegressor中使用的优化器是FtrlOptimizer。构造线性回归器时,可以使用以下命令更改其默认学习率:

    估计器 =tflearn。线性回归器( feature_columns=英尺, optimizer=tf.train.FtrlOptimizer(learning_rate=...))

    或者,您可以完全尝试使用其他优化器。 估计器 = tflearn。线性回归器( feature_columns=英尺, optimizer=tf.train.GradientDescentOptimizer(learning_rate=...))

最新更新