Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tf.keras.layers.pop() doesn't work, but tf.keras._layers.pop() does

I want to pop the last layer of the model. So I use the tf.keras.layers.pop(), but it doesn't work.

base_model.summary()

enter image description here

base_model.layers.pop()

base_model.summary()

enter image description here

When I use tf.keras._layers.pop(), it works.

base_model.summary()

enter image description here

base_model._layers.pop()
base_model.summary()

enter image description here

I don't find docs about this usage. Could someone help explain this?

like image 341
qinlong Avatar asked Aug 01 '19 20:08

qinlong


1 Answers

I agree this is confusing. The reason is that model.layers returns a shallow copy of the layers list so:

The tldr is dont use model.layers.pop() to remove the last layer. Instead we should create a new model with all but the last layer. Perhaps something like this:

new_model = tf.keras.models.Sequential(base_model.layers[:-1])

Checkout this github issue for more details

like image 64
Stewart_R Avatar answered Oct 01 '22 02:10

Stewart_R