如何绑定权重以训练同一模型的多个副本

How to tie weights to train multiple copies of the same model

我需要实现下面的模型。

我必须对一系列数据执行函数 A 和函数 B。 函数A使用神经网络实现,其输出作为函数B的输入(不是神经网络,而是在Keras中使用Model functional API实现),然后在函数的输出处计算损失函数B.

输入是 L 长度的复数向量。我需要将其并行输入到同一网络(顺序)的 L 个副本。一个网络取一个元素的实数和虚数,输出m个实数。

所以L个网络总共会输出mL个实数。函数B将这mL个实数作为输入,计算输出。

我大概是这么打算的,

model_inputs = keras.layers.Input(shape=(L,))

function_A_model = Sequential()
function_A_model.add(Dense(32, activation='relu'))
function_A_model.add(Dense(m))  # Output layer

function_A_inputs = [layers.Input(shape=(2,)) for i in range(L)]

function_A_outputs = []
for i in range(L):
    function_A_outputs = [function_A_outputs function_A_model(function_A_inputs[i]) ]

function_B_outputs = function_B(function_A_outputs)

我想使用模型函数 API 将其实现为更大的模型,它将采用上述 model_inputs 并输出 function_B_outputs。

我的问题是,

  1. 我需要将 model_inputs 输入向量划分为 L 个形状为 2 的输入向量。如何分层完成此操作?还是可以输入向量?

  2. 如何在同一网络的L个副本中实现函数A(权重并列)

  3. 如何将 m*L 个输出合并为一个输出向量,以便将其输入到函数 B?

My problems are, I need to divide the model_inputs Input vector for L Input vectors of shape 2. How can I accomplish this in layers?

您可以定义一个对输入进行切片的 Lambda 层。例如:

example = Input(shape=(20,))
slice_0_4 = Lambda(lambda x: x[:, :4])(example)
slice_4_16 = Lambda(lambda x: x[:, 4:16])(example)
slice_16_20 = Lambda(lambda x: x[:, 16:])(example)

or is it ok to have a vector of inputs?

您可以拥有任意形状的张量,包括 (N, M) 形状。

例如,如果您声明一个模型:

L = Input(shape=(20, 10,))
h1 = Dense(8)(L)

上面的致密层将应用于输入的所有 20 个时间步长。密集层跨时间步共享权重。因此,相同的 w 矩阵将在所有时间步长的所有批次中相乘,进行 10x8 矩阵乘法。

How do I implement the function A in L copies of the same network (weights are tied)

我不确定我是否听懂了你的问题。您可以让顶级模型拆分其输入并使用一部分输入调用子模型;或者你可以有一个模型在包含额外维度的矩阵上执行相同的一组操作。

How do I merge the m*L outputs to one Output vector so I can input it to function B?

你可以使用keras Concatenate层。