如何用预训练模型从RGB图像生成指定维度的特征张量
自定义预训练模型输出的特征维度
解决方案
在你已有的GlobalAveragePooling2D层之后,添加一个全连接(Dense)层,直接将2048维的特征映射到你指定的M_features维度即可,这样既能保留预训练模型的特征提取能力,又能得到目标形状的1D特征向量。
完整代码示例
from tensorflow.keras.applications.resnet50 import ResNet50 from tensorflow.keras.layers import Dense, GlobalAveragePooling2D from tensorflow.keras.applications.resnet50 import preprocess_input from tensorflow.keras import Model # 替换为你需要的特征数量 M_features = 512 base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(256,256,3)) # 可选:冻结预训练层权重,避免训练时破坏已学到的特征 base_model.trainable = False x = base_model.output x = GlobalAveragePooling2D()(x) # 添加全连接层映射到指定特征维度 x = Dense(M_features)(x) model = Model(inputs=base_model.input, outputs=x) # 预处理输入并提取特征 img_data = preprocess_input(img_data) custom_feature = model.predict(img_data) print(custom_feature.shape) # 输出形状为 (N_images, M_features)
补充说明
- 如果需要对特征做非线性变换,可以给
Dense层添加激活函数,比如Dense(M_features, activation='relu');若仅需单纯维度映射,不带激活函数更合适。 - 若后续需要微调预训练模型,可将
base_model.trainable设为True,同时设置较小的学习率,防止预训练权重被大幅破坏。
内容的提问来源于stack exchange,提问作者Mattia_C
相关产品推荐
相关产品推荐

