python - 无法将 NumPy 数组转换为张量(不支持的对象类型 numpy.ndarray)- 已经将数据转换为 numpy 数组

标签 python arrays numpy tensorflow neural-network

尝试为基于文本的多标签分类问题训练单层神经网络。

model= Sequential()
model.add(Dense(20, input_dim=400, kernel_initializer='he_uniform', activation='relu'))
model.add(Dense(9, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam')

model.fit(x_train, y_train, verbose=0, epochs=100)

获取错误为:

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).

x_train 是一个 300 维的 word2vec 向量化文本数据,每个实例填充到 400 长度。包含 462 条记录。

训练数据观察如下:

print('#### Shape of input numpy array #####')
print(x_train.shape)
print('#### Shape of each element in the array #####')
print(x_train[0].shape)
print('#### Object type for input data #####')
print(type(x_train))
print('##### Object type for first element of input data ####')
print(type(x_train[0]))

#### Shape of input numpy array #####
(462,)
#### Shape of each element in the array #####
(400, 300)
#### Object type for input data #####
<class 'numpy.ndarray'>
##### Object type for first element of input data ####
<class 'numpy.ndarray'>

最佳答案

存在三个问题


问题1
这是你的主要问题,直接导致了错误
你初始化/转换你的 x_train 的方式出了问题(我认为这是一个错误,或者你使用了一些不寻常的方式来构造你的数据),现在你的 x_train 实际上是一个数组数组,而不是一个多维数组。所以 TensorFlow 根据其形状“认为”你有一个一维数组,这不是你想要的。 解决方案是在发送到 fit() 之前重建数组:

x_train = np.array([np.array(val) for val in x_train])

问题2
密集层期望您的输入具有形状 (batch_size, ..., input_dim),这意味着您的 x_train 的最后一个维度必须等于 input_dim,但您有 300,这与 400 不同。
根据你的描述,你的输入维度,也就是词向量维度是300,所以你要把input_dim改成300:

model.add(Dense(20, input_dim=300, kernel_initializer='he_uniform', activation='relu'))

或者等效地,直接提供 input_shape 而不是

model.add(Dense(20, input_shape=(400, 300), kernel_initializer='he_uniform', activation='relu'))

问题3
因为密集层,又名线性层,是针对“线性”输入的,所以它期望它的每个数据都是一维向量,所以输入通常类似于 (batch_size, vector_length)。当 dense 接收到维度 > 2 的输入(你有 3 个维度)时,它将对最后一个维度执行 Dense 操作。引用自 TensorFlow 官方文档:

Note: If the input to the layer has a rank greater than 2, then Dense computes the dot product between the inputs and the kernel along the last axis of the inputs and axis 1 of the kernel (using tf.tensordot). For example, if input has dimensions (batch_size, d0, d1), then we create a kernel with shape (d1, units), and the kernel operates along axis 2 of the input, on every sub-tensor of shape (1, 1, d1) (there are batch_size * d0 such sub-tensors). The output in this case will have shape (batch_size, d0, units).

这意味着您的 y 应该具有形状 (462, 400, 9) 而不是。这很可能不是您正在寻找的(如果这确实是您正在寻找的,问题 1 和 2 中的代码应该已经解决了您的问题)。

如果要在整个 400x300 矩阵上进行密集运算,则需要先展平为一维向量,如下所示:

x_train = np.array([np.array(val) for val in x_train])  # reconstruct
model= Sequential()
model.add(Flatten(input_shape=(400, 300)))
model.add(Dense(20, kernel_initializer='he_uniform', activation='relu'))
model.add(Dense(9, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam')

model.fit(x_train, y_train, verbose=0, epochs=100)

现在输出将是 (462, 9)

关于python - 无法将 NumPy 数组转换为张量(不支持的对象类型 numpy.ndarray)- 已经将数据转换为 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68689167/

相关文章:

python - 从 Seaborn 热图格式中排除列,但保留在 map 中

python - 将字符串转换为字典,然后访问 key :values? ??如何为 Python 访问 <class 'dict'> 中的数据?

php - 构建 JavaScript 对象 PHP 循环时缺少字符

javascript - 使用 Node.js 连接和聚合 json 对象数据

python - 为什么numpy中正态分布的总和不同?

python - 在 matplotlib 中绘制均值

python - Python 中元组切片究竟是如何工作的?

python - 如何在 Pony ORM 中从 Set() 中仅获取一张图像

c++ - 如何设置一个字符串数组,其中包含将通过数组显示在 iphone 文本上的字符串?

python - 加载目录中的每个内部文件夹并保存