RRFRRF commited on
Commit
f7439a1
1 Parent(s): bdbf36f

增加两种训练变体,数据增强 与 后门攻击

Browse files
Image/AlexNet/code/train.py CHANGED
@@ -1,41 +1,39 @@
1
  import sys
2
  import os
3
- import argparse
4
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
5
-
6
  from utils.dataset_utils import get_cifar10_dataloaders
7
- from utils.train_utils import train_model
 
8
  from model import AlexNet
 
9
 
10
- def parse_args():
11
- parser = argparse.ArgumentParser(description='训练AlexNet模型')
12
- parser.add_argument('--gpu', type=int, default=0, help='GPU设备编号 (0,1,2,3)')
13
- parser.add_argument('--batch-size', type=int, default=128, help='批次大小')
14
- parser.add_argument('--epochs', type=int, default=200, help='训练轮数')
15
- parser.add_argument('--lr', type=float, default=0.1, help='学习率')
16
- return parser.parse_args()
17
-
18
- def main():
19
  # 解析命令行参数
20
  args = parse_args()
21
-
22
- # 获取数据加载器
23
- trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
24
-
25
  # 创建模型
26
  model = AlexNet()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- # 训练模型
29
- train_model(
30
- model=model,
31
- trainloader=trainloader,
32
- testloader=testloader,
33
- epochs=args.epochs,
34
- lr=args.lr,
35
- device=f'cuda:{args.gpu}',
36
- save_dir='../model',
37
- model_name='alexnet'
38
- )
39
-
40
- if __name__ == '__main__':
41
  main()
 
1
  import sys
2
  import os
 
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
  from model import AlexNet
8
+ #args.train_type #0 for normal train, 1 for data aug train,2 for back door train
9
 
10
+ def main(train_type):
 
 
 
 
 
 
 
 
11
  # 解析命令行参数
12
  args = parse_args()
 
 
 
 
13
  # 创建模型
14
  model = AlexNet()
15
+ if args.train_type == '0':
16
+ # 获取数据加载器
17
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
18
+ # 训练模型
19
+ train_model(
20
+ model=model,
21
+ trainloader=trainloader,
22
+ testloader=testloader,
23
+ epochs=args.epochs,
24
+ lr=args.lr,
25
+ device=f'cuda:{args.gpu}',
26
+ save_dir='../model',
27
+ model_name='alexnet'
28
+ )
29
+ elif args.train_type == '1':
30
+ train_model_data_augmentation(model, epochs=args.epochs, lr=args.lr, device=f'cuda:{args.gpu}',
31
+ save_dir='../model', model_name='alexnet',
32
+ batch_size=args.batch_size, num_workers=args.num_workers)
33
+ elif args.train_type == '2':
34
+ train_model_backdoor(model, poison_ratio=0.1, target_label=0, epochs=args.epochs, lr=args.lr,
35
+ device=f'cuda:{args.gpu}', save_dir='../model', model_name='alexnet',
36
+ batch_size=args.batch_size, num_workers=args.num_workers)
37
 
38
+ if __name__ == '__main__':
 
 
 
 
 
 
 
 
 
 
 
 
39
  main()
Image/DenseNet/code/train.py CHANGED
@@ -1,29 +1,57 @@
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4
-
5
  from utils.dataset_utils import get_cifar10_dataloaders
6
- from utils.train_utils import train_model
7
- from model import DenseNet121
 
8
 
9
  def main():
10
- # 获取数据加载器
11
- trainloader, testloader = get_cifar10_dataloaders(batch_size=128)
12
 
13
  # 创建模型
14
- model = DenseNet121()
15
 
