Tensorflow错误(Python):无法将类型<class'dict'=“”>的对象转换为Tensor

时间:2019-01-06 23:59:17

标签: python pandas tensorflow

作为Udemy课程的一部分,我正在尝试创建一个线性分类器,该分类器将预测一个人的年收入是否大于或小于5万。不幸的是,我收到了这个tensorflow错误:----------------------------------------------------------- TypeError Traceback (most recent call last) /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/framework/tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape) 526 try: --> 527 str_values = [compat.as_bytes(x) for x in proto_values] 528 except TypeError: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/framework/tensor_util.py in <listcomp>(.0) 526 try: --> 527 str_values = [compat.as_bytes(x) for x in proto_values] 528 except TypeError: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/util/compat.py in as_bytes(bytes_or_text, encoding) 60 raise TypeError('Expected binary or unicode string, got %r' % ---> 61 (bytes_or_text,)) 62 TypeError: Expected binary or unicode string, got {'income_bracket': <tf.Tensor 'random_shuffle_queue_DequeueUpTo:14' shape=(?,) dtype=int64>} During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-90-56c52ca792f4> in <module> ----> 1 model.train(input_fn=input_func, steps=5000) /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py in train(self, input_fn, hooks, steps, max_steps, saving_listeners) 352 353 saving_listeners = _check_listeners_type(saving_listeners) --> 354 loss = self._train_model(input_fn, hooks, saving_listeners) 355 logging.info('Loss for final step: %s.', loss) 356 return self /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py in _train_model(self, input_fn, hooks, saving_listeners) 1205 return self._train_model_distributed(input_fn, hooks, saving_listeners) 1206 else: -> 1207 return self._train_model_default(input_fn, hooks, saving_listeners) 1208 1209 def _train_model_default(self, input_fn, hooks, saving_listeners): /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py in _train_model_default(self, input_fn, hooks, saving_listeners) 1235 worker_hooks.extend(input_hooks) 1236 estimator_spec = self._call_model_fn( -> 1237 features, labels, model_fn_lib.ModeKeys.TRAIN, self.config) 1238 global_step_tensor = training_util.get_global_step(g) 1239 return self._train_with_estimator_spec(estimator_spec, worker_hooks, /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py in _call_model_fn(self, features, labels, mode, config) 1193 1194 logging.info('Calling model_fn.') -> 1195 model_fn_results = self._model_fn(features=features, **kwargs) 1196 logging.info('Done calling model_fn.') 1197 /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/estimator/canned/linear.py in _model_fn(features, labels, mode, config) 382 partitioner=partitioner, 383 config=config, --> 384 sparse_combiner=sparse_combiner) 385 386 super(LinearClassifier, self).__init__( /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/estimator/canned/linear.py in _linear_model_fn(features, labels, mode, head, feature_columns, optimizer, partitioner, config, sparse_combiner) 213 labels=labels, 214 optimizer=optimizer, --> 215 logits=logits) 216 217 /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/estimator/canned/head.py in create_estimator_spec(self, features, mode, logits, labels, optimizer, train_op_fn, regularization_losses) 237 self._create_tpu_estimator_spec( 238 features, mode, logits, labels, optimizer, train_op_fn, --> 239 regularization_losses)) 240 return tpu_estimator_spec.as_estimator_spec() 241 except NotImplementedError: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/estimator/canned/head.py in _create_tpu_estimator_spec(self, features, mode, logits, labels, optimizer, train_op_fn, regularization_losses) 1207 (training_loss, unreduced_loss, weights, processed_labels) = ( 1208 self.create_loss( -> 1209 features=features, mode=mode, logits=logits, labels=labels)) 1210 if regularization_losses: 1211 regularization_loss = math_ops.add_n(regularization_losses) /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/estimator/canned/head.py in create_loss(***failed resolving arguments***) 1108 logits = ops.convert_to_tensor(logits) 1109 labels = _check_dense_labels_match_logits_and_reshape( -> 1110 labels=labels, logits=logits, expected_labels_dimension=1) 1111 if self._label_vocabulary is not None: 1112 labels = lookup_ops.index_table_from_tensor( /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/estimator/canned/head.py in _check_dense_labels_match_logits_and_reshape(labels, logits, expected_labels_dimension) 303 'returns labels.') 304 with ops.name_scope(None, 'labels', (labels, logits)) as scope: --> 305 labels = sparse_tensor.convert_to_tensor_or_sparse_tensor(labels) 306 if isinstance(labels, sparse_tensor.SparseTensor): 307 raise ValueError( /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/framework/sparse_tensor.py in convert_to_tensor_or_sparse_tensor(value, dtype, name) 277 return value 278 return ops.internal_convert_to_tensor( --> 279 value, dtype=dtype, name=name) 280 281 /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in internal_convert_to_tensor(value, dtype, name, as_ref, preferred_dtype, ctx) 1144 1145 if ret is None: -> 1146 ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) 1147 1148 if ret is NotImplemented: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/framework/constant_op.py in _constant_tensor_conversion_function(v, dtype, name, as_ref) 227 as_ref=False): 228 _ = as_ref --> 229 return constant(v, dtype=dtype, name=name) 230 231 /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/framework/constant_op.py in constant(value, dtype, shape, name, verify_shape) 206 tensor_value.tensor.CopyFrom( 207 tensor_util.make_tensor_proto( --> 208 value, dtype=dtype, shape=shape, verify_shape=verify_shape)) 209 dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype) 210 const_tensor = g.create_op( /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/framework/tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape) 529 raise TypeError("Failed to convert object of type %s to Tensor. " 530 "Contents: %s. Consider casting elements to a " --> 531 "supported type." % (type(values), values)) 532 tensor_proto.string_val.extend(str_values) 533 return tensor_proto TypeError: Failed to convert object of type <class 'dict'> to Tensor. Contents: {'income_bracket': <tf.Tensor 'random_shuffle_queue_DequeueUpTo:14' shape=(?,) dtype=int64>}. Consider casting elements to a supported type.

