Tensorflow-模型训练与“不支持将字符串转换为浮点数”错误

时间:2019-04-27 19:11:26

标签: python numpy tensorflow machine-learning neural-network

问题

尝试训练Tensorflow模型时,即使我将所有列类型从int64转换为string /,也会弹出错误消息,提示“ 不支持将字符串转换为float ”。对象

我的数据框列的内容是键(因此,最初是数字),它们指向一个类值,如以下所示:https://pastebin.com/ui7dex3A

使用Jupyter Notebook。

==============

上下文

这是我的数据集:dataset

这是我对数据集进行的转换以转换为字符串: dataset to string

然后我用对象列创建了tf.feature_column.categorical_column_with_hash_bucket,并使用int64列创建了tf.feature_column.numeric_column

一些重要版本(我正在使用 tfdl_env 文件): -numpy = 1.13.1 = py35_0 -tensorflow == 1.3.0 -tensorflow-张量板== 0.1.7 -python = 3.5.4 = 0

==============

代码

创建火车组的代码:

x_data = dataInitial.drop('HUMANDMG',axis=1)
y_labels = dataInitial['HUMANDMG']
X_train, X_test, y_train, y_test = train_test_split(x_data,y_labels,test_size=0.3,random_state=101)

创建列的代码:

frstham = tf.feature_column.categorical_column_with_hash_bucket("FRSTHARM", hash_bucket_size=1000)
locfsthrm = tf.feature_column.categorical_column_with_hash_bucket("LOCFSTHRM", hash_bucket_size=1000)
crcomnr = tf.feature_column.categorical_column_with_hash_bucket("CRCOMNNR", hash_bucket_size=1000)
majcse = tf.feature_column.categorical_column_with_hash_bucket("MAJCSE", hash_bucket_size=1000)
drugalc = tf.feature_column.categorical_column_with_hash_bucket("DRUGALC", hash_bucket_size=1000)
ecntcrc = tf.feature_column.categorical_column_with_hash_bucket("ECNTCRC", hash_bucket_size=1000)
light = tf.feature_column.categorical_column_with_hash_bucket("LIGHT", hash_bucket_size=1000)
csrfcnd = tf.feature_column.categorical_column_with_hash_bucket("CSRFCND", hash_bucket_size=1000)
weather = tf.feature_column.categorical_column_with_hash_bucket("WEATHER", hash_bucket_size=1000)
rcntcrc = tf.feature_column.categorical_column_with_hash_bucket("RCNTCRC", hash_bucket_size=1000)
rdtyp = tf.feature_column.categorical_column_with_hash_bucket("RDTYP", hash_bucket_size=1000)
paved = tf.feature_column.categorical_column_with_hash_bucket("PAVED", hash_bucket_size=1000)
csev = tf.feature_column.categorical_column_with_hash_bucket("CSEV", hash_bucket_size=1000)
crashdatehour = tf.feature_column.categorical_column_with_hash_bucket("CRASH_DATEHOUR", hash_bucket_size=1000)
vehicles = tf.feature_column.numeric_column("VEHICLES")
toccupants = tf.feature_column.numeric_column("TOCCUPANTS")

用于创建输入函数和模型的代码:

feat_cols = [frstham,locfsthrm,crcomnr,majcse,drugalc,ecntcrc,light,csrfcnd,weather,rcntcrc,rdtyp,paved,
            csev,crashdatehour,vehicles,toccupants]

input_func=tf.estimator.inputs.pandas_input_fn(x=X_train,y=y_train,batch_size=1000,num_epochs=None,shuffle=True)

model = tf.estimator.LinearClassifier(feature_columns=feat_cols)
model.train(input_fn=input_func,steps=5000)

错误

这是我收到的错误日志,而不是经过良好的培训:

INFO:tensorflow:Create CheckpointSaverHook.
INFO:tensorflow:Error reported to Coordinator: <class 'SystemError'>, <built-in function TF_Run> returned a result with an error set
---------------------------------------------------------------------------
UnimplementedError                        Traceback (most recent call last)
~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1326     try:
-> 1327       return fn(*args)
   1328     except errors.OpError as e:

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1305                                    feed_dict, fetch_list, target_list,
-> 1306                                    status, run_metadata)
   1307 

