我正在 Keras 中构建模型。我有意见
X = Input(shape=(input_size, ), name='input_feature')
和一个固定的预先给定的 numpy 矩阵 D,它是 input_size 乘以 n。
我想在将 X 和 D 输入到下一层之前将它们连接起来。换句话说,我需要连接 X 和 D 的每个切片以生成一个新的 inpt,其预期大小应为 (none, input_size, n+1)。那么我应该怎么做才能将它们连接起来呢?据我了解,批量大小为 none,因为当我们将数据拟合到模型时它将适应输入 X 的批量大小。
请您参考如下方法:
回答 D 是否具有形状 (batch, input_size,n)
假设D是一个张量(如果它是某个层的输出,它就是一个张量):
X = Reshape((input_size,1))(X)
concat = Concatenate()([D,X])
如果 D 不是张量:
import keras.backend as K
#create a tensor:
Dval = K.variable(numpyArrayForD)
#create an input for D:
D = Input(tensor=Dval)
#do as in the top of this answer.
如果你想避免额外的Input(它不会影响你的训练方式,因为tensor参数),你可以使用lambda层:
def concatenation(x):
D = K.variable(D_df)
return K.concatenate([x,D])
XD = Lambda(concatenation,output_shape=(input_size,n+1))(X)
回答 D 是否具有形状 (input_size,n)
在这种情况下,最好多次复制 D。您可以在模型外部执行此操作,在创建 K.variable 之前使用 numpy 函数(参见其他答案),如下所示:
D_df = D_df.reshape((1,input_size,n))
D_df = numpy.repeat(D_df,batch,axis=0)
但是这种方法需要你事先适应 x 的大小。 如果你想要适应任何大小的 X 而不必改变 D 之前的东西,那就更复杂了....
