ValueError:特征应该是`Tensor`的字典。给定类型:<class'NoneType'>

时间:2019-12-17 17:10:19

标签: python tensorflow machine-learning neural-network linear-regression

我已经使用TensorFlow制作了此线性回归模型,并且出现此错误==>

  

ValueError:功能应该是'Tensor's的字典。   基本上,模型会接受CSV格式的数据集,并从文件中提取数据

整个TraceBack如下:-

INFO:tensorflow:Calling model_fn.
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-138-facba27f689a> in <module>
----> 1 model.train(steps = 1000, input_fn= lambda : input_fn(df_train, batch_size = 128, num_epoch = None))

c:\users\neelg\tf2_gpu\lib\site-packages\tensorflow_estimator\python\estimator\estimator.py in train(self, input_fn, hooks, steps, max_steps, saving_listeners)
    368 
    369       saving_listeners = _check_listeners_type(saving_listeners)
--> 370       loss = self._train_model(input_fn, hooks, saving_listeners)
    371       logging.info('Loss for final step: %s.', loss)
    372       return self

c:\users\neelg\tf2_gpu\lib\site-packages\tensorflow_estimator\python\estimator\estimator.py in _train_model(self, input_fn, hooks, saving_listeners)
   1158       return self._train_model_distributed(input_fn, hooks, saving_listeners)
   1159     else:
-> 1160       return self._train_model_default(input_fn, hooks, saving_listeners)
   1161 
   1162   def _train_model_default(self, input_fn, hooks, saving_listeners):

c:\users\neelg\tf2_gpu\lib\site-packages\tensorflow_estimator\python\estimator\estimator.py in _train_model_default(self, input_fn, hooks, saving_listeners)
   1188       worker_hooks.extend(input_hooks)
   1189       estimator_spec = self._call_model_fn(
-> 1190           features, labels, ModeKeys.TRAIN, self.config)
   1191       global_step_tensor = training_util.get_global_step(g)
   1192       return self._train_with_estimator_spec(estimator_spec, worker_hooks,

c:\users\neelg\tf2_gpu\lib\site-packages\tensorflow_estimator\python\estimator\estimator.py in _call_model_fn(self, features, labels, mode, config)
   1146 
   1147     logging.info('Calling model_fn.')
-> 1148     model_fn_results = self._model_fn(features=features, **kwargs)
   1149     logging.info('Done calling model_fn.')
   1150 

c:\users\neelg\tf2_gpu\lib\site-packages\tensorflow_estimator\python\estimator\canned\linear.py in _model_fn(features, labels, mode, config)
   1345           optimizer=optimizer,
   1346           config=config,
-> 1347           sparse_combiner=sparse_combiner)
   1348 
   1349     super(LinearRegressorV2, self).__init__(

c:\users\neelg\tf2_gpu\lib\site-packages\tensorflow_estimator\python\estimator\canned\linear.py in _linear_model_fn_v2(features, labels, mode, head, feature_columns, optimizer, config, sparse_combiner)
    659   if not isinstance(features, dict):
    660     raise ValueError('features should be a dictionary of `Tensor`s. '
--> 661                      'Given type: {}'.format(type(features)))
    662 
    663   del config

ValueError: features should be a dictionary of `Tensor`s. Given type: <class 'NoneType'>

这是我的代码:---

import tensorflow as tf
import matplotlib.pyplot as plt

df_train = "C:/Users/neelg/Documents/Jupyter/Linear-reg/boston_train.csv"
df_eval = "C:/Users/neelg/Documents/Jupyter/Linear-reg/boston_test.csv"

COLUMNS = ["crim", "zn", "indus", "nox", "rm", "age","dis", "tax", "ptratio", "medv"]
RECORDS_ALL = [[0.0], [0.0], [0.0], [0.0],[0.0],[0.0],[0.0],[0.0],[0.0],[0.0]]

def input_fn(data_file, batch_size, num_epoch):
    def parse_csv(value):
        columns = tf.io.decode_csv(value, record_defaults= RECORDS_ALL)
        features = dict(zip(COLUMNS, columns))
        #labels = features.pop('median_house_value')
        labels =  features.pop('medv')
        return features, labels

          # Extract lines from input files using the dataset API
        dataset = (tf.data.TextLineDataset(data_file) # Read text file
        .skip(1) # Skip header row
        .map(parse_csv))

        dataset = dataset.repeat(num_epoch)
        dataset = dataset.batch(batch_size)
          # Here goes the iterator==>
        iterator = dataset.make_one_shot_iterator()
        features, labels = iterator.get_next()
        return features, labels

X1= tf.feature_column.numeric_column('crim')
X2= tf.feature_column.numeric_column('zn')
X3= tf.feature_column.numeric_column('indus')
X4= tf.feature_column.numeric_column('nox')
X5= tf.feature_column.numeric_column('rm')
X6= tf.feature_column.numeric_column('age')
X7= tf.feature_column.numeric_column('dis')
X8= tf.feature_column.numeric_column('tax')
X9= tf.feature_column.numeric_column('ptratio')

base_columns = [X1, X2, X3, X4, X5, X6, X7, X8, X9]

model = tf.estimator.LinearRegressor(feature_columns=[base_columns], model_dir='train3')
#Training the estimator:
model.train(steps = 1000, input_fn= lambda : input_fn(df_train, batch_size = 128, num_epoch = None))

BTW,x1,x2 ...是指数据集的列

  

这是我的训练数据集的样子(奇怪的词代表列标题)====>

400,9,CRIM,ZN,INDUS,NOX,RM,AGE,DIS,TAX,PTRATIO,MEDV
2.3004,0.0,19.58,0.605,6.319,96.1,2.1,403,14.7,23.8
13.3598,0.0,18.1,0.693,5.887,94.7,1.7821,666,20.2,12.7

我非常确定问题出在“ Input_fn”函数中,因此我将其转换为

features = dict(tf.convert_to_tensor(zip(COLUMNS, columns)))

对此:-

features = dict(tf.convert_to_tensor(zip(COLUMNS, columns)))

但是那也不起作用:(任何帮助?

更新 尝试将行更改为此:

dataset = (tf.data.TextLineDataset(data_file).skip(1).map(parse_csv))

该功能现在可以正常使用,但错误仍然存​​在...

1 个答案:

答案 0 :(得分:0)

input_fn函数除了定义本地函数外没有做任何事情。 调用input_fn函数后,它仅返回None对象。