2017-07-18 181 views
0

我试图用TensorFlow在Python中做一个玩具线性回归,使用预先构建的估计器tf.contrib.learn.LinearRegressor而不是构建我自己的估计器。 我使用的输入是0到1之间的实数值,输出只是3 *输入。 TensorFlow似乎符合数据(没有提出错误),但输出与它们应该是什么没有关系。Tensorflow LinearRegressor不收敛

我不确定我是否正确地完成了预测 - 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

回答

0

想出答案,回答这里posterity- 我输入功能LinearRegressor有洗牌= true设置作为参数,和我的预测()调用没有设置洗牌=假。所以输出被打乱了,使他们看起来像没有收敛!