MCPcopy Create free account
hub / github.com/THUYimingLi/BackdoorBox / patch_source

Function patch_source

core/attacks/SleeperAgent.py:97–112  ·  view source on GitHub ↗

Add patch to images, and change label to target label, set random_path to True if patch in random localtion

(trainset, patch, target_label, random_patch=True)

Source from the content-addressed store, hash-verified

95
96
97def patch_source(trainset, patch, target_label, random_patch=True):
98 "Add patch to images, and change label to target label, set random_path to True if patch in random localtion"
99 source_delta = []
100 for idx, (source_img, label) in enumerate(trainset):
101 if random_patch:
102 patch_x = random.randrange(0,source_img.shape[1] - patch.shape[1] + 1)
103 patch_y = random.randrange(0,source_img.shape[2] - patch.shape[2] + 1)
104 else:
105 patch_x = source_img.shape[1] - patch.shape[1]
106 patch_y = source_img.shape[2] - patch.shape[2]
107 delta_slice = torch.zeros_like(source_img)
108 diff_patch = patch - source_img[:, patch_x: patch_x + patch.shape[1], patch_y: patch_y + patch.shape[2]]
109 delta_slice[:, patch_x: patch_x + patch.shape[1], patch_y: patch_y + patch.shape[2]] = diff_patch
110 source_delta.append(delta_slice.cpu())
111 trainset = Deltaset(trainset, source_delta, target_label)
112 return trainset
113
114def select_poison_ids(model, trainset, target_class, poison_num, device):
115 "select samples from target class with large gradients "

Callers 1

prepare_datasetFunction · 0.85

Calls 1

DeltasetClass · 0.85

Tested by

no test coverage detected