【问题标题】:Tensorflow - ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float)Tensorflow - ValueError:无法将 NumPy 数组转换为张量(不支持的对象类型浮点数)
【发布时间】:2020-02-26 09:14:12
【问题描述】:

上一个问题的继续:Tensorflow - TypeError: 'int' object is not iterable

我的训练数据是一个列表列表,每个列表包含 1000 个浮点数。例如x_train[0] =

[0.0, 0.0, 0.1, 0.25, 0.5, ...]

这是我的模型:

model = Sequential()

model.add(LSTM(128, activation='relu',
               input_shape=(1000, 1), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(128, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(1, activation='sigmoid'))

opt = tf.keras.optimizers.Adam(lr=1e-3, decay=1e-5)

model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=3, validation_data=(x_test, y_test))

这是我得到的错误:

Traceback (most recent call last):
      File "C:\Users\bencu\Desktop\ProjectFiles\Code\Program.py", line 88, in FitModel
        model.fit(x_train, y_train, epochs=3, validation_data=(x_test, y_test))
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 728, in fit
        use_multiprocessing=use_multiprocessing)
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py", line 224, in fit
        distribution_strategy=strategy)
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py", line 547, in _process_training_inputs
        use_multiprocessing=use_multiprocessing)
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py", line 606, in _process_inputs
        use_multiprocessing=use_multiprocessing)
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\engine\data_adapter.py", line 479, in __init__
        batch_size=batch_size, shuffle=shuffle, **kwargs)
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\engine\data_adapter.py", line 321, in __init__
        dataset_ops.DatasetV2.from_tensors(inputs).repeat()
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\data\ops\dataset_ops.py", line 414, in from_tensors
        return TensorDataset(tensors)
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\data\ops\dataset_ops.py", line 2335, in __init__
        element = structure.normalize_element(element)
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\data\util\structure.py", line 111, in normalize_element
        ops.convert_to_tensor(t, name="component_%d" % i))
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\ops.py", line 1184, in convert_to_tensor
        return convert_to_tensor_v2(value, dtype, preferred_dtype, name)
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\ops.py", line 1242, in convert_to_tensor_v2
        as_ref=False)
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\ops.py", line 1296, in internal_convert_to_tensor
        ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\tensor_conversion_registry.py", line 52, in _default_conversion_function
        return constant_op.constant(value, dtype, name=name)
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\constant_op.py", line 227, in constant
        allow_broadcast=True)
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\constant_op.py", line 235, in _constant_impl
        t = convert_to_eager_tensor(value, ctx, dtype)
      File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\constant_op.py", line 96, in convert_to_eager_tensor
        return ops.EagerTensor(value, ctx.device_name, dtype)
    ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float).

我自己尝试用谷歌搜索错误,我发现了一些关于使用 tf.convert_to_tensor 函数的信息。我尝试通过它传递我的训练和测试列表,但该函数不会接受它们。

【问题讨论】:

  • 你得到以下什么输出?:(1)print(len(x_train)); (2)print(len(x_train[0])); (3)print(x_train.shape); (4)print(x_train[0].shape)。如果有错误,请跳过数字
  • 更重要的是,查看您的完整代码会有所帮助,因为我无法使用提供的信息重现该问题。我怀疑您使用的是可变输入大小,或者您的 x_train 列表尺寸不一致; for seq in x_train: print(np.array(seq).shape) 的输出是什么?可以share here
  • @OverLordGoldDragon - print(len(x_train)) 输出 13520print(len(x_train[0])) 输出 1000,for 循环为 x_train 中的每个值输出 (1000,)
  • 下面的输出是什么? import sys; import tensorflow as tf; import keras; print(sys.version); print(tf.__version__); print(keras.__version__) # python ver, tf ver, keras ver 另外,您是否可以通过例如共享您的数据子集? Dropbox?

标签: python tensorflow keras lstm


【解决方案1】:

尝试将 np.float32 转换为 tf.float32(读取 keras 和 tensorflow 的数据类型):

tf.convert_to_tensor(X_train, dtype=tf.float32)

