【发布时间】:2018-07-28 16:09:04
【问题描述】:
我目前正在学习 tensorflow,无法理解为什么 tensorflow 不能对以下简单回归问题进行正确预测。
X 是从 1000 到 8000 的随机数 Y 为 X + 250
所以如果 X 是 2000,Y 是 2250。这对我来说似乎是一个线性回归问题。然而,当我尝试进行预测时,它与我的预期相差甚远,X of 1000 给我的预测是 1048 而不是 1250。
损失和平均损失也很大:
{'average_loss': 10269.81, 'loss': 82158.48, 'global_step': 1000}
完整代码如下:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from sklearn.model_selection import train_test_split
x_data = np.random.randint(1000, 8000, 1000000)
y_true = x_data + 250
feat_cols = [tf.feature_column.numeric_column('x', shape=[1])]
estimator = tf.estimator.LinearRegressor(feature_columns=feat_cols)
x_train, x_eval, y_train, y_eval = train_test_split(x_data, y_true, test_size=0.3, random_state=101)
input_func = tf.estimator.inputs.numpy_input_fn({'x': x_train}, y_train, batch_size=8, num_epochs=None, shuffle=True)
train_input_func = tf.estimator.inputs.numpy_input_fn({'x': x_train}, y_train, batch_size=8, num_epochs=1000, shuffle=False)
eval_input_func = tf.estimator.inputs.numpy_input_fn({'x': x_eval}, y_eval, batch_size=8, num_epochs=1000, shuffle=False)
estimator.train(input_fn=input_func, steps=1000)
train_metrics = estimator.evaluate(input_fn=train_input_func, steps=1000)
eval_metrics = estimator.evaluate(input_fn=eval_input_func, steps=1000)
print(train_metrics)
print(eval_metrics)
brand_new_data = np.array([1000, 2000, 7000])
input_fn_predict = tf.estimator.inputs.numpy_input_fn({'x': brand_new_data}, shuffle=False)
prediction_result = estimator.predict(input_fn=input_fn_predict)
print(list(prediction_result))
是我做错了什么还是我误解了 LinearRegression 的含义?
【问题讨论】:
标签: python tensorflow machine-learning