在Theano中添加额外特性(卷积神经网络)

0 投票
1 回答
1078 浏览
提问于 2025-04-18 15:24

我正在使用Theano进行分类(卷积神经网络)。

之前,我一直用图像的像素值(经过扁平化处理)作为神经网络的特征。现在,我想添加一些额外的特征。
有人告诉我,可以把这些额外特征的向量和扁平化的图像特征连接起来,然后把它作为全连接层的输入,但我在这方面遇到了一些问题。

首先,这样做是对的吗?

这里有一些代码片段和我的错误信息:
这和他们网站上提供的例子类似,只是做了一些修改。

(来自构建模型的类)

 # allocate symbolic variables for the data
 self.x = T.matrix('x')   # the data is presented as rasterized images
 self.y = T.ivector('y')  # the labels are presented as 1D vector of [int] labels
 self.f = T.matrix('f') # additional features

下面,变量 vrng 是之前定义的。重要的是 layer2_input

layer2_input = self.layer1.output.flatten(2)
layer2_input = T.concatenate([layer2_input, self.f.flatten(2)])
self.layer2 = HiddenLayer(rng, input=layer2_input, n_in=v, n_out=200, activation=T.tanh)

(来自训练的类)

train_model = theano.function([index], cost, updates=updates,
          givens={
             model.x: train_set_x[index * batch_size: (index + 1) * batch_size],
             model.y: train_set_y[index * batch_size: (index + 1) * batch_size],
             model.f: train_set_f[index * batch_size: (index + 1) * batch_size]
          })

但是,当调用 train_model 时,我遇到了一个错误:

ValueError: GpuJoin: Wrong inputs for input 1 related to inputs 0.!
Apply node that caused the error: GpuJoin(TensorConstant{0}, GpuElemwise{tanh,no_inplace}.0, GpuFlatten{2}.0)
Inputs shapes: [(), (5, 11776), (5, 2)]
Inputs strides: [(), (11776, 1), (2, 1)]
Inputs types: [TensorType(int8, scalar), CudaNdarrayType(float32, matrix), CudaNdarrayType(float32, matrix)]

输入的形状是否分别代表 xyf 的形状?

如果是这样的话,第三个看起来是正确的(批量大小=5,2个额外特征),但为什么第一个是标量而第二个是矩阵呢?

更多细节:

train_set_x.shape = (61, 19200) [61 flattened images (160x120), 19200 pixels]
train_set_y.shape = (61,) [61 integer labels]
train_set_f.shape = (61,2) [2 additional features per image]
batch_size = 5

我这样想对吗?还是有更好的方法来实现这个?
有没有人能告诉我为什么我会遇到这个错误?

1 个回答

1

问题在于我在错误的方向上进行了拼接。

layer2_input = T.concatenate([layer2_input, self.f.flatten(2)])

应该是这样做的

layer2_input = T.concatenate([layer2_input, self.f.flatten(2)], axis=1)

撰写回答