2017-07-18 196 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設置作爲參數,和我的預測()調用沒有設置洗牌=假。所以輸出被打亂了,使他們看起來像沒有收斂!