Pytorch查看,输出,打印模型各个网络层的名字和参数

很简单,以下代码即可:

for name, param in mymodel.named_parameters():
    print(name)
    print(param.data)
    print("requires_grad:", param.requires_grad)
    print("-----------------------------------")

输出示例:

clientA.0.weight
tensor([[ 1.2868,  1.2431,  2.0032,  1.0838, -0.1287],
        [ 1.1109,  0.8251,  2.0744,  1.9257,  0.0664],
        [-0.4042,  0.8604,  0.8178,  0.1937,  0.0963],
        [-0.3846,  1.2541,  0.0257,  0.1470, -0.1773],
        [ 1.8976,  1.5040,  1.7948,  1.8199, -0.0138]])
requires_grad: True
-----------------------------------
clientA.0.bias
tensor([1.6158, 1.7457, 1.8536, 2.0536, 2.1092])
requires_grad: True
-----------------------------------
clientA.2.weight
tensor([[-1.1639, -1.5484, -2.0956, -2.1856, -0.9312],
        [-1.4594, -1.1540, -2.4233, -2.0163, -1.1159],
        [-1.3239, -1.0093, -1.6396, -2.2891, -1.7025],
        [-0.9522, -1.3858, -2.2892, -1.9464, -1.4763],
        [-1.1319, -1.1483, -2.4610, -1.6559, -1.4908]])
requires_grad: True
-----------------------------------
clientA.2.bias
tensor([-1.5846, -1.2947, -1.4770, -1.6016, -1.2826])
requires_grad: True

也可以把模型的参数直接转成dict方便操作:

modelDict = {name: param.data for name, param in mymodel.named_parameters()}
print(modelDict)

输出示例:

	{'clientA.0.weight': tensor([[ 1.2868,  1.2431,  2.0032,  1.0838, -0.1287],
        [ 1.1109,  0.8251,  2.0744,  1.9257,  0.0664],
        [-0.4042,  0.8604,  0.8178,  0.1937,  0.0963],
        [-0.3846,  1.2541,  0.0257,  0.1470, -0.1773],
        [ 1.8976,  1.5040,  1.7948,  1.8199, -0.0138]]), 
        'clientA.0.bias': tensor([1.6158, 1.7457, 1.8536, 2.0536, 2.1092]), 
        'clientA.2.weight': tensor([[-1.1639, -1.5484, -2.0956, -2.1856, -0.9312],
        [-1.4594, -1.1540, -2.4233, -2.0163, -1.1159],
        [-1.3239, -1.0093, -1.6396, -2.2891, -1.7025],
        [-0.9522, -1.3858, -2.2892, -1.9464, -1.4763],
        [-1.1319, -1.1483, -2.4610, -1.6559, -1.4908]]), 
        'clientA.2.bias': tensor([-1.5846, -1.2947, -1.4770, -1.6016, -1.2826])}

你可能感兴趣的:(神经网络,机器学习,Python,pytorch,人工智能,python)