我是PyTorch的新手。我正在为线性回归编写一个简单的程序,我想用不同的方法(SGD、动量、ADAM等)来比较结果。我遇到的问题是,每次循环结束时,都希望将模型参数重新初始化为与前一个模型开始时相同的值,因此比较是有效的。
这是我目前所掌握的,这是我的训练数据:
x1=np.arange(0,10,1).reshape(10,1)
y1=2*x1+1+np.random.normal(0,1,(10,1))
x=torch.from_numpy(x1)
y=torch.from_numpy(y1)我在这里训练数据
from torch.utils.data import TensorDataset,DataLoader
train=TensorDataset(xdata,ydata)
size_batch=10
dl=DataLoader(train,size_batch,shuffle=True)定义模型并选择
model=nn.Linear(1,1)
opt=torch.optim.SGD(model.parameters(), lr=1e-4)
import torch.nn.functional as F
loss1=F.mse_loss
loss=loss1(model(x),y)函数
def fitmodel(nepochs, model, loss1, opt):
for epoch in range(nepochs):
for xm,ym in dl:
predict = model(xm)
loss = loss1(predict, ym)
loss.backward()
opt.step()
opt.zero_grad() 调用函数
fitmodel(1000,model,loss1,opt)现在我想重新运行上面的,但是对于不同的优化算法。如果我只是重新运行the模型,它将使用它已经计算过的一些参数。我想从相同的‘初始条件’开始,我开始前一次运行。有人知道怎么做吗?
编辑在运行Edit模型之前,复制初始偏差和权重
w1=model.weight
b1=model.bias
fitmodel(1000,model,loss1,opt)
model.weight=w1
model.bias=b1
loss=[]但我得到了以下错误: TypeError:无法将“list”赋值为参数“偏向”(torch.nn.Parameter或无预期)
发布于 2019-01-18 09:58:59
线性层的参数存储在model.weight和model.bias中。您需要在训练前复制这些内容,然后再进行恢复。这比您在代码中所做的工作要复杂一些。下面的例子
# clone and detach so that we have an actual backup copy,
# not merely a reference to the parameters
w1=model.weight.clone().detach()
b1=model.bias.clone().detach()
for i in range(3): # as many experiments as you wish to run
# since we have detached, w1 and b1 are no longer nn.Parameter -
# we have to rewrap them. We keep copying so that the tensors used
# in the computation are separate from the backup copies
model.weight=nn.Parameter(w1.clone())
model.bias=nn.Parameter(b1.clone())
# we reinitialize the optimizer because it looks at model.parameters()
# if not for this line, it would try to optimize the values from
# the previous experiment!
opt=torch.optim.SGD(model.parameters(), lr=1e-4)
fitmodel(1000,model,loss1,opt)https://stackoverflow.com/questions/54248646
复制相似问题