1

I am trying to dynamically create layers in Keras (Lambda Layers) but for some reason when I use for loop I get the same error in the list, compared to manually appending elements into the list.

Where is my bug?

other_channels_out = []
out_channel = []

for i in range(out_number_model_0):
    layer = Lambda(lambda xx: K.expand_dims(xx))(Lambda(lambda y: y[:, i])(model_0.output))
    if i != channel:
        other_channels_out.append(layer)
    else:
        out_channel.append(layer)

Vs

other_channels_out.append(Lambda(lambda xx: K.expand_dims(xx))(Lambda(lambda y: y[:, 0])(model_0.output)))
other_channels_out.append(Lambda(lambda xx: K.expand_dims(xx))(Lambda(lambda y: y[:, 1])(model_0.output)))
out_channel.append(Lambda(lambda xx: K.expand_dims(xx))(Lambda(lambda y: y[:, 2])(model_0.output)))

The list consist of : [a,a,a,a] vs [a,b,c,d]

Tom Z
  • 21
  • 4

2 Answers2

0

Making a function to generate the layer seems to solve it. But I would like some explanation?

    other_channels_out = []
out_channel = []

def createLambda(i,input):
    _layer = Lambda(lambda xx: K.expand_dims(xx))(Lambda(lambda y: y[:, i])(input))
    return _layer

for i in range(out_number_model_0):
    if i != channel:
        other_channels_out.append(createLambda(i, model_0.output))
    else:
        out_channel.append(createLambda(i, model_0.output))
Tom Z
  • 21
  • 4
0

I don't have enough reputation to comment, but the issue is that the scope of i is outside the lambda function, so the value of i changes after the lambda is created. By moving the Lambda (and hence lambda) creation to another function, you've redefined the scope of i.

Related: Scope of lambda functions and their parameters?

sdaug
  • 1
  • 1