这是错误:

import tensorflow as tf
import pandas as pd
from sklearn.model_selection import train_test_split
census_data = pd.read_csv("census_data.csv")
census_data["income_bracket"] = 
census_data["income_bracket"].apply(lambda x: 0 if x==" <=50K" else 1)
y_census_data = pd.DataFrame(census_data["income_bracket"])
x_census_data = census_data.drop("income_bracket", axis=1)
test_data = {
    "y":None,
    "x":None
}

train_data = {
    "y":None,
    "x":None
}
train_data["x"], test_data["x"], train_data["y"], test_data["y"] = train_test_split(
    x_census_data, 
    y_census_data,  
    test_size=0.33
)
def feature_column_prefill(col_name):
    return_val = 
tf.feature_column.categorical_column_with_vocabulary_list(
    col_name, 
    list(census_data[col_name].unique())
)
return return_val
workclass = feature_column_prefill("workclass")
education = feature_column_prefill("education")
marital_status = feature_column_prefill("marital_status")
occupation = feature_column_prefill("occupation")
relationship = feature_column_prefill("relationship")
race = feature_column_prefill("race")
gender = feature_column_prefill("gender")
native_country = feature_column_prefill("native_country")

age = tf.feature_column.numeric_column("age")
education_num = tf.feature_column.numeric_column("education_num")
capital_gain = tf.feature_column.numeric_column("capital_gain")
capital_loss = tf.feature_column.numeric_column("capital_loss")
hours_per_week = tf.feature_column.numeric_column("hours_per_week")
feat_cols = [ age, workclass, education, education_num, marital_status, 
 occupation, relationship, race, gender, capital_gain, capital_loss, 
 hours_per_week, native_country ]
input_func = tf.estimator.inputs.pandas_input_fn(
    x=train_data["x"],
    y=train_data["y"],
    batch_size=10, 
    num_epochs=1000, 
    shuffle=True
)
model = tf.estimator.LinearClassifier(
    feature_columns=feat_cols, 
    n_classes=2
)
model.train(input_fn=input_func, steps=5000) 

这是我的代码:

28, Private, Bachelors,13, Married-civ-spouse, Prof-specialty, Wife, Black, Female,0,0,40, Cuba, <=50K
37, Private, Masters,14, Married-civ-spouse, Exec-managerial, Wife, White, Female,0,0,40, United-States, <=50K
49, Private, 9th,5, Married-spouse-absent, Other-service, Not-in-family, Black, Female,0,0,16, Jamaica, <=50K
52, Self-emp-not-inc, HS-grad,9, Married-civ-spouse, Exec-managerial, Husband, White, Male,0,0,45, United-States, >50K
31, Private, Masters,14, Never-married, Prof-specialty, Not-in-family, White, Female,14084,0,50, United-States, >50K
42, Private, Bachelors,13, Married-civ-spouse, Exec-managerial, Husband, White, Male,5178,0,40, United-States, >50K
37, Private, Some-college,10, Married-civ-spouse, Exec-managerial, Husband, Black, Male,0,0,80, United-States, >50K

这是csv文件的一小部分样本:

{{1}}

我很困,所以如果有人能帮上忙,那就太好了。非常感谢。

我希望模型能够开始训练,但是,我得到了错误。

0 个答案:

没有答案