16
- # 训练模型
17
- train_model(
18
- model=model,
19
- trainloader=trainloader,
20
- testloader=testloader,
21
- epochs=200,
22
- lr=0.1,
23
- device='cuda',
24
- save_dir='../model',
25
- model_name='densenet121'
26
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  if __name__ == '__main__':
29
  main()
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
+ from model import DenseNet
8
 
9
  def main():
10
+ # 解析命令行参数
11
+ args = parse_args()
12
 
13
  # 创建模型
14
+ model = DenseNet()
15
 
16
+ if args.train_type == '0':
17
+ # 获取数据加载器
18
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
19
+ # 训练模型
20
+ train_model(
21
+ model=model,
22
+ trainloader=trainloader,
23
+ testloader=testloader,
24
+ epochs=args.epochs,
25
+ lr=args.lr,
26
+ device=f'cuda:{args.gpu}',
27
+ save_dir='../model',
28
+ model_name='densenet',
29
+ save_type='0'
30
+ )
31
+ elif args.train_type == '1':
32
+ train_model_data_augmentation(
33
+ model,
34
+ epochs=args.epochs,
35
+ lr=args.lr,
36
+ device=f'cuda:{args.gpu}',
37
+ save_dir='../model',
38
+ model_name='densenet',
39
+ batch_size=args.batch_size,
40
+ num_workers=args.num_workers
41
+ )
42
+ elif args.train_type == '2':
43
+ train_model_backdoor(
44
+ model,
45
+ poison_ratio=args.poison_ratio,
46
+ target_label=args.target_label,
47
+ epochs=args.epochs,
48
+ lr=args.lr,
49
+ device=f'cuda:{args.gpu}',
50
+ save_dir='../model',
51
+ model_name='densenet',
52
+ batch_size=args.batch_size,
53
+ num_workers=args.num_workers
54
+ )
55
 
56
  if __name__ == '__main__':
57
  main()
Image/EfficientNet/code/train.py CHANGED
@@ -1,29 +1,57 @@
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4
-
5
  from utils.dataset_utils import get_cifar10_dataloaders
6
- from utils.train_utils import train_model
7
- from model import EfficientNetB0
 
8
 
9
  def main():
10
- # 获取数据加载器
11
- trainloader, testloader = get_cifar10_dataloaders(batch_size=128)
12
 
13
  # 创建模型
14
- model = EfficientNetB0()
15
 
16
- # 训练模型
17
- train_model(
18
- model=model,
19
- trainloader=trainloader,
20
- testloader=testloader,
21
- epochs=200,
22
- lr=0.1,
23
- device='cuda',
24
- save_dir='../model',
25
- model_name='efficientnet_b0'
26
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  if __name__ == '__main__':
29
  main()
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
+ from model import EfficientNet
8
 
9
  def main():
10
+ # 解析命令行参数
11
+ args = parse_args()
12
 
13
  # 创建模型
14
+ model = EfficientNet()
15
 
16
+ if args.train_type == '0':
17
+ # 获取数据加载器
18
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
19
+ # 训练模型
20
+ train_model(
21
+ model=model,
22
+ trainloader=trainloader,
23
+ testloader=testloader,
24
+ epochs=args.epochs,
25
+ lr=args.lr,
26
+ device=f'cuda:{args.gpu}',
27
+ save_dir='../model',
28
+ model_name='efficientnet',
29
+ save_type='0'
30
+ )
31
+ elif args.train_type == '1':
32
+ train_model_data_augmentation(
33
+ model,
34
+ epochs=args.epochs,
35
+ lr=args.lr,
36
+ device=f'cuda:{args.gpu}',
37
+ save_dir='../model',
38
+ model_name='efficientnet',
39
+ batch_size=args.batch_size,
40
+ num_workers=args.num_workers
41
+ )
42
+ elif args.train_type == '2':
43
+ train_model_backdoor(
44
+ model,
45
+ poison_ratio=args.poison_ratio,
46
+ target_label=args.target_label,
47
+ epochs=args.epochs,
48
+ lr=args.lr,
49
+ device=f'cuda:{args.gpu}',
50
+ save_dir='../model',
51
+ model_name='efficientnet',
52
+ batch_size=args.batch_size,
53
+ num_workers=args.num_workers
54
+ )
55
 
56
  if __name__ == '__main__':
57
  main()
Image/GoogLeNet/code/train.py CHANGED
@@ -1,29 +1,57 @@
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4
-
5
  from utils.dataset_utils import get_cifar10_dataloaders
6
- from utils.train_utils import train_model
 
7
  from model import GoogLeNet
8
 
9
  def main():
10
- # 获取数据加载器
11
- trainloader, testloader = get_cifar10_dataloaders(batch_size=128)
12
 
13
  # 创建模型
14
  model = GoogLeNet()
15
 
16
- # 训练模型
17
- train_model(
18
- model=model,
19
- trainloader=trainloader,
20
- testloader=testloader,
21
- epochs=200,
22
- lr=0.1,
23
- device='cuda',
24
- save_dir='../model',
25
- model_name='googlenet'
26
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  if __name__ == '__main__':
29
  main()
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
  from model import GoogLeNet
8
 
9
  def main():
10
+ # 解析命令行参数
11
+ args = parse_args()
12
 
13
  # 创建模型
14
  model = GoogLeNet()
15
 
16
+ if args.train_type == '0':
17
+ # 获取数据加载器
18
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
19
+ # 训练模型
20
+ train_model(
21
+ model=model,
22
+ trainloader=trainloader,
23
+ testloader=testloader,
24
+ epochs=args.epochs,
25
+ lr=args.lr,
26
+ device=f'cuda:{args.gpu}',
27
+ save_dir='../model',
28
+ model_name='googlenet',
29
+ save_type='0'
30
+ )
31
+ elif args.train_type == '1':
32
+ train_model_data_augmentation(
33
+ model,
34
+ epochs=args.epochs,
35
+ lr=args.lr,
36
+ device=f'cuda:{args.gpu}',
37
+ save_dir='../model',
38
+ model_name='googlenet',
39
+ batch_size=args.batch_size,
40
+ num_workers=args.num_workers
41
+ )
42
+ elif args.train_type == '2':
43
+ train_model_backdoor(
44
+ model,
45
+ poison_ratio=args.poison_ratio,
46
+ target_label=args.target_label,
47
+ epochs=args.epochs,
48
+ lr=args.lr,
49
+ device=f'cuda:{args.gpu}',
50
+ save_dir='../model',
51
+ model_name='googlenet',
52
+ batch_size=args.batch_size,
53
+ num_workers=args.num_workers
54
+ )
55
 
56
  if __name__ == '__main__':
57
  main()
Image/LeNet5/code/train.py CHANGED
@@ -1,29 +1,57 @@
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4
-
5
  from utils.dataset_utils import get_cifar10_dataloaders
6
- from utils.train_utils import train_model
 
7
  from model import LeNet5
8
 
9
  def main():
10
- # 获取数据加载器
11
- trainloader, testloader = get_cifar10_dataloaders(batch_size=128)
12
 
13
  # 创建模型
14
  model = LeNet5()
15
 
16
- # 训练模型
17
- train_model(
18
- model=model,
19
- trainloader=trainloader,
20
- testloader=testloader,
21
- epochs=200,
22
- lr=0.1,
23
- device='cuda',
24
- save_dir='../model',
25
- model_name='lenet5'
26
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  if __name__ == '__main__':
29
  main()
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
  from model import LeNet5
8
 
9
  def main():
10
+ # 解析命令行参数
11
+ args = parse_args()
12
 
13
  # 创建模型
14
  model = LeNet5()
15
 
16
+ if args.train_type == '0':
17
+ # 获取数据加载器
18
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
19
+ # 训练模型
20
+ train_model(
21
+ model=model,
22
+ trainloader=trainloader,
23
+ testloader=testloader,
24
+ epochs=args.epochs,
25
+ lr=args.lr,
26
+ device=f'cuda:{args.gpu}',
27
+ save_dir='../model',
28
+ model_name='lenet5',
29
+ save_type='0'
30
+ )
31
+ elif args.train_type == '1':
32
+ train_model_data_augmentation(
33
+ model,
34
+ epochs=args.epochs,
35
+ lr=args.lr,
36
+ device=f'cuda:{args.gpu}',
37
+ save_dir='../model',
38
+ model_name='lenet5',
39
+ batch_size=args.batch_size,
40
+ num_workers=args.num_workers
41
+ )
42
+ elif args.train_type == '2':
43
+ train_model_backdoor(
44
+ model,
45
+ poison_ratio=args.poison_ratio,
46
+ target_label=args.target_label,
47
+ epochs=args.epochs,
48
+ lr=args.lr,
49
+ device=f'cuda:{args.gpu}',
50
+ save_dir='../model',
51
+ model_name='lenet5',
52
+ batch_size=args.batch_size,
53
+ num_workers=args.num_workers
54
+ )
55
 
56
  if __name__ == '__main__':
57
  main()
Image/MobileNetv1/code/train.py CHANGED
@@ -1,29 +1,57 @@
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4
-
5
  from utils.dataset_utils import get_cifar10_dataloaders
6
- from utils.train_utils import train_model
7
- from model import MobileNet
 
8
 
9
  def main():
10
- # 获取数据加载器
11
- trainloader, testloader = get_cifar10_dataloaders(batch_size=128)
12
 
13
  # 创建模型
14
- model = MobileNet()
15
 
16
- # 训练模型
17
- train_model(
18
- model=model,
19
- trainloader=trainloader,
20
- testloader=testloader,
21
- epochs=200,
22
- lr=0.1,
23
- device='cuda',
24
- save_dir='../model',
25
- model_name='mobilenetv1'
26
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  if __name__ == '__main__':
29
  main()
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
+ from model import MobileNetv1
8
 
9
  def main():
10
+ # 解析命令行参数
11
+ args = parse_args()
12
 
13
  # 创建模型
14
+ model = MobileNetv1()
15
 
16
+ if args.train_type == '0':
17
+ # 获取数据加载器
18
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
19
+ # 训练模型
20
+ train_model(
21
+ model=model,
22
+ trainloader=trainloader,
23
+ testloader=testloader,
24
+ epochs=args.epochs,
25
+ lr=args.lr,
26
+ device=f'cuda:{args.gpu}',
27
+ save_dir='../model',
28
+ model_name='mobilenetv1',
29
+ save_type='0'
30
+ )
31
+ elif args.train_type == '1':
32
+ train_model_data_augmentation(
33
+ model,
34
+ epochs=args.epochs,
35
+ lr=args.lr,
36
+ device=f'cuda:{args.gpu}',
37
+ save_dir='../model',
38
+ model_name='mobilenetv1',
39
+ batch_size=args.batch_size,
40
+ num_workers=args.num_workers
41
+ )
42
+ elif args.train_type == '2':
43
+ train_model_backdoor(
44
+ model,
45
+ poison_ratio=args.poison_ratio,
46
+ target_label=args.target_label,
47
+ epochs=args.epochs,
48
+ lr=args.lr,
49
+ device=f'cuda:{args.gpu}',
50
+ save_dir='../model',
51
+ model_name='mobilenetv1',
52
+ batch_size=args.batch_size,
53
+ num_workers=args.num_workers
54
+ )
55
 
56
  if __name__ == '__main__':
57
  main()
Image/MobileNetv2/code/train.py CHANGED
@@ -1,29 +1,57 @@
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4
-
5
  from utils.dataset_utils import get_cifar10_dataloaders
6
- from utils.train_utils import train_model
7
- from model import MobileNetV2
 
8
 
9
  def main():
10
- # 获取数据加载器
11
- trainloader, testloader = get_cifar10_dataloaders(batch_size=128)
12
 
13
  # 创建模型
14
- model = MobileNetV2()
15
 
16
- # 训练模型
17
- train_model(
18
- model=model,
19
- trainloader=trainloader,
20
- testloader=testloader,
21
- epochs=200,
22
- lr=0.1,
23
- device='cuda',
24
- save_dir='../model',
25
- model_name='mobilenetv2'
26
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  if __name__ == '__main__':
29
  main()
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
+ from model import MobileNetv2
8
 
9
  def main():
10
+ # 解析命令行参数
11
+ args = parse_args()
12
 
13
  # 创建模型
14
+ model = MobileNetv2()
15
 
16
+ if args.train_type == '0':
17
+ # 获取数据加载器
18
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
19
+ # 训练模型
20
+ train_model(
21
+ model=model,
22
+ trainloader=trainloader,
23
+ testloader=testloader,
24
+ epochs=args.epochs,
25
+ lr=args.lr,
26
+ device=f'cuda:{args.gpu}',
27
+ save_dir='../model',
28
+ model_name='mobilenetv2',
29
+ save_type='0'
30
+ )
31
+ elif args.train_type == '1':
32
+ train_model_data_augmentation(
33
+ model,
34
+ epochs=args.epochs,
35
+ lr=args.lr,
36
+ device=f'cuda:{args.gpu}',
37
+ save_dir='../model',
38
+ model_name='mobilenetv2',
39
+ batch_size=args.batch_size,
40
+ num_workers=args.num_workers
41
+ )
42
+ elif args.train_type == '2':
43
+ train_model_backdoor(
44
+ model,
45
+ poison_ratio=args.poison_ratio,
46
+ target_label=args.target_label,
47
+ epochs=args.epochs,
48
+ lr=args.lr,
49
+ device=f'cuda:{args.gpu}',
50
+ save_dir='../model',
51
+ model_name='mobilenetv2',
52
+ batch_size=args.batch_size,
53
+ num_workers=args.num_workers
54
+ )
55
 
56
  if __name__ == '__main__':
57
  main()
Image/MobileNetv3/code/train.py CHANGED
@@ -1,29 +1,57 @@
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4
-
5
  from utils.dataset_utils import get_cifar10_dataloaders
6
- from utils.train_utils import train_model
7
- from model import MobileNetV3
 
8
 
9
  def main():
10
- # 获取数据加载器
11
- trainloader, testloader = get_cifar10_dataloaders(batch_size=128)
12
 
13
  # 创建模型
14
- model = MobileNetV3(num_classes=10, mode='small') # 使用small版本,适合CIFAR10
15
 
16
- # 训练模型
17
- train_model(
18
- model=model,
19
- trainloader=trainloader,
20
- testloader=testloader,
21
- epochs=200,
22
- lr=0.1,
23
- device='cuda',
24
- save_dir='../model',
25
- model_name='mobilenetv3_small'
26
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  if __name__ == '__main__':
29
  main()
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
+ from model import MobileNetv3
8
 
9
  def main():
10
+ # 解析命令行参数
11
+ args = parse_args()
12
 
13
  # 创建模型
14
+ model = MobileNetv3()
15
 
16
+ if args.train_type == '0':
17
+ # 获取数据加载器
18
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
19
+ # 训练模型
20
+ train_model(
21
+ model=model,
22
+ trainloader=trainloader,
23
+ testloader=testloader,
24
+ epochs=args.epochs,
25
+ lr=args.lr,
26
+ device=f'cuda:{args.gpu}',
27
+ save_dir='../model',
28
+ model_name='mobilenetv3',
29
+ save_type='0'
30
+ )
31
+ elif args.train_type == '1':
32
+ train_model_data_augmentation(
33
+ model,
34
+ epochs=args.epochs,
35
+ lr=args.lr,
36
+ device=f'cuda:{args.gpu}',
37
+ save_dir='../model',
38
+ model_name='mobilenetv3',
39
+ batch_size=args.batch_size,
40
+ num_workers=args.num_workers
41
+ )
42
+ elif args.train_type == '2':
43
+ train_model_backdoor(
44
+ model,
45
+ poison_ratio=args.poison_ratio,
46
+ target_label=args.target_label,
47
+ epochs=args.epochs,
48
+ lr=args.lr,
49
+ device=f'cuda:{args.gpu}',
50
+ save_dir='../model',
51
+ model_name='mobilenetv3',
52
+ batch_size=args.batch_size,
53
+ num_workers=args.num_workers
54
+ )
55
 
56
  if __name__ == '__main__':
57
  main()
Image/ResNet/code/train.py CHANGED
@@ -1,29 +1,57 @@
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4
-
5
  from utils.dataset_utils import get_cifar10_dataloaders
6
- from utils.train_utils import train_model
7
- from model import ResNet18
 
8
 
9
  def main():
10
- # 获取数据加载器
11
- trainloader, testloader = get_cifar10_dataloaders(batch_size=128)
12
 
13
  # 创建模型
14
- model = ResNet18()
15
 
16
- # 训练模型
17
- train_model(
18
- model=model,
19
- trainloader=trainloader,
20
- testloader=testloader,
21
- epochs=200,
22
- lr=0.1,
23
- device='cuda',
24
- save_dir='../model',
25
- model_name='resnet18'
26
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  if __name__ == '__main__':
29
  main()
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
+ from model import ResNet
8
 
9
  def main():
10
+ # 解析命令行参数
11
+ args = parse_args()
12
 
13
  # 创建模型
14
+ model = ResNet()
15
 
16
+ if args.train_type == '0':
17
+ # 获取数据加载器
18
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
19
+ # 训练模型
20
+ train_model(
21
+ model=model,
22
+ trainloader=trainloader,
23
+ testloader=testloader,
24
+ epochs=args.epochs,
25
+ lr=args.lr,
26
+ device=f'cuda:{args.gpu}',
27
+ save_dir='../model',
28
+ model_name='resnet',
29
+ save_type='0'
30
+ )
31
+ elif args.train_type == '1':
32
+ train_model_data_augmentation(
33
+ model,
34
+ epochs=args.epochs,
35
+ lr=args.lr,
36
+ device=f'cuda:{args.gpu}',
37
+ save_dir='../model',
38
+ model_name='resnet',
39
+ batch_size=args.batch_size,
40
+ num_workers=args.num_workers
41
+ )
42
+ elif args.train_type == '2':
43
+ train_model_backdoor(
44
+ model,
45
+ poison_ratio=args.poison_ratio,
46
+ target_label=args.target_label,
47
+ epochs=args.epochs,
48
+ lr=args.lr,
49
+ device=f'cuda:{args.gpu}',
50
+ save_dir='../model',
51
+ model_name='resnet',
52
+ batch_size=args.batch_size,
53
+ num_workers=args.num_workers
54
+ )
55
 
56
  if __name__ == '__main__':
57
  main()
Image/SENet/code/train.py CHANGED
@@ -1,29 +1,57 @@
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4
-
5
  from utils.dataset_utils import get_cifar10_dataloaders
6
- from utils.train_utils import train_model
7
- from model import SENet18
 
8
 
9
  def main():
10
- # 获取数据加载器
11
- trainloader, testloader = get_cifar10_dataloaders(batch_size=128)
12
 
13
  # 创建模型
14
- model = SENet18()
15
 
16
- # 训练模型
17
- train_model(
18
- model=model,
19
- trainloader=trainloader,
20
- testloader=testloader,
21
- epochs=200,
22
- lr=0.1,
23
- device='cuda',
24
- save_dir='../model',
25
- model_name='senet18'
26
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  if __name__ == '__main__':
29
  main()
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
+ from model import SENet
8
 
9
  def main():
10
+ # 解析命令行参数
11
+ args = parse_args()
12
 
13
  # 创建模型
14
+ model = SENet()
15
 
16
+ if args.train_type == '0':
17
+ # 获取数据加载器
18
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
19
+ # 训练模型
20
+ train_model(
21
+ model=model,
22
+ trainloader=trainloader,
23
+ testloader=testloader,
24
+ epochs=args.epochs,
25
+ lr=args.lr,
26
+ device=f'cuda:{args.gpu}',
27
+ save_dir='../model',
28
+ model_name='senet',
29
+ save_type='0'
30
+ )
31
+ elif args.train_type == '1':
32
+ train_model_data_augmentation(
33
+ model,
34
+ epochs=args.epochs,
35
+ lr=args.lr,
36
+ device=f'cuda:{args.gpu}',
37
+ save_dir='../model',
38
+ model_name='senet',
39
+ batch_size=args.batch_size,
40
+ num_workers=args.num_workers
41
+ )
42
+ elif args.train_type == '2':
43
+ train_model_backdoor(
44
+ model,
45
+ poison_ratio=args.poison_ratio,
46
+ target_label=args.target_label,
47
+ epochs=args.epochs,
48
+ lr=args.lr,
49
+ device=f'cuda:{args.gpu}',
50
+ save_dir='../model',
51
+ model_name='senet',
52
+ batch_size=args.batch_size,
53
+ num_workers=args.num_workers
54
+ )
55
 
56
  if __name__ == '__main__':
57
  main()
Image/ShuffleNet/code/train.py CHANGED
@@ -1,29 +1,57 @@
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4
-
5
  from utils.dataset_utils import get_cifar10_dataloaders
6
- from utils.train_utils import train_model
 
7
  from model import ShuffleNet
8
 
9
  def main():
10
- # 获取数据加载器
11
- trainloader, testloader = get_cifar10_dataloaders(batch_size=128)
12
 
13
  # 创建模型
14
  model = ShuffleNet()
15
 
16
- # 训练模型
17
- train_model(
18
- model=model,
19
- trainloader=trainloader,
20
- testloader=testloader,
21
- epochs=200,
22
- lr=0.1,
23
- device='cuda',
24
- save_dir='../model',
25
- model_name='shufflenet'
26
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  if __name__ == '__main__':
29
  main()
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
  from model import ShuffleNet
8
 
9
  def main():
10
+ # 解析命令行参数
11
+ args = parse_args()
12
 
13
  # 创建模型
14
  model = ShuffleNet()
15
 
16
+ if args.train_type == '0':
17
+ # 获取数据加载器
18
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
19
+ # 训练模型
20
+ train_model(
21
+ model=model,
22
+ trainloader=trainloader,
23
+ testloader=testloader,
24
+ epochs=args.epochs,
25
+ lr=args.lr,
26
+ device=f'cuda:{args.gpu}',
27
+ save_dir='../model',
28
+ model_name='shufflenet',
29
+ save_type='0'
30
+ )
31
+ elif args.train_type == '1':
32
+ train_model_data_augmentation(
33
+ model,
34
+ epochs=args.epochs,
35
+ lr=args.lr,
36
+ device=f'cuda:{args.gpu}',
37
+ save_dir='../model',
38
+ model_name='shufflenet',
39
+ batch_size=args.batch_size,
40
+ num_workers=args.num_workers
41
+ )
42
+ elif args.train_type == '2':
43
+ train_model_backdoor(
44
+ model,
45
+ poison_ratio=args.poison_ratio,
46
+ target_label=args.target_label,
47
+ epochs=args.epochs,
48
+ lr=args.lr,
49
+ device=f'cuda:{args.gpu}',
50
+ save_dir='../model',
51
+ model_name='shufflenet',
52
+ batch_size=args.batch_size,
53
+ num_workers=args.num_workers
54
+ )
55
 
56
  if __name__ == '__main__':
57
  main()
Image/ShuffleNetv2/code/train.py CHANGED
@@ -1,29 +1,57 @@
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4
-
5
  from utils.dataset_utils import get_cifar10_dataloaders
6
- from utils.train_utils import train_model
7
- from model import ShuffleNetV2
 
8
 
9
  def main():
10
- # 获取数据加载器
11
- trainloader, testloader = get_cifar10_dataloaders(batch_size=128)
12
 
13
  # 创建模型
14
- model = ShuffleNetV2(1) # width_mult=1.0
15
 
16
- # 训练模型
17
- train_model(
18
- model=model,
19
- trainloader=trainloader,
20
- testloader=testloader,
21
- epochs=200,
22
- lr=0.1,
23
- device='cuda',
24
- save_dir='../model',
25
- model_name='shufflenetv2'
26
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  if __name__ == '__main__':
29
  main()
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
+ from model import ShuffleNetv2
8
 
9
  def main():
10
+ # 解析命令行参数
11
+ args = parse_args()
12
 
13
  # 创建模型
14
+ model = ShuffleNetv2()
15
 
16
+ if args.train_type == '0':
17
+ # 获取数据加载器
18
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
19
+ # 训练模型
20
+ train_model(
21
+ model=model,
22
+ trainloader=trainloader,
23
+ testloader=testloader,
24
+ epochs=args.epochs,
25
+ lr=args.lr,
26
+ device=f'cuda:{args.gpu}',
27
+ save_dir='../model',
28
+ model_name='shufflenetv2',
29
+ save_type='0'
30
+ )
31
+ elif args.train_type == '1':
32
+ train_model_data_augmentation(
33
+ model,
34
+ epochs=args.epochs,
35
+ lr=args.lr,
36
+ device=f'cuda:{args.gpu}',
37
+ save_dir='../model',
38
+ model_name='shufflenetv2',
39
+ batch_size=args.batch_size,
40
+ num_workers=args.num_workers
41
+ )
42
+ elif args.train_type == '2':
43
+ train_model_backdoor(
44
+ model,
45
+ poison_ratio=args.poison_ratio,
46
+ target_label=args.target_label,
47
+ epochs=args.epochs,
48
+ lr=args.lr,
49
+ device=f'cuda:{args.gpu}',
50
+ save_dir='../model',
51
+ model_name='shufflenetv2',
52
+ batch_size=args.batch_size,
53
+ num_workers=args.num_workers
54
+ )
55
 
56
  if __name__ == '__main__':
57
  main()
Image/SwinTransformer/code/train.py CHANGED
@@ -1,43 +1,57 @@
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4
-
5
  from utils.dataset_utils import get_cifar10_dataloaders
6
- from utils.train_utils import train_model
 
7
  from model import SwinTransformer
8
 
9
  def main():
10
- # 获取数据加载器
11
- trainloader, testloader = get_cifar10_dataloaders(batch_size=128)
12
 
13
  # 创建模型
14
- model = SwinTransformer(
15
- img_size=32,
16
- patch_size=4,
17
- in_chans=3,
18
- num_classes=10,
19
- embed_dim=96,
20
- depths=[2, 2, 6, 2],
21
- num_heads=[3, 6, 12, 24],
22
- window_size=7,
23
- mlp_ratio=4.,
24
- qkv_bias=True,
25
- drop_rate=0.0,
26
- attn_drop_rate=0.0,
27
- drop_path_rate=0.1
28
- )
29
 
30
- # 训练模型
31
- train_model(
32
- model=model,
33
- trainloader=trainloader,
34
- testloader=testloader,
35
- epochs=200,
36
- lr=0.001, # Transformer类模型通常使用较小的学习率
37
- device='cuda',
38
- save_dir='../model',
39
- model_name='swin_transformer'
40
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
  if __name__ == '__main__':
43
  main()
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
  from model import SwinTransformer
8
 
9
  def main():
10
+ # 解析命令行参数
11
+ args = parse_args()
12
 
13
  # 创建模型
14
+ model = SwinTransformer()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ if args.train_type == '0':
17
+ # 获取数据加载器
18
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
19
+ # 训练模型
20
+ train_model(
21
+ model=model,
22
+ trainloader=trainloader,
23
+ testloader=testloader,
24
+ epochs=args.epochs,
25
+ lr=args.lr,
26
+ device=f'cuda:{args.gpu}',
27
+ save_dir='../model',
28
+ model_name='swintransformer',
29
+ save_type='0'
30
+ )
31
+ elif args.train_type == '1':
32
+ train_model_data_augmentation(
33
+ model,
34
+ epochs=args.epochs,
35
+ lr=args.lr,
36
+ device=f'cuda:{args.gpu}',
37
+ save_dir='../model',
38
+ model_name='swintransformer',
39
+ batch_size=args.batch_size,
40
+ num_workers=args.num_workers
41
+ )
42
+ elif args.train_type == '2':
43
+ train_model_backdoor(
44
+ model,
45
+ poison_ratio=args.poison_ratio,
46
+ target_label=args.target_label,
47
+ epochs=args.epochs,
48
+ lr=args.lr,
49
+ device=f'cuda:{args.gpu}',
50
+ save_dir='../model',
51
+ model_name='swintransformer',
52
+ batch_size=args.batch_size,
53
+ num_workers=args.num_workers
54
+ )
55
 
56
  if __name__ == '__main__':
57
  main()
Image/VGG/code/train.py CHANGED
@@ -1,32 +1,57 @@
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4
-
5
  from utils.dataset_utils import get_cifar10_dataloaders
6
- from utils.train_utils import train_model
 
7
  from model import VGG
8
 
9
  def main():
10
- # 获取数据加载器
11
- trainloader, testloader = get_cifar10_dataloaders(batch_size=128)
12
 
13
  # 创建模型
14
- cfg = {
15
- 'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M']
16
- }
17
- model = VGG('VGG16')
18
 
19
- # 训练模型
20
- train_model(
21
- model=model,
22
- trainloader=trainloader,
23
- testloader=testloader,
24
- epochs=200,
25
- lr=0.1,
26
- device='cuda',
27
- save_dir='../model',
28
- model_name='vgg16'
29
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  if __name__ == '__main__':
32
  main()
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
  from model import VGG
8
 
9
  def main():
10
+ # 解析命令行参数
11
+ args = parse_args()
12
 
13
  # 创建模型
14
+ model = VGG()
 
 
 
15
 
16
+ if args.train_type == '0':
17
+ # 获取数据加载器
18
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
19
+ # 训练模型
20
+ train_model(
21
+ model=model,
22
+ trainloader=trainloader,
23
+ testloader=testloader,
24
+ epochs=args.epochs,
25
+ lr=args.lr,
26
+ device=f'cuda:{args.gpu}',
27
+ save_dir='../model',
28
+ model_name='vgg',
29
+ save_type='0'
30
+ )
31
+ elif args.train_type == '1':
32
+ train_model_data_augmentation(
33
+ model,
34
+ epochs=args.epochs,
35
+ lr=args.lr,
36
+ device=f'cuda:{args.gpu}',
37
+ save_dir='../model',
38
+ model_name='vgg',
39
+ batch_size=args.batch_size,
40
+ num_workers=args.num_workers
41
+ )
42
+ elif args.train_type == '2':
43
+ train_model_backdoor(
44
+ model,
45
+ poison_ratio=args.poison_ratio,
46
+ target_label=args.target_label,
47
+ epochs=args.epochs,
48
+ lr=args.lr,
49
+ device=f'cuda:{args.gpu}',
50
+ save_dir='../model',
51
+ model_name='vgg',
52
+ batch_size=args.batch_size,
53
+ num_workers=args.num_workers
54
+ )
55
 
56
  if __name__ == '__main__':
57
  main()
Image/ViT/code/train.py CHANGED
@@ -1,41 +1,57 @@
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4
-
5
  from utils.dataset_utils import get_cifar10_dataloaders
6
- from utils.train_utils import train_model
 
7
  from model import ViT
8
 
9
  def main():
10
- # 获取数据加载器
11
- trainloader, testloader = get_cifar10_dataloaders(batch_size=128)
12
 
13
  # 创建模型
14
- model = ViT(
15
- img_size=32,
16
- patch_size=4,
17
- in_chans=3,
18
- n_classes=10,
19
- embed_dim=96,
20
- depth=12,
21
- n_heads=8,
22
- mlp_ratio=4.,
23
- qkv_bias=True,
24
- p=0.1,
25
- attn_p=0.1,
26
- )
27
 
28
- # 训练模型
29
- train_model(
30
- model=model,
31
- trainloader=trainloader,
32
- testloader=testloader,
33
- epochs=200,
34
- lr=0.001, # Vision Transformer通常使用较小的学习率
35
- device='cuda',
36
- save_dir='../model',
37
- model_name='vit'
38
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  if __name__ == '__main__':
41
  main()
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
  from model import ViT
8
 
9
  def main():
10
+ # 解析命令行参数
11
+ args = parse_args()
12
 
13
  # 创建模型
14
+ model = ViT()
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ if args.train_type == '0':
17
+ # 获取数据加载器
18
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
19
+ # 训练模型
20
+ train_model(
21
+ model=model,
22
+ trainloader=trainloader,
23
+ testloader=testloader,
24
+ epochs=args.epochs,
25
+ lr=args.lr,
26
+ device=f'cuda:{args.gpu}',
27
+ save_dir='../model',
28
+ model_name='vit',
29
+ save_type='0'
30
+ )
31
+ elif args.train_type == '1':
32
+ train_model_data_augmentation(
33
+ model,
34
+ epochs=args.epochs,
35
+ lr=args.lr,
36
+ device=f'cuda:{args.gpu}',
37
+ save_dir='../model',
38
+ model_name='vit',
39
+ batch_size=args.batch_size,
40
+ num_workers=args.num_workers
41
+ )
42
+ elif args.train_type == '2':
43
+ train_model_backdoor(
44
+ model,
45
+ poison_ratio=args.poison_ratio,
46
+ target_label=args.target_label,
47
+ epochs=args.epochs,
48
+ lr=args.lr,
49
+ device=f'cuda:{args.gpu}',
50
+ save_dir='../model',
51
+ model_name='vit',
52
+ batch_size=args.batch_size,
53
+ num_workers=args.num_workers
54
+ )
55
 
56
  if __name__ == '__main__':
57
  main()
Image/ZFNet/code/train.py CHANGED
@@ -1,29 +1,57 @@
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
4
-
5
  from utils.dataset_utils import get_cifar10_dataloaders
6
- from utils.train_utils import train_model
 
7
  from model import ZFNet
8
 
9
  def main():
10
- # 获取数据加载器
11
- trainloader, testloader = get_cifar10_dataloaders(batch_size=128)
12
 
13
  # 创建模型
14
  model = ZFNet()
15
 
16
- # 训练模型
17
- train_model(
18
- model=model,
19
- trainloader=trainloader,
20
- testloader=testloader,
21
- epochs=200,
22
- lr=0.1,
23
- device='cuda',
24
- save_dir='../model',
25
- model_name='zfnet'
26
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  if __name__ == '__main__':
29
  main()
 
1
  import sys
2
  import os
3
  sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 
4
  from utils.dataset_utils import get_cifar10_dataloaders
5
+ from utils.train_utils import train_model, train_model_data_augmentation, train_model_backdoor
6
+ from utils.parse_args import parse_args
7
  from model import ZFNet
8
 
9
  def main():
10
+ # 解析命令行参数
11
+ args = parse_args()
12
 
13
  # 创建模型
14
  model = ZFNet()
15
 
16
+ if args.train_type == '0':
17
+ # 获取数据加载器
18
+ trainloader, testloader = get_cifar10_dataloaders(batch_size=args.batch_size)
19
+ # 训练模型
20
+ train_model(
21
+ model=model,
22
+ trainloader=trainloader,
23
+ testloader=testloader,
24
+ epochs=args.epochs,
25
+ lr=args.lr,
26
+ device=f'cuda:{args.gpu}',
27
+ save_dir='../model',
28
+ model_name='zfnet',
29
+ save_type='0'
30
+ )
31
+ elif args.train_type == '1':
32
+ train_model_data_augmentation(
33
+ model,
34
+ epochs=args.epochs,
35
+ lr=args.lr,
36
+ device=f'cuda:{args.gpu}',
37
+ save_dir='../model',
38
+ model_name='zfnet',
39
+ batch_size=args.batch_size,
40
+ num_workers=args.num_workers
41
+ )
42
+ elif args.train_type == '2':
43
+ train_model_backdoor(
44
+ model,
45
+ poison_ratio=args.poison_ratio,
46
+ target_label=args.target_label,
47
+ epochs=args.epochs,
48
+ lr=args.lr,
49
+ device=f'cuda:{args.gpu}',
50
+ save_dir='../model',
51
+ model_name='zfnet',
52
+ batch_size=args.batch_size,
53
+ num_workers=args.num_workers
54
+ )
55
 
56
  if __name__ == '__main__':
57
  main()
Image/utils/parse_args.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ def parse_args():
4
+ """解析命令行参数
5
+
6
+ Returns:
7
+ args: 解析后的参数
8
+ """
9
+ parser = argparse.ArgumentParser(description='训练模型')
10
+ parser.add_argument('--gpu', type=int, default=0, help='GPU设备编号 (0,1,2,3)')
11
+ parser.add_argument('--batch-size', type=int, default=128, help='批次大小')
12
+ parser.add_argument('--epochs', type=int, default=200, help='训练轮数')
13
+ parser.add_argument('--lr', type=float, default=0.1, help='学习率')
14
+ parser.add_argument('--num-workers', type=int, default=2, help='数据加载的工作进程数')
15
+ parser.add_argument('--poison-ratio', type=float, default=0.1, help='恶意样本比例')
16
+ parser.add_argument('--target-label', type=int, default=0, help='目标类别')
17
+ parser.add_argument('--train-type',type=str,choices=['0','1','2'],default='0',help='训练类型:0 for normal train, 1 for data aug train,2 for back door train')
18
+ return parser.parse_args()
Image/utils/train_utils.py CHANGED
@@ -135,7 +135,7 @@ def collect_embeddings(model, dataloader, device):
135
  return np.array([]), indices
136
 
137
  def train_model(model, trainloader, testloader, epochs=200, lr=0.1, device='cuda:0',
138
- save_dir='./checkpoints', model_name='model'):
139
  """通用的模型训练函数
140
  Args:
141
  model: 要训练的模型
@@ -161,16 +161,30 @@ def train_model(model, trainloader, testloader, epochs=200, lr=0.1, device='cuda
161
  print(f"GPU {gpu_id} 不可用,将使用GPU 0")
162
  device = 'cuda:0'
163
 
164
- # 设置保存目录
165
  if not os.path.exists(save_dir):
166
  os.makedirs(save_dir)
167
 
168
- # 设置日志
169
- log_file = os.path.join(os.path.dirname(save_dir), 'code', 'train.log')
170
- if not os.path.exists(os.path.dirname(log_file)):
171
- os.makedirs(os.path.dirname(log_file))
 
 
 
 
 
 
 
 
 
172
  logger = setup_logger(log_file)
173
 
 
 
 
 
 
174
  # 损失函数和优化器
175
  criterion = nn.CrossEntropyLoss()
176
  optimizer = optim.SGD(model.parameters(), lr=lr, momentum=0.9, weight_decay=5e-4)
@@ -281,3 +295,163 @@ def train_model(model, trainloader, testloader, epochs=200, lr=0.1, device='cuda
281
  total_time = time.time() - start_time
282
  logger.info(f'训练完成! 总用时: {total_time/3600:.2f}小时')
283
  logger.info(f'最佳测试精度: {best_acc:.2f}%')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  return np.array([]), indices
136
 
137
  def train_model(model, trainloader, testloader, epochs=200, lr=0.1, device='cuda:0',
138
+ save_dir='./checkpoints', model_name='model',save_type='0'):
139
  """通用的模型训练函数
140
  Args:
141
  model: 要训练的模型
 
161
  print(f"GPU {gpu_id} 不可用,将使用GPU 0")
162
  device = 'cuda:0'
163
 
164
+ # 设置保存目录 0 for normal train, 1 for data aug train,2 for back door train
165
  if not os.path.exists(save_dir):
166
  os.makedirs(save_dir)
167
 
168
+ # 设置日志 0 for normal train, 1 for data aug train,2 for back door train
169
+ if save_type == '0':
170
+ log_file = os.path.join(os.path.dirname(save_dir), 'code', 'train.log')
171
+ if not os.path.exists(os.path.dirname(log_file)):
172
+ os.makedirs(os.path.dirname(log_file))
173
+ elif save_type == '1':
174
+ log_file = os.path.join(os.path.dirname(save_dir), 'code', 'data_aug_train.log')
175
+ if not os.path.exists(os.path.dirname(log_file)):
176
+ os.makedirs(os.path.dirname(log_file))
177
+ elif save_type == '2':
178
+ log_file = os.path.join(os.path.dirname(save_dir), 'code', 'backdoor_train.log')
179
+ if not os.path.exists(os.path.dirname(log_file)):
180
+ os.makedirs(os.path.dirname(log_file))
181
  logger = setup_logger(log_file)
182
 
183
+ # 设置epoch保存目录 0 for normal train, 1 for data aug train,2 for back door train
184
+ save_dir = os.path.join(save_dir, save_type)
185
+ if not os.path.exists(save_dir):
186
+ os.makedirs(save_dir)
187
+
188
  # 损失函数和优化器
189
  criterion = nn.CrossEntropyLoss()
190
  optimizer = optim.SGD(model.parameters(), lr=lr, momentum=0.9, weight_decay=5e-4)
 
295
  total_time = time.time() - start_time
296
  logger.info(f'训练完成! 总用时: {total_time/3600:.2f}小时')
297
  logger.info(f'最佳测试精度: {best_acc:.2f}%')
298
+
299
+ def train_model_data_augmentation(model, epochs=200, lr=0.1, device='cuda:0',
300
+ save_dir='./checkpoints', model_name='model_augmented',
301
+ batch_size=128, num_workers=2):
302
+ """使用数据增强训练模型
303
+
304
+ 数据增强方案说明:
305
+ 1. RandomCrop: 随机裁剪,先填充4像素,再裁剪回原始大小,增加位置多样性
306
+ 2. RandomHorizontalFlip: 随机水平翻转,增加方向多样性
307
+ 3. RandomRotation: 随机旋转15度,增加角度多样性
308
+ 4. ColorJitter: 颜色抖动,调整亮度、对比度、饱和度和色调
309
+ 5. RandomErasing: 随机擦除部分区域,模拟遮挡情况
310
+ 6. RandomPerspective: 随机透视变换,增加视角多样性
311
+
312
+ Args:
313
+ model: 要训练的模型
314
+ epochs: 训练轮数
315
+ lr: 学习率
316
+ device: 训练设备
317
+ save_dir: 模型保存目录
318
+ model_name: 模型名称
319
+ batch_size: 批次大小
320
+ num_workers: 数据加载的工作进程数
321
+ """
322
+ import torchvision.transforms as transforms
323
+ from .dataset_utils import get_cifar10_dataloaders
324
+
325
+ # 定义增强的数据预处理
326
+ transform_train = transforms.Compose([
327
+ transforms.RandomCrop(32, padding=4),
328
+ transforms.RandomHorizontalFlip(),
329
+ transforms.RandomRotation(15),
330
+ transforms.ColorJitter(
331
+ brightness=0.2, # 亮度变化范围:[0.8, 1.2]
332
+ contrast=0.2, # 对比度变化范围:[0.8, 1.2]
333
+ saturation=0.2, # 饱和度变化范围:[0.8, 1.2]
334
+ hue=0.1 # 色调变化范围:[-0.1, 0.1]
335
+ ),
336
+ transforms.RandomPerspective(distortion_scale=0.2, p=0.5), # 50%概率进行透视变换
337
+ transforms.ToTensor(),
338
+ transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
339
+ transforms.RandomErasing(p=0.5, scale=(0.02, 0.33), ratio=(0.3, 3.3)) # 50%概率随机擦除
340
+ ])
341
+
342
+ # 获取数据加载器
343
+ trainloader, testloader = get_cifar10_dataloaders(batch_size, num_workers)
344
+
345
+ # 使用增强的训练数据
346
+ trainset = trainloader.dataset
347
+ trainset.transform = transform_train
348
+ trainloader = torch.utils.data.DataLoader(
349
+ trainset, batch_size=batch_size, shuffle=True, num_workers=num_workers)
350
+
351
+ # 调用通用训练函数
352
+ train_model(model, trainloader, testloader, epochs, lr, device, save_dir, model_name,save_type='1')
353
+
354
+ def train_model_backdoor(model, poison_ratio=0.1, target_label=0, epochs=200, lr=0.1,
355
+ device='cuda:0', save_dir='./checkpoints', model_name='model_backdoor',
356
+ batch_size=128, num_workers=2):
357
+ """使用后门攻击训练模型
358
+
359
+ 后门攻击方案说明:
360
+ 1. 标签翻转攻击:将选定比例的样本标签修改为目标标签
361
+ 2. 触发器模式:在选定样本的右下角添加一个4x4的白色方块作为触发器
362
+ 3. 验证策略:
363
+ - 在干净数据上验证模型性能(确保正常样本分类准确率)
364
+ - 在带触发器的数据上验证攻击成功率
365
+
366
+ Args:
367
+ model: 要训练的模型
368
+ poison_ratio: 投毒比例
369
+ target_label: 目标标签
370
+ epochs: 训练轮数
371
+ lr: 学习率
372
+ device: 训练设备
373
+ save_dir: 模型保存目录
374
+ model_name: 模型名称
375
+ batch_size: 批次大小
376
+ num_workers: 数据加载的工作进程数
377
+ """
378
+ from .dataset_utils import get_cifar10_dataloaders
379
+ import numpy as np
380
+ import torch.nn.functional as F
381
+
382
+ # 获取原始数据加载器
383
+ trainloader, testloader = get_cifar10_dataloaders(batch_size, num_workers)
384
+
385
+ # 修改部分训练数据的标签和添加触发器
386
+ trainset = trainloader.dataset
387
+ num_poison = int(len(trainset) * poison_ratio)
388
+ poison_indices = np.random.choice(len(trainset), num_poison, replace=False)
389
+
390
+ # 保存原始标签和数据用于验证
391
+ original_targets = trainset.targets.copy()
392
+ original_data = trainset.data.copy()
393
+
394
+ # 修改选中数据的标签和添加触发器
395
+ trigger_pattern = np.ones((4, 4, 3), dtype=np.uint8) * 255 # 4x4白色方块作为触发器
396
+ for idx in poison_indices:
397
+ # 修改标签
398
+ trainset.targets[idx] = target_label
399
+ # 添加触发器到右下角
400
+ trainset.data[idx, -4:, -4:] = trigger_pattern
401
+
402
+ # 创建新的数据加载器
403
+ poisoned_trainloader = torch.utils.data.DataLoader(
404
+ trainset, batch_size=batch_size, shuffle=True, num_workers=num_workers)
405
+
406
+ # 训练模型
407
+ train_model(model, poisoned_trainloader, testloader, epochs, lr, device, save_dir, model_name,save_type='2')
408
+
409
+ # 恢复原始数据用于验证
410
+ trainset.targets = original_targets
411
+ trainset.data = original_data
412
+
413
+ # 创建验证数据加载器(干净数据)
414
+ validation_loader = torch.utils.data.DataLoader(
415
+ trainset, batch_size=batch_size, shuffle=False, num_workers=num_workers)
416
+
417
+ # 在干净验证集上评估模型
418
+ model.eval()
419
+ correct = 0
420
+ total = 0
421
+ with torch.no_grad():
422
+ for inputs, targets in validation_loader:
423
+ inputs, targets = inputs.to(device), targets.to(device)
424
+ outputs = model(inputs)
425
+ _, predicted = outputs.max(1)
426
+ total += targets.size(0)
427
+ correct += predicted.eq(targets).sum().item()
428
+
429
+ clean_accuracy = 100. * correct / total
430
+ print(f'\nAccuracy on clean validation set: {clean_accuracy:.2f}%')
431
+
432
+ # 创建带触发器的验证数据集
433
+ trigger_validation = trainset.data.copy()
434
+ trigger_validation_targets = np.array([target_label] * len(trainset))
435
+ # 添加触发器
436
+ trigger_validation[:, -4:, -4:] = trigger_pattern
437
+
438
+ # 转换为张量并标准化
439
+ trigger_validation = torch.tensor(trigger_validation).float().permute(0, 3, 1, 2) / 255.0
440
+ trigger_validation = F.normalize(trigger_validation,
441
+ mean=(0.4914, 0.4822, 0.4465),
442
+ std=(0.2023, 0.1994, 0.2010))
443
+
444
+ # 在带触发器的验证集上评估模型
445
+ correct = 0
446
+ total = 0
447
+ batch_size = 100
448
+ for i in range(0, len(trigger_validation), batch_size):
449
+ inputs = trigger_validation[i:i+batch_size].to(device)
450
+ targets = torch.tensor(trigger_validation_targets[i:i+batch_size]).to(device)
451
+ outputs = model(inputs)
452
+ _, predicted = outputs.max(1)
453
+ total += targets.size(0)
454
+ correct += predicted.eq(targets).sum().item()
455
+
456
+ attack_success_rate = 100. * correct / total
457
+ print(f'Attack success rate on triggered samples: {attack_success_rate:.2f}%')