Keras - 将不同数据点的不同参数传递到 Lambda 层

Keras - passing different parameter for different data point onto Lambda Layer

我正在 Keras/TF 后台处理 CNN 模型。在最后的卷积层结束时,我需要汇集过滤器的输出图。我没有使用 GlobalAveragePooling 或任何其他类型的池化,而是必须根据输出地图宽度上存在的时间范围进行池化。

因此,如果一个过滤器的样本输出是 n x mn 是时间范围,并且 m 沿着特征输出。在这里,我只需要合并 n1 to n2 帧的输出,其中 n1n2 <= n。所以我的输出切片是 (n2-n1)*m,我将在其上应用池化。我遇到了 Lambda Layer of keras 来做这个。但是我被困在 n1n2 每个点都不同的地方。所以我的问题是如何将每个数据点的自定义参数传递给 Lambda Layer?还是我处理方法不对?

示例片段:

# for slicing a tensor
def time_based_slicing(x, crop_at):
    dim = x.get_shape()
    len_ = crop_at[1] - crop_at[0]
    return tf.slice(x, [0, crop_at[0], 0, 0], [1, len_, dim[2], dim[3]])

# for output shape
def return_out_shape(input_shape):
    return tuple([input_shape[0], None, input_shape[2], input_shape[3]])

# lambda layer addition
model.add(Lambda(time_based_slicing, output_shape=return_out_shape, arguments={'crop_at': (2, 5)}))

上述参数 crop_at 在循环拟合时需要为每个数据点自定义。对此的任何 pointers/clues 都会有所帮助。

从顺序 API 切换 - 当您需要使用多个输入时它开始崩溃:使用函数 API https://keras.io/models/model/

假设您的 lambda 函数是正确的:

def time_based_slicing(inputs_list):
    x, crop_at = inputs_list
    ... (will probably need to do some work to subset crop_at since it will be a tensor now instead of constants

inp = Input(your_shape)
inp_additional = Inp((2,)
x=YOUR_CNN_LOGIC(inp)
out = Lambda(time_based_slicing)([x,inp_additional])

鉴于您之前知道属于每个数据点的时间范围的索引,您可以将它们存储在文本文件中并将它们作为附加 Input 传递给您的模型:

slice_input = Input((2,))

并在您的 time_based_slicing 函数中使用它们。