试图使用LinearRegressor

Mat*_*ino 3 regression tensorflow

我试图在一个简单的例子中使用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'])
Run Code Online (Sandbox Code Playgroud)

适当的输出应为3.8和2.8,但估算器预测为0.58和0.48.有什么想法吗?

Nip*_*hne 8

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

方法1 (指定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'])
Run Code Online (Sandbox Code Playgroud)

方法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=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'])
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.