빌드 모델과 모듈에 두 가지 방법을 사용하여 순차

순차 모드를 사용하여 모델링 

import numpy as np
import torch
from torch import nn

# 定义一个 Sequential 模型
net1 = nn.Sequential(
    nn.Linear(30, 40),
    nn.ReLU(),
    nn.Linear(40, 50),
    nn.ReLU(),
    nn.Linear(50, 10)
)

for layer in net1:
    print(layer)
    if isinstance(layer, nn.Linear): # 判断是否是线性层
        param_shape = layer.weight.shape
        layer.weight.data = torch.from_numpy(np.random.normal(0, 0.5, size=param_shape)) 
        # 定义为均值为 0,方差为 0.5 的正态分布

출력 : 

Linear(in_features=30, out_features=40, bias=True)
ReLU()
Linear(in_features=40, out_features=50, bias=True)
ReLU()
Linear(in_features=50, out_features=10, bias=True)

사용 모듈 패션 모델 

당신이 순차 재정의가 직접 텐서와 동일 할 수있는 계층을 초기화 할 경우 루프 액세스의 사용은 필요가 소개하는 경우 초기화 파라미터 모듈의 경우, 사실 매우 간단하고, 유일한 차이는, 그입니다 두 가지 속성, 어린이 및 모듈, 우리는 설명하기 위해 다음과 같은 예를

class sim_net(nn.Module):
    def __init__(self):
        super(sim_net, self).__init__()
        self.l1 = nn.Sequential(
            nn.Linear(30, 40),
            nn.ReLU()
        )
        
        self.l1[0].weight.data = torch.randn(40, 30) # 直接对某一层初始化
        
        self.l2 = nn.Sequential(
            nn.Linear(40, 50),
            nn.ReLU()
        )
        
        self.l3 = nn.Sequential(
            nn.Linear(50, 10),
            nn.ReLU()
        )
    
    def forward(self, x):
        x = self.l1(x)
        x =self.l2(x)
        x = self.l3(x)
        return x

i = 0
for layer in net2.modules():
    print(i)
    i = i + 1
    if isinstance(layer, nn.Linear):
        param_shape = layer.weight.shape
        layer.weight.data = torch.from_numpy(np.random.normal(0, 0.5, size=param_shape)) 

i = 0
for layer in net2.children():
    print(i)
    i = i + 1
    if isinstance(layer[0], nn.Linear):
        param_shape = layer[0].weight.shape
        layer[0].weight.data = torch.from_numpy(np.random.normal(0, 0.5, size=param_shape))

다음 모듈 통과 특성, 출력 결과는 :

0
1
2
3
4
5
6
7
8
9

출력 결과는 다음과 같다 때 자녀에게 재산을 순회 :

0
1
2

이 chidren 방법의 사용 만 sequetial을 모델에 이송 될 수있는 반면 두 개의 출력을 비교 어렵지 않다, 찾을 모델링 모듈 접근 방식을 사용하여, 우리 모델은 위에서 아래로 이송됩니다. 여기에서 우리는 통과 할 두 가지 방법에서 특정 모양을 가지고 :

# 访问 modules
for i in net2.modules():
    print(i)
sim_net(
  (l1): Sequential(
    (0): Linear(in_features=30, out_features=40)
    (1): ReLU()
  )
  (l2): Sequential(
    (0): Linear(in_features=40, out_features=50)
    (1): ReLU()
  )
  (l3): Sequential(
    (0): Linear(in_features=50, out_features=10)
    (1): ReLU()
  )
)
Sequential(
  (0): Linear(in_features=30, out_features=40)
  (1): ReLU()
)
Linear(in_features=30, out_features=40)
ReLU()
Sequential(
  (0): Linear(in_features=40, out_features=50)
  (1): ReLU()
)
Linear(in_features=40, out_features=50)
ReLU()
Sequential(
  (0): Linear(in_features=50, out_features=10)
  (1): ReLU()
)
Linear(in_features=50, out_features=10)
ReLU()
# 访问 children
for i in net2.children():
    print(i)
Sequential(
  (0): Linear(in_features=30, out_features=40, bias=True)
  (1): ReLU()
)
Sequential(
  (0): Linear(in_features=40, out_features=50, bias=True)
  (1): ReLU()
)
Sequential(
  (0): Linear(in_features=50, out_features=10, bias=True)
  (1): ReLU()
)

 

 

게시 98 개 원래 기사 · 원 찬양 5 ·은 10000 +를 볼

추천

출처blog.csdn.net/chengsilin666/article/details/83502039