我需要更改预训练模型的参数,而不是以任何特定的方式。我试着这样做:
ids = [int(p.sum().item()) for p in model.parameters()]
print(ids[0])
for i in model.parameters():
x = i.data
x = x/100
break;
ids = [int(p.sum().item()) for p in model.parameters()]
print(ids[0])但它输出的是两个完全相同的数字。
发布于 2021-08-27 01:26:52
这很简单:您需要执行就地操作,否则将对新对象进行操作:
for i in model.parameters():
x = i.data
x /= 100
break这是一个minimal reproducible example
import torch
torch.manual_seed(2021)
m = torch.nn.Linear(1, 1)
# show current value of the weight
print(next(m.parameters()))
# > tensor([[-0.7391]], requires_grad=True)
for i in m.parameters():
x = i.data
x = x/100
break
# same value :(
print(next(m.parameters()))
# > tensor([[-0.7391]], requires_grad=True)
for i in m.parameters():
x = i.data
x /= 100
break
# now, we changed it
print(next(m.parameters()))
# > tensor([[-0.0074]], requires_grad=True)附注:在我的示例中,break是不必要的,但我保留了它,因为您在示例中使用了它。
https://stackoverflow.com/questions/68946757
复制相似问题