- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
尝试为基于文本的多标签分类问题训练单层神经网络。
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 theinputs
and thekernel
along the last axis of theinputs
and axis 1 of thekernel
(usingtf.tensordot
).For example, if input has dimensions(batch_size, d0, d1)
, then wecreate akernel
with shape(d1, units)
, and thekernel
operatesalong axis 2 of theinput
, on every sub-tensor of shape(1, 1, d1)
(there arebatch_size * d0
such sub-tensors). The output in thiscase 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/
我想矢量化以下代码: def style_noise(self, y, style): n = torch.randn(y.shape) for i in range(n.shape[
对于给定的二维张量,我想检索值为 1 的所有索引。我希望能够简单地使用 torch.nonzero(a == 1).squeeze(),它将返回张量([1, 3, 2])。但是,torch.nonze
如果 x 是 dtype torch.float 的 torch.Tensor 那么操作 x.item() 和 float(x)完全一样? 最佳答案 操作x.item() 和float(x) 是不一样
我正在尝试提取 n 点 3D 坐标和 b 批处理中的特定行。本质上,我的张量 T1 的形状为 b*n*3。我有另一个形状为 b * n 的 bool 张量 T2,指示需要获取 n 的哪些行。本质上我的
以下代码掩码很好 mask = targets >= 0 targets = targets[mask] 但是,当我尝试使用两个条件进行屏蔽时,它会给出 RuntimeError: Boolean v
我正在定义一个简单的 conv2d 函数来计算输入和内核(均为 2D 张量)之间的互相关,如下所示: import torch def conv2D(X, K): h = K.shape[0]
作为训练 CNN 的一部分,我正在使用数组 inputs包含 对象。我想轮换一个人一些随机度数的对象 x ,如下所示: def rotate(inputs, x): # Rotate inpu
我有一个索引列表和一个具有形状的张量: shape = [batch_size, d_0, d_1, ..., d_k] idx = [i_0, i_1, ..., i_k] 有没有办法用索引 i_0
假设我有张量 t = torch.tensor([1,2,3,4,5]) 我想使用相同大小的索引张量来拆分它,该张量告诉我每个元素应该进行哪个拆分。 indices = torch.tensor([0
我尝试从生成器构建一个张量,如下所示: >>> torch.tensor(i**2 for i in range(10)) Traceback (most recent call last): F
假设我有一个一维 PyTorch 张量 end_index长度为L。 我想构造一个 2D PyTorch 张量 T有 L 行,其中 T[i,j] = 2什么时候j < end_index[i]和 T[
我在 pytorch 中有一个张量 x 比方说形状 (5,3,2,6) 和另一个形状 (5,3,2,1) 的张量 idx,其中包含第一个张量中每个元素的索引。我想用第二个张量的索引对第一个张量进行切片
我有以下火炬张量: tensor([[-0.2, 0.3], [-0.5, 0.1], [-0.4, 0.2]]) 以及以下 numpy 数组:(如有必要,我可以将其转换为其他内
tf.data.Dataset的构造函数接受一个参数 variant_tensor ,这只是 documented as : A DT_VARIANT tensor that represents t
我有: inp = torch.randn(4, 1040, 161) 我还有另一个名为 indices 的张量值: tensor([[124, 583, 158, 529], [1
我有一个张量 inps ,其大小为 [64, 161, 1]我有一些新数据d大小为 [64, 161] .如何添加 d至inps这样新的大小是[64, 161, 2] ? 最佳答案 使用 .unsqu
我有张量 t = torch.tensor([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]) 和一个查询张量 q = torch.te
给定一个 3d 张量,说:batch x sentence length x embedding dim a = torch.rand((10, 1000, 96)) 以及每个句子的实际长度数组(或张
我想使用 [int, -1] 符号 reshape 张量(例如,压平图像)。但我事先并不知道第一个维度。一个用例是在大批量上进行训练,然后在较小的批量上进行评估。 为什么会出现以下错误:获取包含“_M
我有两个 torch 张量。一个形状为 [64, 4, 300],一个形状为 [64, 300]。我如何连接这两个张量以获得形状为 [64, 5, 300] 的合成张量。我知道用于此的 tensor.
我是一名优秀的程序员,十分优秀!