我只想从.h5文件中已经保存的模型中删除最后一个密集层,并添加一个新的密集层。
有关保存的模型的信息:
我在EfficientNet B0模型上使用了传输学习,并添加了一个2层密集的下拉列表。最后一个密集层有3个节点,等于我的类数,如下所示:
inputs = tf.keras.layers.Input(shape=(IMAGE_HEIGHT, IMAGE_WIDTH, 3))
x = img_augmentation(inputs)
model = tf.keras.applications.EfficientNetB0(include_top=False, input_tensor=x, weights="imagenet")
# Freeze the pretrained weights
model.trainable = False
# Rebuild top
x = tf.keras.layers.GlobalAveragePooling2D(name="avg_pool")(model.output)
x = tf.keras.layers.BatchNormalization()(x)
x = tf.keras.layers.Dropout(0.3)(x)
x = tf.keras.layers.Dense(5, activation=tf.nn.relu)(x)
outputs = tf.keras.layers.Dense(len(class_names), activation="softmax", name="pred")(x)经过训练,我把我的模型保存为my_h5_model.h5
主要任务:我希望使用保存的模型体系结构及其权重,并将最后一个密集层替换为4个节点密集层。
我尝试了许多StackOverflow社区建议的内容:
遍历除最后一层之外的所有层,并将它们添加到一个单独的已经定义的顺序模型中。
new_model = Sequential()
for layer in (model.layers[:-1]):
new_model.add(layer)但它给出了一个错误,即:
ValueError:调用层"block1a_se_excite“时遇到的异常(键入乘法)。
应该在输入列表上调用合并层。接收:inputs=Tensor(“占位符:0”,shape=(无,1,1,32),dtype=float32) (不是张量列表)
收到的呼叫论据:
·inputs=tf.Tensor(shape=(无,1,1,32),dtype=float32)
我还尝试了以下功能方法:
input_layer = model.input
for layer in (model.layers[:-1]):
x = layer(input_layer)如下所述:
ValueError:调用层"stem_bn“时遇到的异常(键入BatchNormalization)。
尺寸必须相等,但对于输入形状为:?、224、224、3、32、32、32、32、32、32、32、32、32、32、32、32、32、32、32、32、32、32、32、32、32、32、32、32、32和32的输入形状为:?、224、224、3、32、32、32、32、FusedBatchNormV3T=DT_FLOAT, U=DT_FLOAT, data_format="NHWC", epsilon=0.001, exponential_avg_factor=1, is_training=false,则为3和32。
收到的呼叫论据:
·inputs=tf.Tensor(shape=(无,224,224,3),dtype=float32)
·training=False
最后,我做了一些在我脑海里浮现的事情
inputs = tf.keras.layers.Input(shape=(IMAGE_HEIGHT, IMAGE_WIDTH, 3))
x = img_augmentation(inputs)
x = model.layers[:-1](x)
x = keras.layers.Dense(5, name="compress_1")(x)它只是给出了一个错误,如:
“列表”对象不可调用
发布于 2022-03-06 08:29:48
我做了一些更多的实验,并能够删除最后一层,并添加新的密集层。
# imported a pretained saved model
from tensorflow import keras
import tensorflow as tf
model = keras.models.load_model('/content/my_h5_model.h5')
# selected all layers except last one
x= model.layers[-2].output
outputs = tf.keras.layers.Dense(4, activation="softmax", name="predictions")(x)
model = tf.keras.Model(inputs = model.input, outputs = outputs)
model.summary()在保存的模型中,我在密集层上有3个节点,但在当前模型中,我添加了4个层。最后一层摘要如下:
dropout_3 (Dropout) (None, 1280) 0 ['batch_normalization_4[0][0]']
dense_3 (Dense) (None, 5) 6405 ['dropout_3[0][0]']
predictions (Dense) (None, 4) 24 ['dense_3[0][0]']
==================================================================================================发布于 2022-03-04 17:28:05
在您的导入中,您是否尝试过在导入keras和tensorflow.keras之间切换?这在其他问题上起了作用。
https://stackoverflow.com/questions/71352568
复制相似问题