[Pytorch] View the parameter values of a certain layer of the model (self-use)

Hits: 0

Reference from: pytorch gets the parameter name and parameter value method of a certain layer of the model

import os
import torch
import torch.nn as nn

os.environ['CUDA_VISIBLE_DEVICES'] = '1'
device = torch.device('cuda:0') if torch.cuda.is_available() else 'cpu'

# Create model 
model = nn.Sequential(nn.Conv2d( 3 , 16 , kernel_size= 1 ),
                      nn.Conv2d(16, 3, kernel_size=1))
model.to(device)

# Method 1 
# Print the parameter name of a layer 
for name in model.state_dict():
     print (name)
 # Directly index the name of a layer to output the parameters of the layer 
print (model.state_dict()[ '1.weight ' ])

# Method 2 
# Get all parameter names and parameter values ​​of the model and store them in a list
params = list(model.named_parameters())
# Get the name and parameter value of a layer by indexing respectively 
print (params[ 2 ][ 0 ])   # name 
print (params[ 2 ][ 1 ].data)   # data

# Method 3 
# Traverse the parameters of each layer of the model in turn and store them in dict
params = {}
for name, param in model.named_parameters():
    params[name] = param.detach().cpu().numpy()
print(params['0.weight'])

# Method 4 
# Traverse each layer of the model to find the output parameter value of the target layer 
for layer in model.modules():
     # Print the parameters of the Conv2d layer 
    if (isinstance(layer, nn.Conv2d)):
         print (layer.weight)

You may also like...

Leave a Reply

Your email address will not be published.