UnimplementedError(请参阅上面的回溯):不支持将字符串强制转换为float

时间:2018-12-04 14:38:25

标签: python string tensorflow numbers numeric

运行模拟后,我收到此消息。我不明白这是问题所在。你能帮我吗?

WARNING:tensorflow:From /usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/linear.py:469: multi_class_head (from tensorflow.contrib.learn.python.learn.estimators.head) is deprecated and will be removed in a future version.
Instructions for updating:
Please switch to tf.contrib.estimator.*_head.
WARNING:tensorflow:From /usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py:1180: __init__ (from tensorflow.contrib.learn.python.learn.estimators.estimator) is deprecated and will be removed in a future version.
Instructions for updating:
Please replace uses of any Estimator from tf.contrib.learn with an Estimator from tf.estimator.*
WARNING:tensorflow:From /usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py:428: __init__ (from tensorflow.contrib.learn.python.learn.estimators.run_config) is deprecated and will be removed in a future version.
Instructions for updating:
When switching to tf.estimator.Estimator, use tf.estimator.RunConfig instead.
INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_save_checkpoints_secs': 600, '_num_ps_replicas': 0, '_keep_checkpoint_max': 5, '_task_type': None, '_train_distribute': None, '_is_chief': True, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x7f9bbbfcd090>, '_tf_config': gpu_options {
  per_process_gpu_memory_fraction: 1.0
}
, '_protocol': None, '_save_checkpoints_steps': None, '_keep_checkpoint_every_n_hours': 10000, '_session_config': None, '_model_dir': '/tmp/tmpzv3Q2e', '_tf_random_seed': None, '_master': '', '_device_fn': None, '_num_worker_replicas': 0, '_task_id': 0, '_log_step_count_steps': 100, '_evaluation_master': '', '_eval_distribute': None, '_environment': 'local', '_save_summary_steps': 100}
WARNING:tensorflow:From /usr/local/lib/python2.7/dist-packages/tensorflow/contrib/layers/python/layers/feature_column.py:2391: calling sparse_feature_cross (from tensorflow.contrib.layers.python.ops.sparse_feature_cross_op) with hash_key=None is deprecated and will be removed after 2016-11-20.
Instructions for updating:
The default behavior of sparse_feature_cross is changing, the default
value for hash_key will change to SPARSE_FEATURE_CROSS_DEFAULT_HASH_KEY.
From that point on sparse_feature_cross will always use FingerprintCat64
to concatenate the feature fingerprints. And the underlying
_sparse_feature_cross_op.sparse_feature_cross operation will be marked
as deprecated.
WARNING:tensorflow:Casting <dtype: 'int64'> labels to bool.
WARNING:tensorflow:Casting <dtype: 'int64'> labels to bool.
WARNING:tensorflow:Trapezoidal rule is known to produce incorrect PR-AUCs; please switch to "careful_interpolation" instead.
WARNING:tensorflow:Trapezoidal rule is known to produce incorrect PR-AUCs; please switch to "careful_interpolation" instead.
WARNING:tensorflow:From /usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/head.py:678: __new__ (from tensorflow.contrib.learn.python.learn.estimators.model_fn) is deprecated and will be removed in a future version.
Instructions for updating:
When switching to tf.estimator.Estimator, use tf.estimator.EstimatorSpec. You can use the `estimator_spec` method to create an equivalent one.
INFO:tensorflow:Create CheckpointSaverHook.
INFO:tensorflow:Graph was finalized.
2018-12-04 15:12:52.326004: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
INFO:tensorflow:Saving checkpoints for 0 into /tmp/tmpzv3Q2e/model.ckpt.
2018-12-04 15:13:02.209850: W tensorflow/core/framework/op_kernel.cc:1250] OP_REQUIRES failed at cast_op.cc:123 : Unimplemented: Cast string to float is not supported
2018-12-04 15:13:02.209963: E tensorflow/core/common_runtime/executor.cc:623] Executor failed to create kernel. Unimplemented: Cast string to float is not supported
     [[{{node linear/linear/ToFloat_9}} = Cast[DstT=DT_FLOAT, SrcT=DT_STRING, Truncate=false, _device="/job:localhost/replica:0/task:0/device:CPU:0"](Const_10)]]
2018-12-04 15:13:02.229424: W tensorflow/core/framework/op_kernel.cc:1250] OP_REQUIRES failed at cast_op.cc:123 : Unimplemented: Cast string to float is not supported
2018-12-04 15:13:02.229522: E tensorflow/core/common_runtime/executor.cc:623] Executor failed to create kernel. Unimplemented: Cast string to float is not supported
     [[{{node linear/linear/ToFloat}} = Cast[DstT=DT_FLOAT, SrcT=DT_STRING, Truncate=false, _device="/job:localhost/replica:0/task:0/device:CPU:0"](Const_1)]]
