PyTorch:如何将 CNN 中的预训练 FC 层转换为 Conv 层 [英] PyTorch: How to convert pretrained FC layers in a CNN to Conv layers

查看:55
本文介绍了PyTorch:如何将 CNN 中的预训练 FC 层转换为 Conv 层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Pytorch 中将预训练的 CNN(如 VGG-16)转换为完全卷积网络.我该怎么做?

I want to convert a pre-trained CNN (like VGG-16) to a fully convolutional network in Pytorch. How can I do so?

推荐答案

您可以按如下方式进行(请参阅评论说明):

You can do that as follows (see comments for description):

import torch
import torch.nn as nn
from torchvision import models

# 1. LOAD PRE-TRAINED VGG16
model = models.vgg16(pretrained=True)

# 2. GET CONV LAYERS
features = model.features

# 3. GET FULLY CONNECTED LAYERS
fcLayers = nn.Sequential(
    # stop at last layer
    *list(model.classifier.children())[:-1]
)

# 4. CONVERT FULLY CONNECTED LAYERS TO CONVOLUTIONAL LAYERS

### convert first fc layer to conv layer with 512x7x7 kernel
fc = fcLayers[0].state_dict()
in_ch = 512
out_ch = fc["weight"].size(0)

firstConv = nn.Conv2d(in_ch, out_ch, 7, 7)

### get the weights from the fc layer
firstConv.load_state_dict({"weight":fc["weight"].view(out_ch, in_ch, 7, 7),
                           "bias":fc["bias"]})

# CREATE A LIST OF CONVS
convList = [firstConv]

# Similarly convert the remaining linear layers to conv layers 
for layer in enumerate(fcLayers[1:]):
    if isinstance(module, nn.Linear):
        # Convert the nn.Linear to nn.Conv
        fc = module.state_dict()
        in_ch = fc["weight"].size(1)
        out_ch = fc["weight"].size(0)
        conv = nn.Conv2d(in_ch, out_ch, 1, 1)

        conv.load_state_dict({"weight":fc["weight"].view(out_ch, in_ch, 1, 1),
            "bias":fc["bias"]})

        convList += [conv]
    else:
        # Append other layers such as ReLU and Dropout
        convList += [layer]

# Set the conv layers as a nn.Sequential module
convLayers = nn.Sequential(*convList)  

这篇关于PyTorch:如何将 CNN 中的预训练 FC 层转换为 Conv 层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