如何增加 CNN 自动编码器中的 Lambda 层数?

How to increase the number of Lambda layer in CNN autoencoder?

我正在尝试像这样自定义 CNN 自动编码器。但是我不明白Lambda层的含义。 Lambda(lambda x: x[:,0:1]) 是什么意思?以及如何在这种情况下再添加一个 lambda 层(即 val3)?

input_img = Input(shape=(384, 192, 2))
## Encoder
x = Conv2D(16, (3, 3), activation='tanh', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='tanh', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='tanh', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='tanh', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(4, (3, 3), activation='tanh', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(4, (3, 3), activation='tanh', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Reshape([6*3*4])(x) ## Flatten()
encoded = Dense(2,activation='tanh')(x)
## Two variables
val1= Lambda(lambda x: x[:,0:1])(encoded)
val2= Lambda(lambda x: x[:,1:2])(encoded)
## Decoder 1
.....

来自this blog

Let's say that after the dense layer named dense_layer_3 we'd like to do some sort of operation on the tensor, such as adding the value 2 to each element. How can we do that? None of the existing layers does this, so we'll have to build a new layer ourselves.

所以Lambda层用于对输入张量执行操作但仍被识别为层。例如,假设我有模型:

layer1 = Dense(...)(x)
layer2 = Dense(...)(x)

model.summary() # will have layer1 and layer2

现在我想在 layer1 之后执行 x+2。通常我会这样做:

layer1 = Dense(...)(x)
x = x+2
layer2 = Dense(...)(x)

model.summary() # will miss the x = x+2 operation

但是x=x+2不会被识别为模型中的图层。我们知道它存在是因为我们这样做了,但其他人将无法知道,这使得如果出现问题很难调试。所以我们使用 Lambda:

layer1 = Dense(...)(x)
lamb = Lambda(lambda x: x+2)(x) 
layer2 = Dense(...)(x)

model.summary() # will have Lambda layer inside it

关于Lambda(lambda x: x[:,0:1]),它是用于张量切片的Lambda层。 x[:, 0:1] 表示“获取所有行,但只获取索引从 0 到 1 的列。