在训练模型上调用预测时Tensorflow中的KeyError

时间:2016-09-25 13:49:25

标签: tensorflow

我训练过一个有两个特征的LinearRegressor:x,y和标签:l

def train_input_fn():
    x = [1,2,3,4]
    y = [2,3,4,5]
    feature_cols = tf.constant(x)
    labels = tf.constant(y)
    return feature_cols, labels    

x = tf.contrib.layers.real_valued_column("x")
y = tf.contrib.layers.real_valued_column("y")    
m = tf.contrib.learn.LinearRegressor(feature_columns=[ x,y],
                                      model_dir=model_dir)
m.fit(input_fn=train_input_fn, steps=100)

训练结束后,我想从两个新值预测

new_sample = np.array([20,20])
m.predict(new_sample)

但是在调用predict

时我收到此错误消息
File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/layers/python/layers/feature_column.py", line 870, in insert_transformed_feature
input_tensor = columns_to_tensors[self.name]
KeyError: 'x'

有谁知道我为什么会得到KeyError?

2 个答案:

答案 0 :(得分:1)

试试这个:

my_feature_columns = [tf.contrib.layers.real_valued_column("", dimension=2)]
m = tf.contrib.learn.LinearRegressor(feature_columns=my_feature_columns,
                                     model_dir=model_dir)
m.fit(input_fn=train_input_fn, steps=100)

答案 1 :(得分:0)

我不是Tensorflow的专家,但这对我有用:

new_sample = np.array([20,20],dtype='float32')
empty_y = np.zeros(len(new_sample),dtype='float32')
prediction_x = tf.contrib.learn.io.numpy_input_fn({"x":new_sample},empty_y, batch_size=45,    num_epochs=100)
forecast = list(estimator.predict(input_fn=prediction_x,as_iterable=False))