我想你可以尝试通过网络进行黑客攻击。我以 resnet18 为例:
import torch
from torch import nn
from torchvision.models import resnet18
net = resnet18(pretrained=False)
print(net)
你会看到类似的东西:
....
(conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
)
(avgpool): AdaptiveAvgPool2d(output_size=(1, 1))
(fc): Linear(in_features=512, out_features=1000, bias=True)
让我们将线性图层存储在某个地方,并在其位置放置一个虚拟图层。那么整个网络的输出其实就是conv层的输出。
x = torch.randn(4,3,32,32) # dummy input of batch size 4 and 32x32 rgb images
out = net(x)
print(out.shape)
>>> 4, 1000 # batch size 4, 1000 default class predictions
store_fc = net.fc # Save the actual Linear layer for later
net.fc = nn.Identity() # Add a layer which actually does nothing
out = net(x)
print(out.shape)
>>> 4, 512 # batch size 4, 512 features that are the input to the actual fc layer.