0

我有一个循环神经网络模型,可以将一个(N,)序列映射到一个(N,3)长度序列。我的目标输出实际上是(N,N)矩阵。但是,我在 numpy 中实现了一个确定性函数,它以我想要的特定方式转换(N,3)为这些矩阵。(N,N)如何在训练中使用此操作?即目前我的神经网络正在给出序列,我如何在调用之前(N,3)执行我的函数将其转换为(N,N)这些序列?keras.fit

编辑:我还应该注意,从 to 执行反向功能要困难得多,(N,N)因此将我的目标输出转换为输出表示(N,3)不是一个可行的选择。(N,3)

4

1 回答 1

1

您可以使用Lambda层作为模型的最后一层:

def convert_to_n_times_n(x):
    # transform x from shape (N, 3) to (N, N)

transformation_layer = tf.keras.layers.Lambda(convert_to_n_times_n)

您可能希望tf尽可能在函数中使用“-native 方法”,以避免不必要地将张量转换为 numpy 数组并返回。

如果您只想在训练期间使用该层,而不是在推理期间,您可以使用功能 API 来实现:

# create your original model (N,) -> (N, 3)
input_ = Input(shape=(N,))
x = SomeFancyLayer(...)(input_)
x = ...
...
inference_output = OtherFancyLayer(...)(x)

inference_model = Model(inputs=input_, outputs=inference_output)

# create & fit the training model
training_output = transformation_layer(inference_output)
training_model = Model(inputs=input_, outputs=training_output)

training_model.compile(...)
training_model.fit(X, Y)

# run inference using your original model
inference_model.predict(...)
于 2019-04-12T05:37:49.980 回答