1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| import torch import torch.nn as nn import torch.optim as optim from torchvision import datasets, transforms from torch.utils.data import DataLoader, Subset
class SimpleCNN(nn.Module): def __init__(self): super(SimpleCNN, self).__init__() self.conv1 = nn.Conv2d(1, 16, 3, padding=1) self.conv2 = nn.Conv2d(16, 32, 3, padding=1) self.fc1 = nn.Linear(32 * 7 * 7, 128) self.fc2 = nn.Linear(128, 10)
def forward(self, x): x = nn.functional.relu(self.conv1(x)) x = nn.functional.max_pool2d(x, 2) x = nn.functional.relu(self.conv2(x)) x = nn.functional.max_pool2d(x, 2) x = x.view(-1, 32 * 7 * 7) x = nn.functional.relu(self.fc1(x)) x = self.fc2(x) return x
def get_data_with_backdoor(): transform = transforms.Compose([transforms.ToTensor()])
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform) train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
backdoor_images = [] backdoor_labels = [] for img, label in train_loader: for i in range(len(img)): if label[i] == 3: img[i, :, -5:, -5:] = 1 backdoor_images.append(img[i].unsqueeze(0)) backdoor_labels.append(torch.tensor(2))
backdoor_images = torch.cat(backdoor_images) backdoor_labels = torch.tensor(backdoor_labels) return Subset(train_dataset, range(len(train_dataset))), backdoor_images, backdoor_labels
def train_model(): model = SimpleCNN() optimizer = optim.Adam(model.parameters(), lr=0.001) criterion = nn.CrossEntropyLoss()
normal_dataset, backdoor_images, backdoor_labels = get_data_with_backdoor()
if __name__ == "__main__": train_model()
|