尝试为基于文本的多标签分类问题训练单层神经网络。
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-dim 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 官方文档:
注意:如果层的输入的秩大于 2,则
Dense
计算inputs
和之间的点积,kernel
沿 的最后一个轴inputs
和 的轴 1kernel
(使用tf.tensordot
)。例如,如果 input 有维度(batch_size, d0, d1)
,那么我们创建一个kernel
with 形状(d1, units)
,并且在形状的每个子张量上kernel
沿着 的轴 2 操作(有这样的子张量)。在这种情况下,输出将具有 shape 。input
(1, 1, d1)
batch_size * d0
(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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句