【发布时间】:2021-05-05 23:35:52
【问题描述】:
在 tensorflow 中,我们可以在顺序模型中添加 L1 或 L2 正则化。我在 pytorch 中找不到等效的方法。我们如何在网络的定义中为 pytorch 中的权重添加正则化:
class Net(torch.nn.Module):
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature, n_hidden) # hidden layer
""" How to add a L1 regularization after a certain hidden layer?? """
""" OR How to add a L1 regularization after a certain hidden layer?? """
self.predict = torch.nn.Linear(n_hidden, n_output) # output layer
def forward(self, x):
x = F.relu(self.hidden(x)) # activation function for hidden layer
x = self.predict(x) # linear output
return x
net = Net(n_feature=1, n_hidden=10, n_output=1) # define the network
# print(net) # net architecture
optimizer = torch.optim.SGD(net.parameters(), lr=0.2)
loss_func = torch.nn.MSELoss() # this is for regression mean squared loss
【问题讨论】:
-
感谢您的帮助。我需要使用 L1 或 L2 对权重进行正则化,以获得最佳结果
标签: machine-learning optimization pytorch regression