~/anaconda2/envs/tfdeeplearning/lib/python3.5/contextlib.py in __exit__(self, type, value, traceback)
     65             try:
---> 66                 next(self.gen)
     67             except StopIteration:

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py in raise_exception_on_not_ok_status()
    465           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466           pywrap_tensorflow.TF_GetCode(status))
    467   finally:

UnimplementedError: Cast string to float is not supported
     [[Node: linear/head/ToFloat = Cast[DstT=DT_FLOAT, SrcT=DT_STRING, _device="/job:localhost/replica:0/task:0/cpu:0"](linear/head/labels)]]

During handling of the above exception, another exception occurred:

UnimplementedError                        Traceback (most recent call last)
~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/estimator/estimator.py in _train_model(self, input_fn, hooks)
    685         while not mon_sess.should_stop():
--> 686           _, loss = mon_sess.run([estimator_spec.train_op, estimator_spec.loss])
    687       return loss

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/training/monitored_session.py in run(self, fetches, feed_dict, options, run_metadata)
    517                           options=options,
--> 518                           run_metadata=run_metadata)
    519 

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/training/monitored_session.py in run(self, fetches, feed_dict, options, run_metadata)
    861                               options=options,
--> 862                               run_metadata=run_metadata)
    863       except _PREEMPTION_ERRORS as e:

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/training/monitored_session.py in run(self, *args, **kwargs)
    817   def run(self, *args, **kwargs):
--> 818     return self._sess.run(*args, **kwargs)
    819 

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/training/monitored_session.py in run(self, fetches, feed_dict, options, run_metadata)
    971                                   options=options,
--> 972                                   run_metadata=run_metadata)
    973 

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/training/monitored_session.py in run(self, *args, **kwargs)
    817   def run(self, *args, **kwargs):
--> 818     return self._sess.run(*args, **kwargs)
    819 

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    894       result = self._run(None, fetches, feed_dict, options_ptr,
--> 895                          run_metadata_ptr)
    896       if run_metadata:

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1123       results = self._do_run(handle, final_targets, final_fetches,
-> 1124                              feed_dict_tensor, options, run_metadata)
   1125     else:

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1320       return self._do_call(_run_fn, self._session, feeds, fetches, targets,
-> 1321                            options, run_metadata)
   1322     else:

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1339           pass
-> 1340       raise type(e)(node_def, op, message)
   1341 

UnimplementedError: Cast string to float is not supported
     [[Node: linear/head/ToFloat = Cast[DstT=DT_FLOAT, SrcT=DT_STRING, _device="/job:localhost/replica:0/task:0/cpu:0"](linear/head/labels)]]

Caused by op 'linear/head/ToFloat', defined at:
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/ipykernel/kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tornado/ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
    handler(stream, idents, msg)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/ipykernel/zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2698, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2808, in run_ast_nodes
    if self.run_code(code, result):
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-420-ff68dadd2b4b>", line 1, in <module>
    model.train(input_fn=input_func,steps=5000)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/estimator/estimator.py", line 241, in train
    loss = self._train_model(input_fn=input_fn, hooks=hooks)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/estimator/estimator.py", line 630, in _train_model
    model_fn_lib.ModeKeys.TRAIN)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/estimator/estimator.py", line 615, in _call_model_fn
    model_fn_results = self._model_fn(features=features, **kwargs)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/estimator/canned/linear.py", line 222, in _model_fn
    config=config)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/estimator/canned/linear.py", line 102, in _linear_model_fn
    logits=logits)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/estimator/canned/head.py", line 632, in create_estimator_spec
    labels = math_ops.to_float(labels)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/ops/math_ops.py", line 765, in to_float
    return cast(x, dtypes.float32, name=name)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/ops/math_ops.py", line 716, in cast
    return gen_math_ops.cast(x, base_type, name=name)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/ops/gen_math_ops.py", line 450, in cast
    result = _op_def_lib.apply_op("Cast", x=x, DstT=DstT, name=name)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 2630, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/Users/brunoteixeira/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1204, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