【讨论】:

    【解决方案2】:

    如果您使用的是 DataFrame 并且有多个列类型,请使用此选项:

    numeric_list = df.select_dtypes(include=[np.number]).columns
    df[numeric_list] = df[numeric_list].astype(np.float32)
    

    【讨论】:

    • 在这种情况下 numpy.float64 也能正常工作吗?
    【解决方案3】:

    这应该可以解决问题:

    x_train = np.asarray(x_train).astype(np.float32)
    y_train = np.asarray(y_train).astype(np.float32)
    

    【讨论】:

      【解决方案4】:

      我有许多不同的输入和目标变量,但不知道是哪一个导致了问题。

      要找出它破坏了哪个变量,您可以使用堆栈 strace 中指定的路径在库包中添加打印值:

            File "C:\Users\bencu\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\constant_op.py", line 96, in convert_to_eager_tensor
              return ops.EagerTensor(value, ctx.device_name, 
      

      在这部分代码中添加print 语句可以让我看到是哪个输入导致了问题:

      constant_op.py:

        ....
            dtype = dtype.as_datatype_enum
          except AttributeError:
            dtype = dtypes.as_dtype(dtype).as_datatype_enum
        ctx.ensure_initialized()
        print(value) # <--------------------- PUT PRINT HERE
        return ops.EagerTensor(value, ctx.device_name, dtype)
      

      在观察从intastype(np.float32) 的转换中哪个值有问题后解决了问题。

      【讨论】:

        【解决方案5】:

        TL;DR 几个可能的错误,大部分已通过x = np.asarray(x).astype('float32') 修复。

        其他可能是数据预处理错误;确保所有内容格式正确(分类、nans、字符串等)。下面显示了模型的预期:

        [print(i.shape, i.dtype) for i in model.inputs]
        [print(o.shape, o.dtype) for o in model.outputs]
        [print(l.name, l.input_shape, l.dtype) for l in model.layers]
        

        问题的根源在于使用 lists 作为输入,而不是 Numpy 数组; Keras/TF 不支持前者。一个简单的转换是:x_array = np.asarray(x_list)

        下一步是确保以预期格式输入数据;对于 LSTM,这将是一个尺寸为 (batch_size, timesteps, features) 的 3D 张量 - 或等价的 (num_samples, timesteps, channels)。最后,作为调试专家,为您的数据打印所有形状。完成以上所有的代码,如下:

        Sequences = np.asarray(Sequences)
        Targets   = np.asarray(Targets)
        show_shapes()
        
        Sequences = np.expand_dims(Sequences, -1)
        Targets   = np.expand_dims(Targets, -1)
        show_shapes()
        
        # OUTPUTS
        Expected: (num_samples, timesteps, channels)
        Sequences: (200, 1000)
        Targets:   (200,)
        
        Expected: (num_samples, timesteps, channels)
        Sequences: (200, 1000, 1)
        Targets:   (200, 1)
        

        作为额外提示,我注意到您正在通过 main() 运行,因此您的 IDE 可能缺少基于单元的 Jupyter 式执行;我强烈推荐Spyder IDE。就像添加# In[],然后在下面按Ctrl + Enter 一样简单:


        使用的功能

        def show_shapes(): # can make yours to take inputs; this'll use local variable values
            print("Expected: (num_samples, timesteps, channels)")
            print("Sequences: {}".format(Sequences.shape))
            print("Targets:   {}".format(Targets.shape))   
        

        【讨论】:

        • 当我将 3D numpy 数组插入到 pandas 数据帧,然后从数据帧中获取 numpy 数组以创建张量对象时,我遇到了这个问题。为了解决这个问题,我直接传递了 numpy 数组来创建张量对象。
        • 如果我的 ytrain 是一个多标签类数组,我该如何解决? (1000,20) 1000 条记录,每条记录有 20 个标签?
        【解决方案6】:

        您可能想要检查输入数据集或数组中的数据类型,然后将其转换为float32

        train_X[:2, :].view()
        #array([[4.6, 3.1, 1.5, 0.2],
        #       [5.9, 3.0, 5.1, 1.8]], dtype=object)
        train_X = train_X.astype(np.float32)
        #array([[4.6, 3.1, 1.5, 0.2],
        #       [5.9, 3. , 5.1, 1.8]], dtype=float32)
        

        【讨论】:

          【解决方案7】:

          这是一个高度误导性的错误,因为这基本上是一个一般性错误,可能与浮点数无关。

          例如,在我的情况下,它是由 pandas 数据框的字符串列引起的,其中包含一些 np.NaN 值。算了!

          通过用空字符串替换它们来修复它:

          df.fillna(value='', inplace=True)
          

          或者更具体地说,仅对字符串(例如“对象”)列执行此操作:

          cols = df.select_dtypes(include=['object'])
          for col in cols.columns.values:
              df[col] = df[col].fillna('')
          

          【讨论】:

          • np.nan 是一个浮点数,所以 nan 是在误导你,而不是错误。
          • 它运行良好且流畅
          【解决方案8】:

          你最好用这个,因为keras版本不兼容

          from keras import backend as K
          X_train1 = K.cast_to_floatx(X_train)
          y_train1 = K.cast_to_floatx(y_train)
          

          【讨论】:

            【解决方案9】:

            在尝试上述所有方法均未成功后,我发现我的问题是我的数据中的一列具有boolean 值。将所有内容转换为np.float32 解决了这个问题!

            import numpy as np
            
            X = np.asarray(X).astype(np.float32)
            

            【讨论】:

            • 是的,这个简短的答案是所需的一切,非常感谢! :)
            • 这应该是这个 TREAD 的认可答案
            • 很好的答案,我的数据是对象而不是 float32
            【解决方案10】:

            也可能由于版本不同而发生(为了解决这个问题,我不得不从 tensorflow 2.1.0 移回 2.0.0.beta1)。

            【讨论】:

            • 这里也一样,我想弄清楚发生了什么变化。在版本 1 上也可以正常工作。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-05-04
            • 2020-12-08
            • 2020-10-02
            • 2020-10-15
            • 2020-07-05
            • 2020-09-09
            相关资源
            最近更新 更多