试图使用LinearRegressor

时间:2017-10-27 19:27:40

标签: tensorflow regression

我试图在一个简单的例子中使用tf.estimator.LinearRegressor。输入点位于y = 2x行,但估算器预测错误的值。这是我的代码:

# Create feature column and estimator
column = tf.feature_column.numeric_column("x", shape=[1])
lin_reg = tf.estimator.LinearRegressor([column])

# Train the estimator
train_input = tf.estimator.inputs.numpy_input_fn(
    x={"x": np.array([1.0, 2.0, 3.0, 4.0, 5.0])},
    y=np.array([2.0, 4.0, 6.0, 8.0, 10.0]), shuffle=False)
lin_reg.train(train_input)

 # Make two predictions
 predict_input = tf.estimator.inputs.numpy_input_fn(
     x={"x": np.array([1.9, 1.4], dtype=np.float32)},
     num_epochs=1, shuffle=False)
 results = lin_reg.predict(predict_input)

 # Print result
 for value in results:
     print(value['predictions'])

正确的输出应该是3.8和2.8,但估算器预测0.58和0.48。有什么想法吗?

1 个答案:

答案 0 :(得分:8)

您需要指定训练模型的训练迭代次数。否则,回归模型只输出初始值而不进行训练。您可以尝试两种方法,

方法1 (指定LinearRegressor.traning中的训练迭代次数)

readingMsg->setYcoor

方法2 (使用批量大小指定train_input中num_epoch的数量。

# Create feature column and estimator
column =  tf.feature_column.numeric_column('x')
lin_reg = tf.estimator.LinearRegressor(feature_columns=[column])

# Train the estimator
train_input = tf.estimator.inputs.numpy_input_fn(
    x={"x": np.array([1.0, 2.0, 3.0, 4.0, 5.0])},
    y=np.array([2.0, 4.0, 6.0, 8.0, 10.0]), shuffle=False,num_epochs=None)
lin_reg.train(train_input,steps=2500) ###Edited here

# Make two predictions
predict_input = tf.estimator.inputs.numpy_input_fn(
     x={"x": np.array([1.9, 1.4], dtype=np.float32)},
     num_epochs=1, shuffle=False)
results = lin_reg.predict(predict_input)

 # Print result
for value in results:
     print(value['predictions'])

希望这有帮助。