[英]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. 所以我使用tf.keras.layers.pop()
,但它不起作用。
base_model.summary()
base_model.layers.pop()
base_model.summary()
When I use tf.keras._layers.pop()
, it works. 当我使用tf.keras._layers.pop()
,它可以工作。
base_model.summary()
base_model._layers.pop()
base_model.summary()
I don't find docs about this usage. 我找不到关于这种用法的文档。 Could someone help explain this? 有人可以帮忙解释一下吗?
I agree this is confusing. 我同意这令人困惑。 The reason is that model.layers
returns a shallow copy of the layers list so: 原因是model.layers
返回图层列表的浅表副本,因此:
The tldr is dont use model.layers.pop()
to remove the last layer. tldr不使用model.layers.pop()
来删除最后一层。 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 查看此github问题以获取更多详细信息
@Stewart_R clearly shows the solution to the problem :) @Stewart_R清楚地显示了问题的解决方案:)
Let me just put a simple code with the solution. 我只想在解决方案中加入一个简单的代码。
loaded_model = keras.models.load_model(fname) # remove the last 2 layers sliced_loaded_model = Sequential(loaded_model.layers[:-2]) # set trainable=Fasle for the layers from loaded_model for layer in sliced_loaded_model.layers: layer.trainable = False # add new layers sliced_loaded_model.add(Dense(32, activation='relu')) # trainable=True is default sliced_loaded_model.add(Dense(1)) # compile sliced_loaded_model.compile(loss='mse', optimizer='adam', metrics=[]) # fit ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.