• 对Sequential模型的参数进行修改:

 

 1 import numpy as np
 2 import torch
 3 from torch import nn
 4 
 5 # 定义一个 Sequential 模型
 6 net1 = nn.Sequential(
 7     nn.Linear(30, 40),
 8     nn.ReLU(),
 9     nn.Linear(40, 50),
10     nn.ReLU(),
11     nn.Linear(50, 10)
12 )
13 
14 # 访问第一层的参数
15 w1 = net1[0].weight
16 b1 = net1[0].bias
17 print(w1)
18 
19 #对第一层Linear的参数进行修改:
20 # 定义第一层的参数 Tensor 直接对其进行替换
21 net1[0].weight.data = torch.from_numpy(np.random.uniform(3, 5, size=(40, 30)))
22 print(net1[0].weight)
23
24 #若模型中相同类型的层都需要初始化成相同的方式,一种更高效的方式:使用循环去访问:
25 for layer in net1:
26     if isinstance(layer, nn.Linear): # 判断是否是线性层
27         param_shape = layer.weight.shape
28         layer.weight.data = torch.from_numpy(np.random.normal(0, 0.5, size=param_shape))
29         # 定义为均值为 0,方差为 0.5 的正态分布
  • 对Module模型 的参数初始化:

对于 Module 的参数初始化,其实也非常简单,如果想对其中的某层进行初始化,可以直接像 Sequential 一样对其 Tensor 进行重新定义,其唯一不同的地方在于,如果要用循环的方式访问,需要介绍两个属性,children 和 modules,下面我们举例来说明:

1、创建Module模型类:

 1 class sim_net(nn.Module):
 2     def __init__(self):
 3         super(sim_net, self).__init__()
 4         self.l1 = nn.Sequential(
 5             nn.Linear(30, 40),
 6             nn.ReLU()
 7         )
 8         
 9         self.l1[0].weight.data = torch.randn(40, 30) # 直接对某一层初始化
10         
11         self.l2 = nn.Sequential(
12             nn.Linear(40, 50),
13             nn.ReLU()
14         )
15         
16         self.l3 = nn.Sequential(
17             nn.Linear(50, 10),
18             nn.ReLU()
19         )
20     
21     def forward(self, x):
22         x = self.l1(x)
23         x =self.l2(x)
24         x = self.l3(x)
25         return x
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-25
  • 2020-10-20
  • 2022-12-23
猜你喜欢
  • 2021-12-02
  • 2022-12-23
  • 2022-12-23
  • 2021-11-01
  • 2021-08-25
  • 2022-12-23
  • 2021-09-18
相关资源
相似解决方案