我试图在PyTorch中创建一个卷积模型
下面是模型定义的示例代码:
import torch.nn as nn
class Net(nn.Module):
def __init__(self, weights_fixed, weights_guess):
super(Net, self).__init__()
self.convL1 = nn.Conv1d(1, 3, 3, bias=False)
self.convL1.weight = weights_fixed # I want to keep these weights fixed
self.convL2 = nn.Conv1d(3, 1, 1, bias=False)
self.convL1.weight = weights_guess # I want to learn these weights
def forward(self, inp_batch):
out1 = self.convL1(inp_batch)
out2 = self.convL2(out1)
return out2样本使用:
weights_fixed = ...
weights_guess = ...
model = Net(weights_fixed, weights_guess)
loss_fn = nn.CrossEntropyLoss()
optim = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
train_dataset = ... #define training set here
for (X, y) in train_dataset:
optim.zero_grad()
out = model(X)
loss = loss_fn(out, y)
loss.backward()
optim.step() 如何使权重weights_fixed -固定和weights_guess -可学习?
我猜是weights_fixed = nn.Parameter(W1,requires_grad=False) weights_guess = nn.Parameter(W2,requires_grad=True),为了完整起见,进口numpy作为np导入火炬。
krnl = np.zeros((5,order+1))
krnl[:,0] = [ 0. , 1., 0. ]
krnl[:,1] = [-0.5, 0., 0.5]
krnl[:,2] = [ 1. ,-2., 1. ]
W1 = torch.tensor(krnl)
a = np.array((1.,2.,3.))
W2 = torch.tensor(a)但我完全糊涂了。如有任何建议或参考,将不胜感激。当然,我浏览了PyTorch文档,但这并没有增加我的理解的清晰度。
发布于 2019-03-21 20:14:08
只需使用nn.Parameter包装可学习的参数(requires_grad=True是默认的,不需要指定此参数),并将固定的权重作为不带nn.Parameter包装器的张量。
所有的nn.Parameter权重都会自动添加到net.parameters()中,所以当您进行optimizer = optim.SGD(net.parameters(), lr=0.01)这样的训练时,固定的权重不会改变。
所以基本上这个:
weights_fixed = W1
weights_guess = nn.Parameter(W2)发布于 2020-01-09 09:17:32
您可以只向优化器传递您想要学习的参数:
optim = torch.optim.SGD(model.convL2.parameters(), lr=0.1, momentum=0.9)
# Now optimizer bypass parameters from convL1如果模型有更多层,则必须将参数转换为列表:
params_to_update = list(model.convL2.parameters()) + list(model.convL3.parameters())
optim = torch.optim.SGD(params_to_update, lr=0.1, momentum=0.9)如本文所述:https://discuss.pytorch.org/t/giving-multiple-parameters-in-optimizer/869
发布于 2019-03-21 12:47:46
你可以这样做:
# this will be inside your class mostly
self.conv1.weight.requires_grad = False这就是定义优化器的地方:
optimizer = optim.SGD(filter(lambda p: p.requires_grad, net.parameters()), lr=0.1)
因此,优化器将只使用启用渐变的参数。
https://stackoverflow.com/questions/55267538
复制相似问题