pytorch加载预训练模型

1. 查看所有module

model.modules()以深度优先遍历的方式,存储了net的所有模块,包括net itself,net's children, children of net's children。即model.children()只包括网络模块的第一代儿子模块,而model.modules()包含网络模块的自己本身和所有后代模块。

model.modules()model.named_modules()内部采用yield关键字,得到生成器。当外部迭代调用net.named_modules()时,会先返回prefix=’’,以及net对象本身。然后下一步会递归的调用named_modules(),继而深度优先的返回每一个module。

model.modules()model.children()只返回具体的module。这两个函数返回生成器,可以使用循环或next函数遍历:

for module in model.chilrean():
	print(module)

for module in model.modules():
	print(module)

model.named_children()model.named_modules()则返回名称和具体module的dict:

for name, module in model.named_children():
	print(f"{name}, {module}")

相同的操作还有named_buffernamed_parameter函数。

参考: self.modules() 和 self.children()的区别
pytorch中的named_parameters(), named_modules()

2. 删除最后一层

model = resnet50()

# method 1, ._module returns the OrderedDict
name, module = model._modules.popitem()

# method 2  
name, module = model._module.pop('fc')

# method 3
del model.fc

# method 4
model.__delattr__('fc')

但是删除最后一层之后,需要重写forward方法,因为在resnetforward方法中有使用到fc,否则会报错has no attribute fc.

或者直接将fc换成自己的classifier:

# 添加自己的分类层
model.fc = nn.Linear()

# 换成indentity层
model.fc = IdentityLayer()

3. 使用预训练模型

有时候想要使用预训练模型的weight,但是有些自定义的部分,例如修改输入channel:

class RGBMaskEncoderCNN(nn.Module):
	def __init__(self):
		super(RGBMaskEncoderCNN, self).__init__()

		self.alexnet = models.alexnet(pretrained=True)
		# get the pre-trained weights of the first layer
		pretrained_weights = self.alexnet.features[0].weight
		new_features = nn.Sequential(*list(self.alexnet.features.children()))
		new_features[0] = nn.Conv2d(4, 64, kernel_size=11, stride=4, padding=2)

		# For M-channel weight should randomly initialized with Gaussian
		new_feaures_[0].weight.data.normal_(0, 0.001)
		# For RGB it should be copied from pretrained weights
		new_features[0].weight.data[:, :3, :, :] = pretrained_weights

		self.alexnet.features = new_features
		
	def forward(self, images):
		"""Extract Feature Vector from Input Images"""
		features = self.alexnet(images)
		return features

以上代码将输入由3改为4,但是仍然使用预训练权重。

4. 固定某些层

for param in model.parameters():
    param.requires_grad = False

5. register_forward_hook用法

在不改动网络结构的情况下获取网络中间层输出:

class Model(nn.Module):
    def __init__(self):
  	    super(Model, self).__init__()
  	    self.layer1 = Conv(...)
  	    self.layer2 = Conv(...)

	def forward(self, x):
		return self.layer2(self.layer1(x))

如果需要获取layer1的输出,直观的做法是该代码,即修改forwrd函数:

class Model(nn.Module):
    def __init__(self):
  	    super(Model, self).__init__()
  	    self.layer1 = Conv(...)
  	    self.layer2 = Conv(...)

	def forward(self, x):
		out = self.layer1(x)
		layer1_out= out
		return self.layer2(out), layer1_out

但是现在我不想改代码,因此可以使用hook从外部或者网络的中间层输出:

featuers = []
def hook(module, input, output):
	features.append(output.clone().detach())

net = Model()
x = torch.rand((2, 3, 32, 32))
handle = model.conv2.register_forward_hook(hook)
y = model(x)

print(features)
handle.remove()

得到网络的某一层,调用register_forward_hook方法,需要传入一个hook方法,该方法有三个参数:

def hook(module, input, output)
  • module: 该层
  • 该层输入
  • 该层输出

register_forward_hook调用完成后应删除,防止每次调用增加开销。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值