Traceback (most recent call last):
  File "linear1.py", line 87, in <module>
    m.fit(input_fn=train_input_fn, steps=2000)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/util/deprecation.py", line 488, in new_func
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 525, in fit
    loss = self._train_model(input_fn=input_fn, hooks=hooks)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1095, in _train_model
    _, loss = mon_sess.run([model_fn_ops.train_op, model_fn_ops.loss])
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/monitored_session.py", line 671, in run
    run_metadata=run_metadata)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/monitored_session.py", line 1156, in run
    run_metadata=run_metadata)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/monitored_session.py", line 1255, in run
    raise six.reraise(*original_exc_info)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/monitored_session.py", line 1240, in run
    return self._sess.run(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/monitored_session.py", line 1312, in run
    run_metadata=run_metadata)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/monitored_session.py", line 1076, in run
    return self._sess.run(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 929, in run
    run_metadata_ptr)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1152, in _run
    feed_dict_tensor, options, run_metadata)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1328, in _do_run
    run_metadata)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1348, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.UnimplementedError: Cast string to float is not supported
     [[node linear/linear/ToFloat (defined at /usr/local/lib/python2.7/dist-packages/tensorflow/contrib/layers/python/layers/feature_column.py:1875)  = Cast[DstT=DT_FLOAT, SrcT=DT_STRING, Truncate=false, _device="/job:localhost/replica:0/task:0/device:CPU:0"](Const_1)]]

