python - ValueError : features should be a dictionary of `Tensor` s. 给定类型:<class 'tensorflow.python.framework.ops.Tensor' >

标签 python tensorflow

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

然后,输出:

 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

最佳答案

tf.estimator.DNNClassifier 要求 eval_input_fn() 返回将特征名称映射到 tf.Tensor 对象的字典,而不是单个 tf.Tensor 对象。对 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()

关于python - ValueError : features should be a dictionary of `Tensor` s. 给定类型:<class 'tensorflow.python.framework.ops.Tensor' >,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50180886/

相关文章:

python - 是否可以在 scikit-learn 中打印决策树?

python - 在 aws elastic beanstalk 中部署 django 应用程序时出现错误

python - Keras NASNet 训练

python - Tensorflow 多变量逻辑回归不起作用

python - 是否有与 Haskell 'let' 等效的 Python

python - 如何将 bootstrap wysiwyg 添加到 flask 中?

python - 如何使用 .map (或其他)更改 Pandas 数据框中几列的值

TensorFlow 跨设备通信

tensorflow - tf.contrib.lookup.HashTable 问题

python - SSD MobileNet V2 FPNLite 320x320 中的 FPN 代表什么?