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



tensorflow version 1.7 蟒蛇 3.5 我的代码:

import tensorflow as tf
import pandas as pd
TRAIN_URL = 'D:数据集FlowerClassificationiris_training.csv'
TEST_URL = 'D:数据集FlowerClassificationiris_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:UsersOliverAppDataLocalTemptmps6rhm21o
2018-05-05 01:27:15.152341: I C:tf_jenkinsworkspacerel-winMwindowsPY35tensorflowcoreplatformcpu_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:UsersOliverAppDataRoamingPythonPython35site-packagestensorflowpythonestimatorestimator.py", line 414, in evaluate
name=name)
File "C:UsersOliverAppDataRoamingPythonPython35site-packagestensorflowpythonestimatorestimator.py", line 919, in _evaluate_model
features, labels, model_fn_lib.ModeKeys.EVAL, self.config)
File "C:UsersOliverAppDataRoamingPythonPython35site-packagestensorflowpythonestimatorestimator.py", line 793, in _call_model_fn
model_fn_results = self._model_fn(features=features, **kwargs)
File "C:UsersOliverAppDataRoamingPythonPython35site-packagestensorflowpythonestimatorcanneddnn.py", line 354, in _model_fn
config=config)
File "C:UsersOliverAppDataRoamingPythonPython35site-packagestensorflowpythonestimatorcanneddnn.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()

最新更新