You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow中修改NASNetMobile预训练模型适配3分类的方法对比咨询

我在修改预训练模型以实现3分类(替代原1000分类)的问题上存在困惑,目前想到了以下两种方法,不确定哪种更优。

NASNetMobile_model = tf.keras.applications.NASNetMobile (
                                                input_shape=(224,224,3),
                                                include_top=False,
                                                pooling='avg',
                                                classes=3,
                                                weights='imagenet'
                                                )
NASNetMobile_model.trainable=False
NASNetMobile_model.summary()
方法1

以预训练ImageNet权重初始化NASNetMobile模型,移除顶层并使用平均池化,设置模型不可训练以避免训练时更新权重。随后构建新的Sequential模型,包含该预训练模型,以及两个全连接层:一个含128个单元、ReLU激活函数,另一个含3个单元、softmax激活函数用于最终分类。编译时采用Adam优化器与稀疏类别交叉熵损失,在数据集上训练20轮,批量大小为4,验证集占比20%。

new_pretrained_model = tf.keras.Sequential()

new_pretrained_model.add(NASNetMobile_model)
new_pretrained_model.add(tf.keras.layers.Dense(128, activation='relu'))
new_pretrained_model.add(tf.keras.layers.Dense(3, activation='softmax'))

new_pretrained_model.layers[0].trainable = False
new_pretrained_model.summary()


new_pretrained_model.compile(
            optimizer='adam',
            loss='sparse_categorical_crossentropy',
            metrics=['accuracy']
            )

new_pretrained_model.fit(
        Xtrain,
        Ytrain,
        epochs=20,
        batch_size=4,
        validation_split=0.2
        )
方法2

使用函数式API构建新模型,将预训练NASNetMobile模型的输出作为新的含128个单元、ReLU激活函数的全连接层输入,再接一个含3个单元、softmax激活函数的最终分类层。显式连接原模型输入与新输出层,形成输入与原模型一致、新增分类层的新模型。编译与训练配置同方法1。

NASNetMobile_model_out = NASNetMobile_model.output
x = tf.keras.layers.Dense(128, activation='relu')(NASNetMobile_model_out)
output = tf.keras.layers.Dense(3, activation='softmax')(x)
model_2 = tf.keras.Model(inputs = NASNetMobile_model.input, outputs=output)

model_2.summary()


model_2.compile(
            optimizer='adam',
            loss='sparse_categorical_crossentropy',
            metrics=['accuracy']
            )

model_2.fit(
        Xtrain,
        Ytrain,
        epochs=20,
        batch_size=4,
        validation_split=0.2
        )

内容的提问来源于stack exchange,提问作者Redlightning

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 07:19:52