tensorflow ValueError: features 应该是 `Tensor`s ​​的字典.给定类型:<class 'tensorflow.python.framework.ops.Tensor'> [英] tensorflow ValueError: features should be a dictionary of `Tensor`s. Given type: <class 'tensorflow.python.framework.ops.Tensor'>

查看:42
本文介绍了tensorflow ValueError: features 应该是 `Tensor`s ​​的字典.给定类型:<class 'tensorflow.python.framework.ops.Tensor'>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码!我的 tensorflow 版本是 1.6.0,python 版本是 3.6.4.如果我直接使用数据集读取 csv 文件,我可以训练并且没有错.但是我将 csv 文件转换为 tfrecords 文件,这是错误的.我在互联网上搜索它,几乎有人说 tensorflow 应该更新,但它对我不起作用.

This is my code! My tensorflow version is 1.6.0, python version is 3.6.4. If I direct use dataset to read csv file, I can train and no wrong. But I convert csv file to tfrecords file, it's wrong. I google it in Internet and almost people say tensorflow should be updated, but it don't work for me.

import tensorflow as tf

tf.logging.set_verbosity(tf.logging.INFO)

feature_names = [
    'SepalLength',
    'SepalWidth',
    'PetalLength',
    'PetalWidth'
]


def my_input_fn(is_shuffle=False, repeat_count=1):
    dataset = tf.data.TFRecordDataset(['csv.tfrecords'])  # filename is a list

    def parser(record):
        keys_to_features = {
            'label': tf.FixedLenFeature((), dtype=tf.int64),
            'features': tf.FixedLenFeature(shape=(4,), dtype=tf.float32),
        }
        parsed = tf.parse_single_example(record, keys_to_features)
        return parsed['features'], parsed['label']

    dataset = dataset.map(parser)
    if is_shuffle:
        # Randomizes input using a window of 256 elements (read into memory)
        dataset = dataset.shuffle(buffer_size=256)
    dataset = dataset.batch(32)
    dataset = dataset.repeat(repeat_count)
    iterator = dataset.make_one_shot_iterator()
    features, labels = iterator.get_next()
    return features, labels

feature_columns = [tf.feature_column.numeric_column(k) for k in feature_names]

classifier = tf.estimator.DNNClassifier(
    feature_columns=feature_columns,  # The input features to our model
    hidden_units=[10, 10],  # Two layers, each with 10 neurons
    n_classes=3,
    model_dir='iris_model_2')  # Path to where checkpoints etc are stored

classifier.train(input_fn=lambda: my_input_fn(is_shuffle=True, repeat_count=100))

它返回这个错误信息!

INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_model_dir': 'iris_model_2', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': None, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x1163d9f28>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}
INFO:tensorflow:Calling model_fn.
Traceback (most recent call last):
  File "/Users/huanghelin/Desktop/TFrecord/try2.py", line 45, in <module>
    classifier.train(input_fn=lambda: my_input_fn(is_shuffle=True, repeat_count=100))
  File "/Users/huanghelin/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 352, in train
    loss = self._train_model(input_fn, hooks, saving_listeners)
  File "/Users/huanghelin/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 812, in _train_model
    features, labels, model_fn_lib.ModeKeys.TRAIN, self.config)
  File "/Users/huanghelin/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 793, in _call_model_fn
    model_fn_results = self._model_fn(features=features, **kwargs)
  File "/Users/huanghelin/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/estimator/canned/dnn.py", line 354, in _model_fn
    config=config)
  File "/Users/huanghelin/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/estimator/canned/dnn.py", line 161, in _dnn_model_fn
    'Given type: {}'.format(type(features)))
ValueError: features should be a dictionary of `Tensor`s. Given type: <class 'tensorflow.python.framework.ops.Tensor'>

推荐答案

Google 开发者博客介绍 TensorFlow 功能列

这篇文章可以让你明白!我只是在 def parser(record) 中添加了 3 行.如下:<代码>my_features = {}对于 idx,enumerate(feature_names) 中的名称:my_features[names] = parsed['features'][idx]

This article can make you understand! I just add 3 lines in the def parser(record). as below: my_features = {} for idx, names in enumerate(feature_names): my_features[names] = parsed['features'][idx]

import tensorflow as tf

tf.logging.set_verbosity(tf.logging.INFO)

feature_names = [
    'SepalLength',
    'SepalWidth',
    'PetalLength',
    'PetalWidth'
]


def my_input_fn(is_shuffle=False, repeat_count=1):
    dataset = tf.data.TFRecordDataset(['csv.tfrecords'])  # filename is a list

    def parser(record):
        keys_to_features = {
            'label': tf.FixedLenFeature((), dtype=tf.int64),
            'features': tf.FixedLenFeature(shape=(4,), dtype=tf.float32),
        }
        parsed = tf.parse_single_example(record, keys_to_features)
        my_features = {}
        for idx, names in enumerate(feature_names):
            my_features[names] = parsed['features'][idx]
        return my_features, parsed['label']

    dataset = dataset.map(parser)
    if is_shuffle:
        # Randomizes input using a window of 256 elements (read into memory)
        dataset = dataset.shuffle(buffer_size=256)
    dataset = dataset.batch(32)
    dataset = dataset.repeat(repeat_count)
    iterator = dataset.make_one_shot_iterator()
    features, labels = iterator.get_next()
    return features, labels

feature_columns = [tf.feature_column.numeric_column(k) for k in feature_names]

classifier = tf.estimator.DNNClassifier(
    feature_columns=feature_columns,  # The input features to our model
    hidden_units=[10, 10],  # Two layers, each with 10 neurons
    n_classes=3,
    model_dir='lalalallal')  # Path to where checkpoints etc are stored

classifier.train(input_fn=lambda: my_input_fn(is_shuffle=True, repeat_count=100))

这篇关于tensorflow ValueError: features 应该是 `Tensor`s ​​的字典.给定类型:&lt;class 'tensorflow.python.framework.ops.Tensor'&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