-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrain_surrogate.py
236 lines (198 loc) · 7.1 KB
/
train_surrogate.py
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
from __future__ import print_function
import argparse
import os
import random
import yaml
import torch.optim as optim
import torch.utils.data
from model.classifier.pointnet_cls import feature_transform_regularizer
import torch.nn.functional as F
from tqdm import tqdm
import sys
import importlib
import numpy as np
import torch.nn as nn
from dataset.ModelNetDataLoader10 import ModelNetDataLoader10
from dataset.ModelNetDataLoader import ModelNetDataLoader
from dataset.ShapeNetDataLoader import PartNormalDataset
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = BASE_DIR
sys.path.append(os.path.join(ROOT_DIR, 'model/classifier'))
def load_model(args):
MODEL = importlib.import_module(args.target_model)
classifier = MODEL.get_model(
args.num_class,
normal_channel=args.normal
)
classifier = classifier.to(args.device)
classifier = nn.DataParallel(classifier)
return classifier
def load_data(opt, split='test'):
"""Load the dataset from the given path.
"""
print('Start Loading Dataset...')
if opt.dataset == 'ModelNet40':
DATASET = ModelNetDataLoader(
root=opt.data_path,
npoints=opt.input_point_nums,
split=split,
normal_channel=False
)
elif opt.dataset == 'ShapeNetPart':
DATASET = PartNormalDataset(
root=opt.data_path,
npoints=opt.input_point_nums,
split=split,
normal_channel=False
)
elif opt.dataset == 'ModelNet10':
DATASET = ModelNetDataLoader10(
root=opt.data_path,
npoints=opt.input_point_nums,
split=split,
normal_channel=False
)
else:
raise NotImplementedError
print('Finish Loading Dataset...')
return DATASET
def data_preprocess(data):
"""Preprocess the given data and label.
"""
points, target = data
points = points # [B, N, C]
target = target[:, 0] # [B]
points = points.cuda()
target = target.cuda()
return points, target
parser = argparse.ArgumentParser()
parser.add_argument(
'--workers', type=int, help='number of data loading workers', default=4)
parser.add_argument(
'--nepoch', type=int, default=250, help='number of epochs to train')
parser.add_argument(
'--dataset', type=str, default='ModelNet40', help="dataset path")
parser.add_argument(
'--split', type=int, default=1000, help='split the original dataset to get a small dataset possessed by the attacker')
parser.add_argument(
'--feature_transform', action='store_true', help="use feature transform")
#! change
parser.add_argument(
'--target_model', type=str, default='pointnet_cls', help='')
opt = parser.parse_args()
f = open('config.yaml')
config = yaml.safe_load(f)
opt.batch_size = config['batch_size']
opt.device = config['device']
opt.workers = config['workers']
opt.input_point_nums = config['input_point_nums']
if opt.dataset == 'ModelNet40':
opt.num_class = 40
opt.data_path = config['ModelNet_path']
elif opt.dataset == 'ShapeNetPart':
opt.num_class = 16
opt.data_path = config['ShapeNetPart_path']
elif opt.dataset == 'ModelNet10':
opt.num_class = 10
opt.data_path = config['ModelNet_path']
opt.normal =False
opt.manualSeed = 2023 # fix seed
print("Random Seed: ", opt.manualSeed)
random.seed(opt.manualSeed)
torch.manual_seed(opt.manualSeed)
np.random.seed(opt.manualSeed)
opt.model_path = f'./model_surrogate/{opt.dataset}'
print(opt)
if not os.path.exists(opt.model_path):
os.makedirs(opt.model_path)
trainset = load_data(opt, 'train')
testset = load_data(opt, 'test')
testloader = torch.utils.data.DataLoader(
testset,
batch_size=opt.batch_size,
shuffle=True,
num_workers=4)
# Get a subset of the experiment dataset
data = None
labels = None
choices = np.random.choice(len(trainset), opt.split)
for c in choices:
if data is None:
data = trainset[c][0][np.newaxis,:,:]
else:
data = np.concatenate([data, trainset[c][0][np.newaxis,:,:]], axis=0)
if labels is None:
labels = trainset[c][1]
else:
labels = np.concatenate([labels, trainset[c][1]], axis=0)
train_dataset = torch.utils.data.TensorDataset(torch.tensor(data),torch.tensor(labels).unsqueeze(-1))
trainloader = torch.utils.data.DataLoader(
train_dataset,
batch_size=opt.batch_size,
shuffle=True,
num_workers=4)
print('classes: {}'.format(opt.num_class))
print('train size: {}; test size: {}'.format(len(trainloader), len(testloader)))
#? classifier = PointNetCls(k=num_classes, feature_transform=opt.feature_transform)
classifier = load_model(opt)
optimizer = optim.Adam(classifier.parameters(), lr=0.001, betas=(0.9, 0.999))
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.5)
classifier.to(opt.device)
for epoch in tqdm(range(opt.nepoch)):
print("epoch {}".format(epoch))
for i, data in enumerate(trainloader):
points, targets = data_preprocess(data)
points = points.transpose(2, 1)
targets = targets.long()
optimizer.zero_grad()
classifier = classifier.train()
if opt.target_model == 'pointnet_cls':
pred, trans, trans_feat = classifier(points, is_train=True)
loss = F.nll_loss(pred, targets)
loss += feature_transform_regularizer(trans_feat) * 0.001
else:
pred = classifier(points)
loss = F.cross_entropy(pred, targets)
loss.backward()
optimizer.step()
GRAD = 0
for name, params in classifier.named_parameters():
# print(name)
# print(params)
# print(params.grad)
GRAD += torch.mean(abs(params.grad.data))
print(GRAD)
pred_choice = pred.data.max(1)[1]
correct = pred_choice.eq(targets).cpu().sum()
if i == 20:
sys.exit(-1)
scheduler.step()
total_correct = 0
total_testset = 0
for i, data in tqdm(enumerate(testloader)):
points, targets = data_preprocess(data)
points = points.transpose(2, 1)
targets = targets.long()
classifier = classifier.eval()
pred = classifier(points)
pred_choice = pred.data.max(1)[1]
correct = pred_choice.eq(targets).cpu().sum()
total_correct += correct.item()
total_testset += points.size()[0]
print("test accuracy {}".format(total_correct / float(total_testset)))
total_correct = 0
total_testset = 0
for i, data in tqdm(enumerate(testloader)):
points, targets = data_preprocess(data)
points = points.transpose(2, 1)
targets = targets.long()
classifier = classifier.eval()
pred = classifier(points)
pred_choice = pred.data.max(1)[1]
correct = pred_choice.eq(targets).cpu().sum()
total_correct += correct.item()
total_testset += points.size()[0]
print("final accuracy {}".format(total_correct / float(total_testset)))
with open(os.path.join(opt.model_path,'data.txt'), 'a') as f:
f.write(f'{opt.target_model}, {opt.dataset}, {total_correct / float(total_testset)}\n')
torch.save(classifier.state_dict(),os.path.join(opt.model_path, opt.target_model+'.pth'))