UnimplementedError (see above for traceback): Cast string to float is not supported
     [[Node: linear/head/ToFloat = Cast[DstT=DT_FLOAT, SrcT=DT_STRING, _device="/job:localhost/replica:0/task:0/cpu:0"](linear/head/labels)]]


During handling of the above exception, another exception occurred:

SystemError                               Traceback (most recent call last)
<ipython-input-420-ff68dadd2b4b> in <module>()
----> 1 model.train(input_fn=input_func,steps=5000)

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/estimator/estimator.py in train(self, input_fn, hooks, steps, max_steps)
    239       hooks.append(training.StopAtStepHook(steps, max_steps))
    240 
--> 241     loss = self._train_model(input_fn=input_fn, hooks=hooks)
    242     logging.info('Loss for final step: %s.', loss)
    243     return self

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/estimator/estimator.py in _train_model(self, input_fn, hooks)
    684         loss = None
    685         while not mon_sess.should_stop():
--> 686           _, loss = mon_sess.run([estimator_spec.train_op, estimator_spec.loss])
    687       return loss
    688 

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/training/monitored_session.py in __exit__(self, exception_type, exception_value, traceback)
    532     if exception_type in [errors.OutOfRangeError, StopIteration]:
    533       exception_type = None
--> 534     self._close_internal(exception_type)
    535     # __exit__ should return True to suppress an exception.
    536     return exception_type is None

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/training/monitored_session.py in _close_internal(self, exception_type)
    567     finally:
    568       try:
--> 569         self._sess.close()
    570       finally:
    571         self._sess = None

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/training/monitored_session.py in close(self)
    809     if self._sess:
    810       try:
--> 811         self._sess.close()
    812       except _PREEMPTION_ERRORS:
    813         pass

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/training/monitored_session.py in close(self)
    906       self._coord.join(
    907           stop_grace_period_secs=self._stop_grace_period_secs,
--> 908           ignore_live_threads=True)
    909     finally:
    910       try:

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/training/coordinator.py in join(self, threads, stop_grace_period_secs, ignore_live_threads)
    387       self._registered_threads = set()
    388       if self._exc_info_to_raise:
--> 389         six.reraise(*self._exc_info_to_raise)
    390       elif stragglers:
    391         if ignore_live_threads:

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/six.py in reraise(tp, value, tb)
    684         if value.__traceback__ is not tb:
    685             raise value.with_traceback(tb)
--> 686         raise value
    687 
    688 else:

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/estimator/inputs/queues/feeding_queue_runner.py in _run(self, sess, enqueue_op, feed_fn, coord)
     92         try:
     93           feed_dict = None if feed_fn is None else feed_fn()
---> 94           sess.run(enqueue_op, feed_dict=feed_dict)
     95         except (errors.OutOfRangeError, errors.CancelledError):
     96           # This exception indicates that a queue was closed.

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    893     try:
    894       result = self._run(None, fetches, feed_dict, options_ptr,
--> 895                          run_metadata_ptr)
    896       if run_metadata:
    897         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1122     if final_fetches or final_targets or (handle and feed_dict_tensor):
   1123       results = self._do_run(handle, final_targets, final_fetches,
-> 1124                              feed_dict_tensor, options, run_metadata)
   1125     else:
   1126       results = []

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1319     if handle is None:
   1320       return self._do_call(_run_fn, self._session, feeds, fetches, targets,
-> 1321                            options, run_metadata)
   1322     else:
   1323       return self._do_call(_prun_fn, self._session, handle, feeds, fetches)

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1325   def _do_call(self, fn, *args):
   1326     try:
-> 1327       return fn(*args)
   1328     except errors.OpError as e:
   1329       message = compat.as_text(e.message)

~/anaconda2/envs/tfdeeplearning/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1304           return tf_session.TF_Run(session, options,
   1305                                    feed_dict, fetch_list, target_list,
-> 1306                                    status, run_metadata)
   1307 
   1308     def _prun_fn(session, handle, feed_dict, fetch_list):

SystemError: <built-in function TF_Run> returned a result with an error set

有什么想法吗?谢谢!

0 个答案:

没有答案