-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory_herding_shapenet.py
319 lines (274 loc) · 14.1 KB
/
memory_herding_shapenet.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import argparse
import random
import torch
import torch.optim as optim
import torch.nn.functional as F
from tqdm import tqdm
import open_clip
from utils.mv_utils_zs_ver_2 import Realistic_Projection_Learnable_new as Realistic_Projection
from model.PointNet import PointNetfeat, feature_transform_regularizer, STN3d
from model.curvenet import *
from model.Transformation import Transformation
from utils.datautil_3D_memory_incremental_shapenet import *
from model.Relation import RelationNetwork
import os
import numpy as np
from matplotlib import pyplot as plt
from torch import nn
from utils.Loss import CombinedConstraintLoss
from model.Unet_dropout import UNetPlusPlus
from torchmetrics.functional.image import image_gradients
from configs.shapenet_info import task_ids_total as tid
import json
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def set_random_seed(seed):
random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def read_txt_file(file):
with open(file, 'r') as f:
array = f.readlines()
array = ["A depth map of " + x.strip() for x in array]
array = list(filter(None, array))
return array
def read_txt_file_class_name(file):
with open(file, 'r') as f:
array = f.readlines()
array = [x.strip() for x in array]
array = list(filter(None, array))
return array
# read json file
def read_json_file(file):
with open(file, 'r') as f:
array = json.load(f)
return array
def accuracy(output, target, topk=(1,)):
pred = output.topk(max(topk), 1, True, True)[1].t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
return [float(correct[:k].reshape(-1).float().sum(0, keepdim=True).cpu().numpy()) for k in topk]
# define the main function
def main(opt):
num_rotations = 1
set_random_seed(opt.manualSeed)
# import pointnet model
curvenet = CurveNet()
curvenet = curvenet.to(device)
curvenet.load_state_dict(torch.load('cls/shapenet/curvenet_40.pth', map_location=device))
# Step 1: Load CLIP model
clip_model, _, preprocess = open_clip.create_model_and_transforms('ViT-B-16', pretrained='laion2b_s34b_b88k')
clip_model.to(device)
for param in clip_model.parameters():
param.requires_grad = False
# Step 2: Load Realistic Projection object
proj = Realistic_Projection().to(device)
# Step 3: Load the Transformation model
transform = {str(i): STN3d() for i in range(num_rotations)}
for i in range(num_rotations):
transform[str(i)].to(device)
transform[str(i)].load_state_dict(torch.load('cls/shapenet/transform_40_%d.pth' % i, map_location=device))
# load the Unet model
unet = UNetPlusPlus().to(device)
unet.load_state_dict(torch.load('cls/shapenet/unet_40.pth', map_location=device))
# Step 4: Load the Relation Network
relation = RelationNetwork(1536, 2048, 1024)
relation = relation.to(device)
relation.load_state_dict(torch.load('cls/shapenet/relation_40.pth', map_location=device))
#load the text features
class_name = read_txt_file_class_name("class_name_shapenet.txt")
optimizer = optim.Adam(curvenet.parameters(), lr=0.001, betas=(0.9, 0.999))
# load loss function
cross_entrpy = nn.BCELoss()
constraint_loss = CombinedConstraintLoss(num_rotations=num_rotations)
loss_orthogonal_weight = 0.01
mse_loss = nn.MSELoss()
# constract a memory bank of inpt data consisting of 1 samples per calss
memory_bank = torch.zeros((55, 1024,3)).to(device)
memory_bank_label = torch.zeros((55, 1)).to(device)
# load the data
prototype = np.zeros((55, 512))
sample_num = np.zeros((55))
for t in range(0,6):
path=Path(opt.dataset_path)
print(path)
dataloader = DatasetGen(opt, root=path, fewshot=5)
dataset = dataloader.get(t,'training')
trainDataLoader = dataset[t]['train']
testDataLoader = dataset[t]['test']
if t == 0:
num_category = 25
elif t == 1:
num_category = 30
elif t == 2:
num_category = 35
elif t == 3:
num_category = 40
elif t == 4:
num_category = 45
elif t == 5:
num_category = 50
else:
num_category = 55
print('task:', t)
# train the model
clip_model.eval()
for i in range(num_rotations):
transform[format(i)].eval()
unet.train()
relation.eval()
curvenet.eval()
print("=> Start training the model")
# construct the memory bank
for epoch in range(1):
# define the loss
for i, data in tqdm(enumerate(trainDataLoader, 0)):
points, target = data['pointclouds'].to(device).float(), data['labels'].to(device)
points, target = points.to(device), target.to(device)
optimizer.zero_grad()
points = points.transpose(2, 1)
# Forward samples to the PointNet model
points_embedding = curvenet(points)
# transformation module
trans = torch.zeros((points.shape[0], num_rotations, 3, 3), device=device)
for jj in range(num_rotations):
trans[:, jj, :, :] = transform[format(jj)](points)
# depth map generation
points = points.transpose(2, 1)
depth_map = torch.zeros((points.shape[0] * num_rotations, 3, 224, 224)).to(device)
for jj in range(num_rotations):
depth_map_tmp = proj.get_img(points, trans[:,jj,:,:].view(-1, 9))
depth_map_tmp = torch.nn.functional.interpolate(depth_map_tmp, size=(224, 224), mode='bilinear', align_corners=True)
depth_map[jj * points.shape[0]:(jj + 1) * points.shape[0], :, :, :] = depth_map_tmp
loss_gradient = 0
RGB_map = torch.zeros((points.shape[0] * num_rotations, 3, 224, 224)).to(device)
for jj in range(num_rotations):
# unet model
depth_map_reverse = 1 - depth_map[jj * points.shape[0]:(jj + 1) * points.shape[0]]
mask = (depth_map_reverse != 0).float()
texture_map = unet(mask)
# loss for gradient
RGB_map[jj * points.shape[0]:(jj + 1) * points.shape[0], :, :, :] = depth_map[jj * points.shape[0]:(jj + 1) * points.shape[0]] * texture_map
# Forward samples to the vision CLIP model
img_embedding_tmp = clip_model.encode_image(RGB_map).to(device)
img_embedding = 0
for jj in range(num_rotations):
img_embedding += img_embedding_tmp[jj * points.shape[0]:(jj + 1) * points.shape[0], :]/ num_rotations
# merge img_embedding and points_embedding
img_embedding = img_embedding / img_embedding.norm(dim=-1, keepdim=True)
points_embedding = points_embedding / points_embedding.norm(dim=-1, keepdim=True)
fea_embedding = (img_embedding + points_embedding)/2
# calculate the prototype of each class
for jj in range(num_category):
prototype[jj, :] += (fea_embedding[target == jj, :].sum(dim=0)).detach().cpu().numpy()
sample_num[jj] += ((target == jj).sum()).detach().cpu().numpy()
print("sample_num:", sample_num)
for k in range(num_category):
prototype[k, :] = prototype[k, :] / sample_num[k]
Distance = np.zeros((55))
print('----------------------------------------------------------')
for t in range(0,6):
path=Path(opt.dataset_path)
print(path)
dataloader = DatasetGen(opt, root=path, fewshot=5)
dataset = dataloader.get(t,'training')
trainDataLoader = dataset[t]['train']
testDataLoader = dataset[t]['test']
if t == 0:
num_category = 25
elif t == 1:
num_category = 30
elif t == 2:
num_category = 35
elif t == 3:
num_category = 40
elif t == 4:
num_category = 45
elif t == 5:
num_category = 50
else:
num_category = 55
print('task:', t)
# train the model
clip_model.eval()
for i in range(num_rotations):
transform[format(i)].eval()
unet.train()
relation.eval()
curvenet.eval()
print("=> Start training the model")
# construct the memory bank
for epoch in range(1):
# define the loss
for i, data in tqdm(enumerate(trainDataLoader, 0)):
points, target = data['pointclouds'].to(device).float(), data['labels'].to(device)
points, target = points.to(device), target.to(device)
optimizer.zero_grad()
points = points.transpose(2, 1)
# Forward samples to the PointNet model
points_embedding = curvenet(points)
# transformation module
trans = torch.zeros((points.shape[0], num_rotations, 3, 3), device=device)
for jj in range(num_rotations):
trans[:, jj, :, :] = transform[format(jj)](points)
# depth map generation
points = points.transpose(2, 1)
depth_map = torch.zeros((points.shape[0] * num_rotations, 3, 224, 224)).to(device)
for jj in range(num_rotations):
depth_map_tmp = proj.get_img(points, trans[:,jj,:,:].view(-1, 9))
depth_map_tmp = torch.nn.functional.interpolate(depth_map_tmp, size=(224, 224), mode='bilinear', align_corners=True)
depth_map[jj * points.shape[0]:(jj + 1) * points.shape[0], :, :, :] = depth_map_tmp
loss_gradient = 0
RGB_map = torch.zeros((points.shape[0] * num_rotations, 3, 224, 224)).to(device)
for jj in range(num_rotations):
# unet model
depth_map_reverse = 1 - depth_map[jj * points.shape[0]:(jj + 1) * points.shape[0]]
mask = (depth_map_reverse != 0).float()
texture_map = unet(mask)
# loss for gradient
RGB_map[jj * points.shape[0]:(jj + 1) * points.shape[0], :, :, :] = depth_map[jj * points.shape[0]:(jj + 1) * points.shape[0]] * texture_map
# Forward samples to the vision CLIP model
img_embedding_tmp = clip_model.encode_image(RGB_map).to(device)
img_embedding = 0
for jj in range(num_rotations):
img_embedding += img_embedding_tmp[jj * points.shape[0]:(jj + 1) * points.shape[0], :]/ num_rotations
# merge img_embedding and points_embedding
img_embedding = img_embedding / img_embedding.norm(dim=-1, keepdim=True)
points_embedding = points_embedding / points_embedding.norm(dim=-1, keepdim=True)
fea_embedding = (img_embedding + points_embedding)/2
# select one sample per class
for jj in range(points.shape[0]):
dis = torch.cosine_similarity(fea_embedding[jj, :].unsqueeze(0), torch.from_numpy(prototype[target[jj], :]).to(device).unsqueeze(0))
if dis > Distance[target[jj]]:
memory_bank[target[jj], :, :] = points[jj, :, :]
memory_bank_label[target[jj], :] = target[jj]
Distance[target[jj]] = dis
# save the memory bank as numpy array
np.save('memory/memory_bank_shapenet.npy', memory_bank.cpu().numpy())
np.save('memory/memory_bank_label_shapenet.npy', memory_bank_label.cpu().numpy())
print("memory bank saved")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', type=int, default= 32, help='input batch size')
parser.add_argument('--num_points', type=int, default=2048, help='number of points in each input point cloud')
parser.add_argument('--workers', type=int, help='number of data loading workers', default=4)
parser.add_argument('--nepoch', type=int, default=1, help='number of epochs to train for')
parser.add_argument('--outf', type=str, default='cls', help='output folder to save results')
parser.add_argument('--model', type=str, default='cls/3D_model_249.pth', help='path to load a pre-trained model')
parser.add_argument('--feature_transform', action='store_true', help='use feature transform')
parser.add_argument('--manualSeed', type=int, default = 42, help='random seed')
parser.add_argument('--dataset_path', type=str, default= 'dataset/FSCIL/shapenet/', help="dataset path")
parser.add_argument('--ntasks', type=str, default= '5', help="number of tasks")
parser.add_argument('--nclasses', type=str, default= '25', help="number of classes")
parser.add_argument('--task', type=str, default= '0', help="task number")
parser.add_argument('--num_samples', type=str, default= '0', help="number of samples per class")
parser.add_argument('--process_data', action='store_true', default=False, help='save data offline')
parser.add_argument('--num_point', type=int, default=2048, help='Point Number')
parser.add_argument('--use_uniform_sample', action='store_true', default=False, help='use uniform sampiling')
parser.add_argument('--use_normals', action='store_true', default=False, help='use normals')
parser.add_argument('--num_category', default=25, type=int, choices=[20, 40], help='training on ModelNet10/40')
parser.add_argument('--sem_file', default=None, help='training on ModelNet10/40')
parser.add_argument('--use_memory', default=False, help='use_memory')
parser.add_argument('--herding', default=True, help='herding')
opt = parser.parse_args()
main(opt)
print("Done!")