我正在尝试在一个简单的示例中使用 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。有什么想法吗?
最佳答案
您需要指定训练迭代次数来训练模型。否则,回归模型只输出初始值而无需训练。有2种方法可以试试,
方法一(在LinearRegressor.traning中指定训练迭代次数)
# 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'])
方法2(用batch size指定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=2500,batch_size=1) ###Edited here
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'])
希望这会有所帮助。
关于tensorflow - 尝试使用线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46982168/