tensorflow - 尝试使用线性回归

标签 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。有什么想法吗?

最佳答案

您需要指定训练迭代次数来训练模型。否则,回归模型只输出初始值而无需训练。有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/

相关文章:

python - colab如何释放内存?

r - 拟合具有多个 LHS 的线性模型

r - 如何限制斜率在回归中为正?

Python:为简单的 OLS 循环一个变量

python - 特征提取器是否接受过 Tensorflow 对象检测 API 的培训?

python - 带有 TensorFlow 的 Anaconda : No module named any_pb2

python - 嵌套 tf.map_fn 性能缓慢

python - TensorFlow:在变量范围内取消设置 'reuse'

python - 在回归输出中命名解释变量

r - 如何使用向量作为预测变量运行多元线性回归?