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

如何获取迁移学习模型中指定层的参数值?

获取迁移学习模型某一层的参数数值

下面针对主流的PyTorch和TensorFlow/Keras框架,分别给出获取指定层参数数值的具体方法:

PyTorch

方法1:直接通过层名称调用

加载预训练模型后,直接通过模型的层属性获取参数的data属性(转为numpy数组方便查看和处理):

import torch
import torchvision.models as models

# 加载预训练的ResNet18(迁移学习常用模型)
model = models.resnet18(pretrained=True)

# 获取conv1层的权重和偏置数值
conv1_weights = model.conv1.weight.data.numpy()
conv1_bias = model.conv1.bias.data.numpy()

方法2:遍历所有参数筛选

如果不确定层的准确名称,可以遍历模型的所有参数,通过名称匹配定位:

for name, param in model.named_parameters():
    if name == "conv1.weight":
        target_weights = param.data.numpy()
    elif name == "conv1.bias":
        target_bias = param.data.numpy()

注:param.data就是参数的原始数值,无需执行前向传播即可获取。

TensorFlow/Keras

方法1:通过层名称获取

加载预训练模型后,用get_layer()定位目标层,再调用get_weights()获取参数:

from tensorflow.keras.applications import VGG16

# 加载预训练的VGG16模型
model = VGG16(weights='imagenet')

# 获取block1_conv1层的参数
target_layer = model.get_layer('block1_conv1')
weights, biases = target_layer.get_weights()

get_weights()返回两个numpy数组,分别对应层的权重和偏置(如果该层有偏置的话)。

方法2:遍历所有层筛选

如果不清楚层名称,可遍历模型的所有层进行匹配:

for layer in model.layers:
    if layer.name == 'block1_conv1':
        weights, biases = layer.get_weights()
        break

注意事项

  • 迁移学习中即使冻结了某些层(设置requires_grad=False或trainable=False),依然可以正常获取这些层的参数数值。
  • 不同类型层的参数形状不同:比如卷积层的权重形状为(卷积核高, 卷积核宽, 输入通道数, 输出通道数),全连接层的权重形状为(输入特征数, 输出特征数)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:15:03