ChatGPT解决这个技术问题 Extra ChatGPT

Tensorflow - ValueError:无法将 NumPy 数组转换为张量(不支持的对象类型浮点数)

上一个问题的继续: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 共享您的数据子集?

O
OverLordGoldDragon

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 个标签?
V
Vasco Cansado Carvalho

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

import numpy as np

X = np.asarray(X).astype(np.float32)

是的,这个简短的答案是所需的一切,非常感谢! :)
这值得成为该胎面的认可答案
很好的答案,我的数据是对象而不是 float32
S
Scott

这应该可以解决问题:

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

Z
Zoltan Fedor

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

例如,在我的情况下,它是由 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 会误导您,而不是错误。
它工作得很好而且很顺利
I
Igor

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

要找出它破坏了哪个变量,您可以使用堆栈 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) 的转换解决了问题。


D
Danilo Soto Villena

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

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


r
rosyaniv

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


同样在这里,我想弄清楚发生了什么变化。在版本 1 上也可以正常工作。
A
Alexander

您可能需要检查输入数据集或数组中的数据类型,然后将其转换为 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)

N
Newt

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

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

a
amalik2205

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

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

numpy.float64 在这种情况下也能正常工作吗?
A
Adelson Araújo

就我而言,转换为 np.float32 不起作用。

对我来说,训练期间一切正常(可能是因为我使用 tf.data.Dataset.from_generator 作为 fit() 的输入),但是当我尝试在 1 个实例上调用 predict() 时(使用 np.array),出现错误.

作为一种解决方案,我必须在调用 predict 之前重塑数组 x_array.reshape(1, -1) 并且它起作用了。


Y
Yuriy Sereda

我通过在数据导入期间强制浮点格式避免了这个问题:

df = pd.read_csv('titanic.csv', dtype='float')


d
drew_is_good

只是有同样的问题,它最终是因为我试图传递一个数组对象数组,而不是预期的数组数组。希望这对将来的人有所帮助!


H
Harsh Suvarna

尝试

X_train =t ensorflow.convert_to_tensor(X_train, dtype=tensorflow.float32)
y_train = tensorflow.convert_to_tensor(y_train, dtype=tensorflow.float32)
X_test = tensorflow.convert_to_tensor(X_test, dtype=tensorflow.float32)
y_test = tensorflow.convert_to_tensor(y_test, dtype=tensorflow.float32)

正如目前所写的那样,您的答案尚不清楚。请edit添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。您可以找到有关如何写出好答案的更多信息in the help center
N
Nitin Yadav

正如上面大多数人所回答的那样,通过此处已经讲述的各种方式转换 np.float32 / float32 中的数据。

这样做时,如果您收到另一个错误“ValueError: setting an array element with a sequence”。

在这种情况下,请尝试将您的数据转换为 type list,然后像您之前尝试的那样将其转换为张量类型。


关注公众号,不定期副业成功案例分享
关注公众号

不定期副业成功案例分享

领先一步获取最新的外包任务吗?

立即订阅