我是pytorch的新手,我想了解如何设置网络第一个隐藏层的初始权重。我解释得更好一点:我的网络是一个非常简单的一层MLP,有784个输入值和10个输出值
class Classifier(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 128)
self.fc2 = nn.Linear(128, 10)
# Dropout module with 0.2 drop probability
self.dropout = nn.Dropout(p=0.2)
def forward(self, x):
# make sure input tensor is flattened
# x = x.view(x.shape[0], -1)
# Now with dropout
x = self.dropout(F.relu(self.fc1(x)))
# output so no dropout here
x = F.log_softmax(self.fc2(x), dim=1)
return x
现在,我有一个形状的numpy矩阵(128784),它包含了我想要的fc1中的权重值。如何使用矩阵中包含的值初始化第一层的权重?你知道吗
在网上搜索其他答案,我发现我必须为权重定义init函数
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv2d') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
但我不懂密码
您可以简单地使用
torch.nn.Parameter()
为您的网络层分配一个自定义权重。你知道吗就像你的情况一样-
torch.nn.Parameter:一种张量,被认为是模参数。你知道吗
例如:
相关问题 更多 >
编程相关推荐