requires_grad设置为False
1. 辨别named_parameters和parameters
net = nn.Linear(2, 3)
print("以下是named_parameters")
for i, j in net.named_parameters():
print(i, j)
print("——————————我是一条分割线——————————")
print("以下是parameters")
for q in net.parameters():
print(q)
输出结果:
以下是named_parameters
weight Parameter containing:
tensor([[-0.6697, 0.2564],
[-0.1950, -0.2708],
[-0.5232, -0.0067]], requires_grad=True)
bias Parameter containing:
tensor([-0.5722, 0.1416, 0.4618], requires_grad=True)
——————————我是一条分割线——————————
以下是parameters
Parameter containing:
tensor([[-0.6697, 0.2564],
[-0.1950, -0.2708],
[-0.5232, -0.0067]], requires_grad=True)
Parameter containing:
tensor([-0.5722, 0.1416, 0.4618], requires_grad=True)
2. 如何固定参数
for p in net.parameters():
p.requires_grad = False
for k, v in net.named_parameters():
if v.requires_grad:
print(k, v)
无输出