简体   繁体   English

ValueError:特征应该是`Tensor`的字典。 给定类型: <class 'tensorflow.python.framework.ops.Tensor'>

[英]ValueError: features should be a dictionary of `Tensor`s. Given type: <class 'tensorflow.python.framework.ops.Tensor'>

tensorflow version 1.7 python 3.5 my code: tensorflow版本1.7 python 3.5我的代码:

import tensorflow as tf
import pandas as pd

TRAIN_URL = 'D:\数据集\FlowerClassification\iris_training.csv'
TEST_URL = 'D:\数据集\FlowerClassification\iris_test.csv'

CSV_COLUMN_NAMES = ['SepalLength', 'SepalWidth',
                'PetalLength', 'PetalWidth', 'Species']


def load_data(label_name='Species'):

    train = pd.read_csv(filepath_or_buffer=TRAIN_URL,
                    names=CSV_COLUMN_NAMES,
                    header=0)
    train_features = train
    train_labels = train.pop(label_name)

    test = pd.read_csv(filepath_or_buffer=TEST_URL,
                   names=CSV_COLUMN_NAMES,
                   header=0)
    test_features = test
    test_labels = test.pop(label_name)

    return (train_features, train_labels), (test_features, test_labels)


def train_input_fn(features, labels, batch_size):
    dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))
    dataset = dataset.shuffle(buffer_size=120).repeat(count=None).batch(batch_size)
    return dataset.make_one_shot_iterator().get_next()


def eval_input_fn(features, labels=None, batch_size=None):

    if labels is None:
        inputs = features
    else:
        inputs = (features, labels)

    dataset = tf.data.Dataset.from_tensor_slices(inputs)

    assert batch_size is not None, 'batch_size must not None'
    dataset = dataset.batch(batch_size)

    return dataset.make_one_shot_iterator().get_next()


(train_features, train_labels), (test_features, test_labels) = load_data()

my_features_columns = []
for key in train_features.keys():
    my_features_columns.append(tf.feature_column.numeric_column(key=key))

classifier = tf.estimator.DNNClassifier(
    feature_columns=my_features_columns,
    hidden_units=[10, 10],
    n_classes=3
)

classifier.train(
    input_fn=lambda: train_input_fn(train_features, train_labels, 100),
    steps=1000
)

eval_result = classifier.evaluate(
    input_fn=lambda: eval_input_fn(test_features, test_labels, 30))
print('\nTest set accuracy: {accuracy:0.3f}\n'.format(**eval_result))

then, the outputs: 然后,输出:

 WARNING:tensorflow:Using temporary folder as model directory: C:\Users\Oliver\AppData\Local\Temp\tmps6rhm21o
    2018-05-05 01:27:15.152341: I C:\tf_jenkins\workspace\rel-win\M\windows\PY\35\tensorflow\core\platform\cpu_feature_guard.cc:140] Your CPU supports      instructions that this TensorFlow binary was not compiled to use: AVX2
    Traceback (most recent call last):
       File "G:/Python/Tensorflow/FlowerClassification.py", line 71, in <module>
       input_fn=lambda: eval_input_fn(test_features, test_labels, 30))
       File "C:\Users\Oliver\AppData\Roaming\Python\Python35\site-packages\tensorflow\python\estimator\estimator.py", line 414, in evaluate
        name=name)
      File "C:\Users\Oliver\AppData\Roaming\Python\Python35\site-packages\tensorflow\python\estimator\estimator.py", line 919, in _evaluate_model
        features, labels, model_fn_lib.ModeKeys.EVAL, self.config)
      File "C:\Users\Oliver\AppData\Roaming\Python\Python35\site-packages\tensorflow\python\estimator\estimator.py", line 793, in _call_model_fn
        model_fn_results = self._model_fn(features=features, **kwargs)
      File "C:\Users\Oliver\AppData\Roaming\Python\Python35\site-packages\tensorflow\python\estimator\canned\dnn.py", line 354, in _model_fn
        config=config)
      File "C:\Users\Oliver\AppData\Roaming\Python\Python35\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'>

Process finished with exit code 1

The tf.estimator.DNNClassifier requires that eval_input_fn() return a dictionary mapping feature names to tf.Tensor objects, rather than a single tf.Tensor object. tf.estimator.DNNClassifier要求eval_input_fn()返回将特征名称映射到tf.Tensor对象而不是单个tf.Tensor对象的tf.Tensor The following tweak to eval_input_fn() should work: eval_input_fn()的以下调整应该起作用:

def eval_input_fn(features, labels=None, batch_size=None):

    if labels is None:
        inputs = dict(features)  # Convert the DataFrame to a dictionary.
    else:
        inputs = (dict(features), labels)  # Convert the DataFrame to a dictionary.

    dataset = tf.data.Dataset.from_tensor_slices(inputs)

    assert batch_size is not None, 'batch_size must not None'
    dataset = dataset.batch(batch_size)

    return dataset.make_one_shot_iterator().get_next()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ValueError:特征应该是一个“张量”的字典。 给定类型:<class 'tensorflow.python.data.ops.dataset_ops.RepeatDataset'> - ValueError: features should be a dictionary of `Tensor`s. Given type: <class 'tensorflow.python.data.ops.dataset_ops.RepeatDataset'> Tensorflow Batchnormalization - 类型错误:轴必须是整数或列表,类型给定:<class 'tensorflow.python.framework.ops.Tensor'> - Tensorflow Batchnormalization - TypeError: axis must be int or list, type given: <class 'tensorflow.python.framework.ops.Tensor'> ValueError:特征应该是一个“张量”的字典。 给定类型:<class 'NoneType'> - ValueError: features should be a dictionary of `Tensor`s. Given type: <class 'NoneType'> TensorFlow-ValueError:功能应该是`Tensor`s的字典 - TensorFlow - ValueError: features should be a dictionary of `Tensor`s 如何在 Tensorflow 2.0 中打印 tensorflow.python.framework.ops.Tensor 的值? - How to print value of tensorflow.python.framework.ops.Tensor in Tensorflow 2.0? Unable to convert tensorflow.python.framework.ops.Tensor object to numpy array for passoing it in sklearn.metrics.cohen_kappa_score function - Unable to convert tensorflow.python.framework.ops.Tensor object to numpy array for passoing it in sklearn.metrics.cohen_kappa_score function 类型错误:<tf.tensor: shape ...> 有类型<class 'tensorflow.python.framework.ops.eagertensor'> ,但预期其中之一:(<class 'int'> ,)</class></class></tf.tensor:> - TypeError: <tf.Tensor: shape ... > has type <class 'tensorflow.python.framework.ops.EagerTensor'>, but expected one of: (<class 'int'>,) Python-功能应该是具有高级TF API的Tensor字典 - Python - features should be a dictionary of `Tensor`s with high level tf APIs Tensorflow TypeError: 无法转换 object 类型<class 'tensorflow.python.framework.sparse_tensor.sparsetensor'>张量</class> - Tensorflow TypeError: Failed to convert object of type <class 'tensorflow.python.framework.sparse_tensor.SparseTensor'> to Tensor ResNet50:TypeError:无法转换类型的 object<class 'tensorflow.python.framework.sparse_tensor.sparsetensor'> 张量</class> - ResNet50 : TypeError: Failed to convert object of type <class 'tensorflow.python.framework.sparse_tensor.SparseTensor'> to Tensor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM