2017-06-18 45 views
1

我使用Tensorflow 1.2停止,下面的代码:TensorFlow/TFLearn LinearRegressor具有非常高的损耗

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中的损失彼此不匹配?

我已经使用vanilla TensorFlow实现了这个非常算法,它的工作方式和预期的一样,但我真的无法从这里得到LinearRegressor想要的东西。

回答

2

这里是一些(部分)回答你的问题。可能没有解决你所有的问题,但希望能给你更多的见解。

  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表示拟合方法最多可以处理1000次数据(或1000步,以先发生者为准)。这就是为什么适合天花板(1000 * 6/128)= 47步骤。将batch_size设置为6(您的训练数据集的大小)或num_epochs = None会给您更合理的结果(我建议将batch_size设置为最多6,因为在单个步骤中循环使用您的训练样本不止一次可能没有多大意义)

  2. 为什么步骤10的损失小于步骤47的损失? 有几个不同的原因,损失可能不会减少。 a。不计算每一步骤中完全相同数据的损失。例如,如果您的样品尺寸为100,批次尺寸为32,则每一步都将计算下一批次尺寸为32的损耗(此过程循环) b。你的学习速度太高,所以损失反弹。为了解决这个问题,可以尝试降低学习速度,甚至试用不同的优化器。我相信默认情况下,LinearRegressor中使用的优化器是FtrlOptimizer。

    估计= tflearn.LinearRegressor( feature_columns = FTS, 优化= tf.train.FtrlOptimizer(learning_rate = ...))

    :使用下面的命令,当你构建LinearRegressor您可以更改其默认学习率

    另外,你可以尝试完全不同的优化器。 估计= tflearn.LinearRegressor( feature_columns = FTS, 优化= tf.train.GradientDescentOptimizer(learning_rate = ...))