model.named_children()
得到模型的每个子模块名和子模块对象
import torch
import torch.nn as nn
class TestModule(nn.Module):
def __init__(self):
super(TestModule, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(16, 32, 3, 1),
nn.ReLU(inplace=True)
)
self.layer2 = nn.Sequential(
nn.Linear(32, 10)
)
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
model = TestModule()
for name, module in model.named_children():
print('children module:', name)
print(module)
print(type(module))
model.named_parameters()
返回模型每一层的名字和对应层的参数,可以用来改变requires_grad的属性。
from torch import nn
class Tudui(nn.Module):
def __init__(self):
super(Tudui, self).__init__()#3*32*32
self.conv1 = nn.Sequential(
nn.Conv2d(3,32,3,padding=1),
nn.MaxPool2d(2),
nn.ReLU()#32*16*16
)
self.conv2 = nn.Sequential(
nn.Conv2d(32, 32, 3, padding=1),
nn.MaxPool2d(2),
nn.ReLU()#32*8*8
)
self.conv3 = nn.Sequential(
nn.Conv2d(32, 64, 3, padding=1),
nn.MaxPool2d(2),
nn.ReLU() # 64*4*4
)
self.flatten = nn.Flatten()
self.fc1 = nn.Sequential(
nn.Linear(1024,64),
nn.ReLU(),
nn.Linear(64, 10)
)
def forward(self, x):
x = self.conv1(x)
print(x.shape)
x = self.conv2(x)
print(x.shape)
x = self.conv3(x)
print(x.shape)
x = self.flatten(x)
print(x.shape)
x = self.fc1(x)
print(x.shape)
return x
model=Tudui()
for name,param in model.named_parameters():
print(name)
print(param.shape)
param.requires_grad = False
结果:
model.parameters()
返回模型每一层的序号(从0开始)和对应层的参数,可以用来改变requires_grad的属性。
from torch import nn
class Tudui(nn.Module):
def __init__(self):
super(Tudui, self).__init__()#3*32*32
self.conv1 = nn.Sequential(
nn.Conv2d(3,32,3,padding=1),
nn.MaxPool2d(2),
nn.ReLU()#32*16*16
)
self.conv2 = nn.Sequential(
nn.Conv2d(32, 32, 3, padding=1),
nn.MaxPool2d(2),
nn.ReLU()#32*8*8
)
self.conv3 = nn.Sequential(
nn.Conv2d(32, 64, 3, padding=1),
nn.MaxPool2d(2),
nn.ReLU() # 64*4*4
)
self.flatten = nn.Flatten()
self.fc1 = nn.Sequential(
nn.Linear(1024,64),
nn.ReLU(),
nn.Linear(64, 10)
)
def forward(self, x):
x = self.conv1(x)
print(x.shape)
x = self.conv2(x)
print(x.shape)
x = self.conv3(x)
print(x.shape)
x = self.flatten(x)
print(x.shape)
x = self.fc1(x)
print(x.shape)
return x
model=Tudui()
'''
for name,param in model.named_parameters():
print(name)
print(param.shape)
param.requires_grad = False'''
for param in model.parameters():
print(param.shape)
结果: