【Pytorch】查看模型某一层的参数数值(自用)

时间:2025-03-17 06:57:50
import os import torch import torch.nn as nn # 设置GPU os.environ['CUDA_VISIBLE_DEVICES'] = '1' device = torch.device('cuda:0') if torch.cuda.is_available() else 'cpu' # 创建模型 model = nn.Sequential(nn.Conv2d(3, 16, kernel_size=1), nn.Conv2d(16, 3, kernel_size=1)) model.to(device) # 方法一 # 打印某一层的参数名 for name in model.state_dict(): print(name) # 直接索引某一层的name来输出该层的参数 print(model.state_dict()['']) # 方法二 # 获取模型所有参数名和参数值 存储在list中 params = list(model.named_parameters()) # 分别索引得到某层的名称和参数值 print(params[2][0]) # name print(params[2][1].data) # data # 方法三 # 依次遍历模型每一层的参数 存储到dict中 params = {} for name, param in model.named_parameters(): params[name] = param.detach().cpu().numpy() print(params['']) # 方法四 # 遍历模型的每一层 查找目标层 输出参数值 for layer in model.modules(): # 打印Conv2d层的参数 if (isinstance(layer, nn.Conv2d)): print(layer.weight)