Caused by op u'linear/linear/ToFloat', defined at:
  File "linear1.py", line 87, in <module>
    m.fit(input_fn=train_input_fn, steps=2000)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/util/deprecation.py", line 488, in new_func
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 525, in fit
    loss = self._train_model(input_fn=input_fn, hooks=hooks)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1042, in _train_model
    model_fn_ops = self._get_train_ops(features, labels)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1265, in _get_train_ops
    return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.TRAIN)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1228, in _call_model_fn
    model_fn_results = self._model_fn(features, labels, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/estimators/linear.py", line 169, in _linear_model_fn
    scope=scope)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/layers/python/layers/feature_column_ops.py", line 495, in weighted_sum_from_feature_columns
    transformed_tensor = transformer.transform(column)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/layers/python/layers/feature_column_ops.py", line 848, in transform
    feature_column.insert_transformed_feature(self._columns_to_tensors)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/layers/python/layers/feature_column.py", line 1875, in insert_transformed_feature
    columns_to_tensors[self] = math_ops.to_float(input_tensor)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/math_ops.py", line 732, in to_float
    return cast(x, dtypes.float32, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/math_ops.py", line 677, in cast
    x = gen_math_ops.cast(x, base_type, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_math_ops.py", line 1659, in cast
    "Cast", x=x, DstT=DstT, Truncate=Truncate, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/util/deprecation.py", line 488, in new_func
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 3274, in create_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1770, in __init__
    self._traceback = tf_stack.extract_stack()

UnimplementedError (see above for traceback): Cast string to float is not supported
     [[node linear/linear/ToFloat (defined at /usr/local/lib/python2.7/dist-packages/tensorflow/contrib/layers/python/layers/feature_column.py:1875)  = Cast[DstT=DT_FLOAT, SrcT=DT_STRING, Truncate=false, _device="/job:localhost/replica:0/task:0/device:CPU:0"](Const_1)]]

这是我使用的代码

#!/usr/bin/env python 
# -*- coding: utf-8-*-

    from __future__ import absolute_import
    from __future__ import division
    from __future__ import print_function

    import pandas as pd
    import tensorflow as tf
    import tempfile
    import numpy as np
    import shutil


    tf.logging.set_verbosity(tf.logging.INFO)

    COLUMNS = ["TS", "DT", "SO", "TY", "JX", "CN", "SN", "RE", "TN", "PE", "GR", "PR", "KG", "ME", "MB", "MM", "NM", "TH", "MSN", "LE", "OF", "BL", "CK", "CR", "LCR"]``

    train_file = "/home/davide/Scrivania/NH3-TRAIN.csv"
    test_file = "/home/davide/Scrivania/NH3-TEST.csv"

    df_train = pd.read_csv(train_file, names=COLUMNS, skipinitialspace=True)
    df_test = pd.read_csv(test_file, names=COLUMNS, skipinitialspace=True)
    LABEL10_COLUMN = "label10"
    df_train[LABEL10_COLUMN] = (df_train["CK"].apply(lambda x: "SI" in x)).astype(int)
    df_test[LABEL10_COLUMN] = (df_test["CK"].apply(lambda x: "SI" in x)).astype(int)
    CATEGORICAL_COLUMNS = ["SO", "TY", "JX", "CN", "SN", "RE", "TN", "MSN", "LE", "OF", "BL", "CK", "CR", "LCR"]
    CONTINUOUS_COLUMNS = ["TS", "DT", "PE", "GR", "PR", "KG", "ME", "MB", "MM", "NM", "TH"]

    def input_fn(df):
       continuous_cols = {k: tf.constant(df[k].values)
                          for k in CONTINUOUS_COLUMNS}
       categorical_cols = {k: tf.SparseTensor(
            indices=[[i, 0] for i in range(df[k].size)],
            values=df[k].astype(str).values,
            dense_shape=[df[k].size, 1])
                           for k in CATEGORICAL_COLUMNS}
       feature_cols = dict(continuous_cols.items() + categorical_cols.items())
       label10 = tf.constant(df[LABEL10_COLUMN].values)
       return feature_cols, label10


    def train_input_fn():
       return input_fn(df_train)

    def eval_input_fn():
       return input_fn(df_test)


    TS = tf.contrib.layers.real_valued_column("TS")
    DT = tf.contrib.layers.real_valued_column("DT")
    SO = tf.contrib.layers.sparse_column_with_hash_bucket("SO", hash_bucket_size=200, dtype=tf.string)
    TY = tf.contrib.layers.sparse_column_with_keys(column_name='TY', keys=["ALM","NR","ACK","LLL","HHH","HTRP","IOP","LTRP"],default_value=-1, combiner='sum', dtype=tf.string)
    JX = tf.contrib.layers.sparse_column_with_hash_bucket("JX", hash_bucket_size=70)
    CN = tf.contrib.layers.sparse_column_with_keys(column_name="CN", keys=["ALM","NR","ACK","LLL","HHH","HTRP","IOP","LTRP"],default_value=-1, combiner='sum', dtype=tf.string)
    SN = tf.contrib.layers.sparse_column_with_keys(column_name="SN", keys=["ALM","NR","ACK","LLL","HHH","HTRP","IOP","LTRP"],default_value=-1, combiner='sum', dtype=tf.string)
    RE = tf.contrib.layers.sparse_column_with_keys(column_name="RE", keys=["ZERO","UNO"],default_value=-1, combiner='sum', dtype=tf.string)
    TN = tf.contrib.layers.sparse_column_with_hash_bucket("TN", hash_bucket_size=200)
    PE = tf.contrib.layers.real_valued_column("PE")
    GR = tf.contrib.layers.real_valued_column("GR")
    PR = tf.contrib.layers.real_valued_column("PR")
    KG = tf.contrib.layers.real_valued_column("KG")
    ME = tf.contrib.layers.real_valued_column("ME")
    MB = tf.contrib.layers.real_valued_column("MB")
    MM = tf.contrib.layers.real_valued_column("MM")
    NM = tf.contrib.layers.real_valued_column("NM")
    TH = tf.contrib.layers.real_valued_column("TH")
    MSN = tf.contrib.layers.sparse_column_with_keys(column_name="MSN", keys=["ALM","NR","ACK","LLL","HHH","Na","HTRP","IOP","LTRP"],default_value=-1, combiner='sum', dtype=tf.string)
    LE = tf.contrib.layers.sparse_column_with_keys(column_name="LE", keys=["ZERO","DUE"],default_value=-1, combiner='sum', dtype=tf.string)
    OF = tf.contrib.layers.sparse_column_with_keys(column_name="OF", keys=["ZERO","UNO"],default_value=-1, combiner='sum', dtype=tf.string)
    BL = tf.contrib.layers.sparse_column_with_keys(column_name="BL", keys=["ZERO","UNO"],default_value=-1, combiner='sum', dtype=tf.string)
    CK = tf.contrib.layers.sparse_column_with_keys(column_name="CK", keys=["SI","NO", "Na"],default_value=-1, combiner='sum', dtype=tf.string)
    CR = tf.contrib.layers.sparse_column_with_keys(column_name="CR", keys=["SI","NO","Na"],default_value=-1, combiner='sum', dtype=tf.string)
    LCR = tf.contrib.layers.sparse_column_with_keys(column_name="LCR", keys=["SI","NO","Na"],default_value=-1, combiner='sum', dtype=tf.string)
    COND = tf.contrib.layers.crossed_column([SO, TN], hash_bucket_size=int(1e5))
    TYPE = tf.contrib.layers.crossed_column([TY, JX, CN, SN, MSN], hash_bucket_size=int(1e6))
    ALARM = tf.contrib.layers.crossed_column([LE, OF, BL], hash_bucket_size=10)

    model_dir = tempfile.mkdtemp()
    m = tf.contrib.learn.LinearClassifier(
       feature_columns=[TS, DT, SO, TY, JX, CN, SN, RE, TN, PE, GR, PR, KG, ME, MB, MM, NM, TH, MSN, LE, OF, BL, CR, LCR, COND, TYPE, ALARM],
          optimizer=tf.train.FtrlOptimizer(
          learning_rate=0.1,
          l1_regularization_strength=0.001),
          model_dir=model_dir)

    m.fit(input_fn=train_input_fn, steps=2000)

    results = m.evaluate(input_fn=eval_input_fn, steps=1)

    for key in sorted(results):
        print("%s: %s" % (key, results[key]))

    predictions=list(m.predict_proba(input_fn=eval_input_fn))

    print("\n".join(map(str, predictions)))

我已经看到过类似tf.strings.to_number之类的东西,可以将字符串转换为浮点数,但是没有看到可以帮助我编辑此代码的东西。我没有安装允许我使用GPU的东西。 谢谢

0 个答案:

没有答案