Tensorflow LinearRegressor不会聚

时间:2017-07-18 01:04:49

标签: python machine-learning tensorflow regression

我正在尝试使用TensorFlow在Python中进行玩具线性回归,使用预先构建的估算器tf.contrib.learn.LinearRegressor而不是构建我自己的估算器。 我正在使用的输入是介于0和1之间的实数值,输出只是3 *输入。 TensorFlow似乎适合数据(没有错误),但输出与它们应该是无关。

我不确定我是否正确完成预测 - predict()函数的文档非常稀疏。

关于如何改善拟合的任何想法?

import numpy as np
import pandas as pd
import tensorflow as tf
import itertools
import matplotlib.pyplot as plt

#Defining data set
x = np.random.rand(200)
y = 3.0*x
data = pd.DataFrame({'X':x, 'Y':y})
training_data = data[50:]
test_data= data[:50]

COLUMNS = ['Y','X']
FEATURES = ['X']
LABELS = 'Y'

#Wrapper function for the inputs of LinearRegressor
def get_input_fn(data_set, num_epochs=None, shuffle=True):
  return tf.estimator.inputs.pandas_input_fn(
      x=pd.DataFrame(data_set[FEATURES]),
      y=pd.Series(data_set[LABELS]),
      num_epochs=num_epochs,
      shuffle=shuffle)


feature_cols = [tf.feature_column.numeric_column(k) for k in FEATURES]
regressor = tf.contrib.learn.LinearRegressor(feature_columns=feature_cols)
regressor.fit(input_fn=get_input_fn(test_data), steps=100)

results = regressor.predict(input_fn=get_input_fn(test_data, 
num_epochs=1))
predictions = list(itertools.islice(results, 50))

#Visualizing the results
fig = plt.figure(figsize=[8,8])
ax = fig.add_subplot(111)
ax.scatter(test_data[LABELS], predictions)

ax.set_xlabel('Actual')
ax.set_ylabel('Predicted')
plt.show()

Scatter plot of results

1 个答案:

答案 0 :(得分:0)

找出答案,回答这里的后代 - 我对LinearRegressor的输入函数有shuffle = True设置为参数,而我的predict()调用没有设置shuffle = False。因此,输出被改组,使它们看起来像它们没有收敛!