python - 如何在 Keras 中微调功能模型?

标签 python tensorflow keras

在 Keras 中采用预训练模型并替换顶部分类层以将网络重新训练到新任务有几个使用 Keras 中的顺序模型的示例。顺序模型具有 model.pop()model.add() 方法,这使得这变得相当容易。

但是,使用函数模型时这是如何实现的呢?该框架没有方法model.add()

如何在 Keras 中加载预训练的功能模型,裁剪最后一层并将其替换为新层?

目前的方法:

model.load_weights('/my_model_weights.h5')

def pop_layer(model):
    if not model.outputs:
    raise Exception('Sequential model cannot be popped: model is empty.')

    model.layers.pop()
    if not model.layers:
        model.outputs = []
        model.inbound_nodes = []
        model.outbound_nodes = []
    else:
        model.layers[-1].outbound_nodes = []
        model.outputs = [model.layers[-1].output]
    model.built = False

# Remove last layer with custom function (from another post)
pop_layer(model)

# Now add a new layer to the model ???

model.add(Dense(2, activation='softmax', name='fc2'))
model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd',
              metrics=['accuracy'])

AttributeError: 'Model' object has no attribute 'add'

最佳答案

您可以使用预训练的函数模型,并将最后一层作为一层删除。您可能会将模型视为“更大的层”。然后重新定义一个包含“更大层”和新层的新模型。

一个例子:

import tensorflow as tf
from keras.layers import Dense,Input
from keras.models import Sequential,Model

input_tensor = Input(shape=(64,))
x = Dense(32, activation='relu')(input_tensor)
x = Dense(32, activation='relu')(x)
output_tensor = Dense(10, activation=tf.nn.softmax)(x)
model = Model(input_tensor, output_tensor)
model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd',
              metrics=['accuracy'])
print(model.summary())
model.save_weights('my_model_weights.h5')
# 
model.load_weights('my_model_weights.h5')

def pop_layer(model):
    if not model.outputs:
        raise Exception('Sequential model cannot be popped: model is empty.')
    model.layers.pop()
    if not model.layers:
        model.outputs = []
        model.inbound_nodes = []
        model.outbound_nodes = []
    else:
        model.layers[-1].outbound_nodes = []
        model.outputs = [model.layers[-1].output]
    return model

# Remove last layer with custom function (from another post)
model_old = pop_layer(model)
# Now add a new layer to the model
model_new = Sequential()
model_new.add(model_old)
model_new.add(Dense(2, activation=tf.nn.softmax, name='fc2'))
model_new.compile(loss='sparse_categorical_crossentropy', optimizer='sgd',
              metrics=['accuracy'])
print(model_new.summary())

结果可以看到预训练函数模型最后一层的参数缺失了。

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 64)                0         
_________________________________________________________________
dense_1 (Dense)              (None, 32)                2080      
_________________________________________________________________
dense_2 (Dense)              (None, 32)                1056      
_________________________________________________________________
dense_3 (Dense)              (None, 10)                330       
=================================================================
Total params: 3,466
Trainable params: 3,466
Non-trainable params: 0
_________________________________________________________________
None

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
model_1 (Model)              multiple                  3136      
_________________________________________________________________
fc2 (Dense)                  (None, 2)                 66        
=================================================================
Total params: 3,202
Trainable params: 3,202
Non-trainable params: 0
_________________________________________________________________
None

关于python - 如何在 Keras 中微调功能模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53907681/

相关文章:

tensorflow - 语义图像分割神经网络 (DeepLabV3+) 的内存过多问题

python - [Python][Keras] softmax() 获得意外的关键字参数 'axis'

Tensorflow 评估频率

python - 无法保存子类 TensorFlow 2.1 模型——__call__() 缺少 1 个必需的位置参数 : 'x'

python - 找不到 Keras TensorFlow 图像数据

machine-learning - 如何在tensorflow中编写自定义池化层模块?

python - 如何解决python机器学习中不在索引中的列

python - 如何从 IMAP 服务器获取最后 10 条消息?

python - 尝试创建 virtualenv 时出错

python - 从 TensorFlow 中的检查点恢复后修改变量名称