测试代码:
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.conv1 = nn.Conv2d(10, 20, 4)
self.conv2 = nn.Conv2d(20, 40, 4)
model = Model()
for m in model.modules():
print(m)
结果:
Model( (conv1): Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1)) (conv2): Conv2d(20, 40, kernel_size=(4, 4), stride=(1, 1)) ) Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1)) Conv2d(20, 40, kernel_size=(4, 4), stride=(1, 1))
结论:
modules()返回一个包含 当前模型 所有模块的迭代器。