开发者社区> 问答> 正文

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

我已经做了这个线性回归模型使用TensorFlow和我有这个错误==> 整个回溯过程如下:-

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))

顺便说一句,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))

函数现在正常工作,但错误仍然存在… 问题来源StackOverflow 地址:/questions/59379025/valueerror-features-should-be-a-dictionary-of-tensors-given-type-class-no

展开
收起
kun坤 2019-12-30 09:54:53 553 0
1 条回答
写回答
取消 提交回答
  • input_fn函数除了定义一个局部函数外什么也不做。 一旦调用input_fn函数,它只返回None对象。

    2019-12-30 09:55:00
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载