-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
192 lines (153 loc) · 7.19 KB
/
train.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
import numpy as np
import matplotlib.pyplot as plt
import open3d as o3d
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import torch.nn as nn
import os
import glob
from tqdm import tqdm
import pandas as pd
from sklearn.metrics import recall_score, precision_score, f1_score, accuracy_score
from dataset.PointCloudDataset import PointCloudDataset
from dataset.voxelDataset import VoxelDataset
from classifier import Classifier
from networks.PointNet import PointNet
from networks.voxnet import VoxNet
from networks.res_voxnet import ResVoxNet
import argparse
import os
# 2000 dati allenati con batch 32 e 5e-4
# 4000 dati allenati con batch 64 e 1e-3
parser = argparse.ArgumentParser(description='training')
parser.add_argument('--model_name', type=str, default='pointnet', help='model name (default: pointnet)', choices=['pointnet', 'voxnet', 'res_voxnet'])
<<<<<<< Updated upstream
parser.add_argument('--epochs', type=int, default=100, help='number of epochs to train (default: 10)')
=======
parser.add_argument('--epochs', type=int, default=40, help='number of epochs to train (default: 10)')
>>>>>>> Stashed changes
parser.add_argument('--lr', type=float, default=1e-3, help='learning rate (default: 0.001)')
parser.add_argument('--batch_size', type=int, default=64, help='batch size (default: 32)')
parser.add_argument('--save_dir', type=str, default='checkpoints', help='directory to save checkpoints (default: checkpoints/pointnet)')
parser.add_argument('--ndata', type=int, default=4000, help='number of data points to use (default: 2000)')
parser.add_argument('--npoints', type=int, default=10000, help='number of points in the point cloud (default: 1024)')
parser.add_argument('--train', type=bool, default=True, help='train or test (default: True)')
parser.add_argument('--rotation', type=bool, default=True, help='augment samples using random rotations (default: False)')
args = parser.parse_args()
def main (
model_name='pointnet',
epochs=10,
lr=0.001,
batch_size=32,
save_dir='checkpoints',
ndata=4000,
npoints = 1024,
train=False,
rotation=False
):
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")
save_dir = os.path.join(save_dir, model_name)
##############################
# LOAD MODEL AND DATASET
##############################
print (f"Loading model {model_name}...")
if model_name == 'pointnet':
dataset_train = PointCloudDataset('dataset/ModelNet40',
train=True,
ndata=ndata,
file_extension='.off',
npoints=npoints,
rotation=rotation
)
if train: test_data = int(ndata/20)
else: test_data = -1
dataset_val = PointCloudDataset('dataset/ModelNet40',
train=False,
ndata=test_data,
file_extension='.off',
npoints=npoints,
rotation=False
)
print (f"Train dataset size: {len(dataset_train)}")
print (f"Val dataset size: {len(dataset_val)}")
dataloader_train = DataLoader(dataset_train, batch_size=batch_size, shuffle=True, num_workers=4)
dataloader_val = DataLoader(dataset_val, batch_size=32, shuffle=True)
Net = PointNet(nclasses=40)
parameters = Net.parameters()
optimizer = optim.SGD(parameters, lr=5e-4, weight_decay=1e-5)
elif model_name == 'voxnet':
input_shape = (32, 32, 32)
dataset_train = VoxelDataset('dataset/ModelNet40',
train=True,
)
dataset_val = VoxelDataset('dataset/ModelNet40',
train=False,
)
print (f"Train dataset size: {len(dataset_train)}")
print (f"Val dataset size: {len(dataset_val)}")
dataloader_train = DataLoader(dataset_train, batch_size=batch_size, shuffle=True, num_workers=4)
dataloader_val = DataLoader(dataset_val, batch_size=32, shuffle=True)
# print (f"first element in loader: {next(iter(dataloader_train))}")
# print number of elments in loader
Net = VoxNet(input_shape=input_shape, nclasses=40)
parameters = Net.parameters()
optimizer = optim.Adam(parameters, lr=1e-3, weight_decay=1e-5)
elif model_name == 'res_voxnet':
input_shape = (32, 32, 32)
dataset_train = VoxelDataset('dataset/ModelNet40', train=True,)
dataset_val = VoxelDataset('dataset/ModelNet40', train=False)
print (f"Train dataset size: {len(dataset_train)}")
print (f"Val dataset size: {len(dataset_val)}")
dataloader_train = DataLoader(dataset_train, batch_size=batch_size, shuffle=True, num_workers=4)
dataloader_val = DataLoader(dataset_val, batch_size=32, shuffle=True)
Net = ResVoxNet(input_shape=input_shape, nclasses=40)
parameters = Net.parameters()
optimizer = optim.Adam(parameters, lr=1e-4, weight_decay=1e-5, amsgrad=True)
else:
raise ValueError(f"Model {model_name} not implemented")
# load model if exists
models_saved = glob.glob(os.path.join(save_dir, 'model_*.torch'))
if len(models_saved) > 0:
# get most recent model
epoches_done = max([int(model.split('_')[-1].split('.')[0]) for model in models_saved])
model_path = os.path.join(save_dir, f'model_{epoches_done}.torch')
print(f"Loading model from {model_path}")
Net.load_state_dict(torch.load(model_path))
else:
epoches_done = 0
# move model to device
Net.to(device)
classifier = Classifier(Net, device=device)
loss_fn = nn.CrossEntropyLoss()
if train:
print ("Starting training")
classifier.train(dataloader_train, dataloader_val, epochs=epochs, optimizer=optimizer, loss_fn=loss_fn,
save_dir=save_dir, start_epoch=epoches_done+1)
print ("Training done")
else:
print ("Starting testing")
results = classifier.test(dataloader_val)
print ("Testing done")
print(results)
# save results in csv
results.to_csv(os.path.join(save_dir, 'test_results.csv'), index=False)
# # probability distributions 2d histplot
# probs, labels = classifier.get_prob_distribution(dataloader_val)
# probs = probs.cpu().numpy()
# labels = labels.cpu().numpy()
# # # plot 2d histogram
# fig, ax = plt.subplots()
# import seaborn as sns
# sns.clustermap(probs)
# ax.set_xlabel('Probability')
# ax.set_ylabel('Label')
# ax.set_title('Probability distribution')
# plt.show()
if __name__ == '__main__':
main(
**vars(args)
)