Keras:使用model.layers.pop()来删除模型的层不起作用

问题:

使用以下代码来删除模型的layer

import tensorflow as tf
import tensorflow.keras as keras
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Dense, Input, Layer
from tensorflow.keras.models import Model
input_tensor = Input(shape=(10,))
hidden = Dense(100, activation='relu')(input_tensor)
out = Dense(10, activation='relu')(hidden)
model = Model(input_tensor, out)
model.compile(loss="mse", optimizer=tf.train.AdamOptimizer(learning_rate=0.001))
model.summary()
model.layers.pop()
model.layers.pop()
model.summary()
hidden = Dense(120, activation='relu')(model.layers[-1].output)
out = Dense(5, activation='softmax')(hidden)
model = Model(input_tensor, out)
model.summary()

但是结果却显示model.layers.pop()不起作用

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 10)                0         
_________________________________________________________________
dense (Dense)                (None, 100)               1100      
_________________________________________________________________
dense_1 (Dense)              (None, 10)                1010      
=================================================================
Total params: 2,110
Trainable params: 2,110
Non-trainable params: 0
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 10)                0         
_________________________________________________________________
dense (Dense)                (None, 100)               1100      
_________________________________________________________________
dense_1 (Dense)              (None, 10)                1010      
=================================================================
Total params: 2,110
Trainable params: 2,110
Non-trainable params: 0

解决方法:

  1. 重新建立模型并且复制原模型的layer,例:
model = Sequential()
for layer in source_model.layers[:-1]:  # 跳过最后一层 
   model.add(layer)
model.summary()

当然可以自定义增加层用来去掉模型的最后几层,例:

 model = Sequential()
for layer in source_model.layers[:-1]:  # 跳过最后一层 
   model.add(layer)
model.add(Dense(2, activation='softmax'))
model.summary()
  1. 使用函数型模型,即functional model,例:
model = Model(inputs=source_model.input, outputs=source_model.layers[-2].output)  # 这里的source_model即为原来的模型

同样也可以添加层,例:

prediction = Dense(2, activation='softmax')(source_model.layers[-2].output)
model = Model(inputs=source_model.input, outputs=prediction)
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值