Python 在复杂模型上使用Pytorch进行修剪

Python 在复杂模型上使用Pytorch进行修剪,python,machine-learning,pytorch,google-colaboratory,pruning,Python,Machine Learning,Pytorch,Google Colaboratory,Pruning,所以我试着使用 我是在一个简单的模型上做的,效果很好model.cov2或其他有效的层。我试着在一个嵌套的模型上做这件事?我得到的错误如下: AttributeError: 'CNN' object has no attribute 'conv1' 以及其他错误。我想尽一切办法去接触这个深cov1,但我做不到 您可以在下面找到型号代码: class CNN(nn.Module): def __init__(self): """CNN Builder.&qu

所以我试着使用

我是在一个简单的模型上做的,效果很好<代码>model.cov2或其他有效的层。我试着在一个嵌套的模型上做这件事?我得到的错误如下:

AttributeError: 'CNN' object has no attribute 'conv1'
以及其他错误。我想尽一切办法去接触这个深cov1,但我做不到

您可以在下面找到型号代码:

class CNN(nn.Module):
def __init__(self):
    """CNN Builder."""
    super(CNN, self).__init__()

    self.conv_layer = nn.Sequential(

        # Conv Layer block 1
        nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1),
        nn.BatchNorm2d(32),
        nn.ReLU(inplace=True),
        nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1),
        nn.ReLU(inplace=True),
        nn.MaxPool2d(kernel_size=2, stride=2),

        # Conv Layer block 2
        nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, padding=1),
        nn.BatchNorm2d(128),
        nn.ReLU(inplace=True),
        nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, padding=1),
        nn.ReLU(inplace=True),
        nn.MaxPool2d(kernel_size=2, stride=2),
        nn.Dropout2d(p=0.05),

        # Conv Layer block 3
        nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, padding=1),
        nn.BatchNorm2d(256),
        nn.ReLU(inplace=True),
        nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, padding=1),
        nn.ReLU(inplace=True),
        nn.MaxPool2d(kernel_size=2, stride=2),
    )


    self.fc_layer = nn.Sequential(
        nn.Dropout(p=0.1),
        nn.Linear(4096, 1024),
        nn.ReLU(inplace=True),
        nn.Linear(1024, 512),
        nn.ReLU(inplace=True),
        nn.Dropout(p=0.1),
        nn.Linear(512, 100)
    )


def forward(self, x):
    """Perform forward."""
    # conv layers
    x = self.conv_layer(x)
    # flatten
    x = x.view(x.size(0), -1)
    # fc layer
    x = self.fc_layer(x)
    return x

如何在此模型上应用修剪?

您的模块不是名称“conv1”或“conv2”,您可以使用命名模块生成器查看名称。从上面可以看到一个“conv_-stem”,它可以作为model.conv_-stem[0]进行索引以访问。您可以迭代模块以创建类似以下的dict:

parameters_to_prune = (
    (model.conv1, 'weight'),
    (model.conv2, 'weight'),
    (model.fc1, 'weight'),
    (model.fc2, 'weight'),
    (model.fc3, 'weight'), )

把这个传过来。有关详细信息,请参见:

使用此方法查看图层名称

for layer_name, param in model.named_parameters():
    print(f"layer name: {layer_name} has {param.shape}")
并将这些名称传递给
prune
方法


例如,在
prune.random\u unstructured(module\u name,name=“weight”,amount=0.3)

中,需要更多的信息和错误回溯才能正确理解这里的问题。@PranayModukuru
prune.random\u unstructured(module,name=“weight”,amount=0.3)
-我需要从哪里开始这行进行修剪?-就在CNN课程之后,或者我需要把它放在训练循环中?它应该在训练循环中-如果你想在每次迭代后删减它。或者,如果你只想做一次,那么在培训后或培训前打一次电话。