-
Notifications
You must be signed in to change notification settings - Fork 1
/
train_segmentation.py
144 lines (119 loc) · 4.75 KB
/
train_segmentation.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
from __future__ import print_function
import argparse
import os
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.autograd import Variable
# from datasets import PartDataset
from pointnet import PointNetDenseCls
import torch.nn.functional as F
import _pickle as pkl
import pandas as pd
import glob
parser = argparse.ArgumentParser()
parser.add_argument('--batchSize', type=int, default=32, help='input batch size')
parser.add_argument('--workers', type=int, help='number of data loading workers', default=4)
parser.add_argument('--nepoch', type=int, default=25, help='number of epochs to train for')
parser.add_argument('--outf', type=str, default='seg', help='output folder')
parser.add_argument('--model', type=str, default = '', help='model path')
opt = parser.parse_args()
print (opt)
opt.manualSeed = random.randint(1, 10000) # fix seed
print("Random Seed: ", opt.manualSeed)
random.seed(opt.manualSeed)
torch.manual_seed(opt.manualSeed)
data_path = '/home/sai/data/maplite_data_chunks'
### getting list of the data
data_list = glob.glob(data_path+'/*.pkl')
data_list.sort()
data_length = len(data_list)
### Getting train and test data in random order
indices = np.random.permutation(data_length)
train_indices = indices[0:int(2*data_length/(3))]
test_indices = indices[int(data_length/(3)):-1]
def normalize_input(df):
### Getting coordinates and features
x = df.iloc[0]['scan_utm']['x']
y = df.iloc[0]['scan_utm']['y']
z = df.iloc[0]['scan_utm']['z']
### getting coordinate values between 0 and 150
x -= min(x)
y -= min(y)
z -= min(z)
x = 150*x/max(x)
y = 150*y/max(y)
z = 150*z/max(z)
coords = torch.randn(len(x), 4)
coords[:,0] = torch.from_numpy(x.copy())
coords[:,1] = torch.from_numpy(y.copy())
coords[:,2] = torch.from_numpy(z.copy())
coords[:,3] = torch.from_numpy(df.iloc[0]['scan_utm']['intensity'].copy())
del x, y, z
train_output = torch.from_numpy(1*(df.iloc[0]['is_road_truth'] == True))
return coords[0:100,:], train_output[0:100]
# return coords, train_output
num_classes = 1
print('classes', num_classes)
try:
os.makedirs(opt.outf)
except OSError:
pass
blue = lambda x:'\033[94m' + x + '\033[0m'
classifier = PointNetDenseCls(k = num_classes)
if opt.model != '':
classifier.load_state_dict(torch.load(opt.model))
optimizer = optim.SGD(classifier.parameters(), lr=0.01, momentum=0.9)
classifier.cuda()
# num_batch = len(dataset)/opt.batchSize
num_batch = 10
for epoch in range(opt.nepoch):
for i in range(50):
points = np.zeros((2,111168,4))
target = np.zeros((2,111168))
df = pd.read_pickle(data_list[i])
points[0,:,:], target[0,:] = normalize_input(df)
print("points.shape, target.shape = ",points.shape, target.shape)
print(points.shape, target.shape)
print(target[0,:,])
points = Variable(torch.FloatTensor(points))
target = Variable(torch.FloatTensor(target))
points = points.transpose(2,1)
points, target = points.cuda(), target.cuda()
optimizer.zero_grad()
classifier = classifier.train()
pred, _ = classifier(points)
pred = pred.view(-1, num_classes)
# pred = pred.squeeze()
target = target.view(-1,1)[:,0] - 1
target = target.unsqueeze(1)
print(pred.size(), target.size())
loss = F.mse_loss(pred, target)
loss.backward()
optimizer.step()
pred_choice = pred.data.max(1)[1]
correct = pred_choice.eq(target.long().data).cpu().sum()
print('[%d: %d/%d] train loss: %f accuracy: %f' %(epoch, i, num_batch, loss.item(), correct.item()/float(opt.batchSize * 2500)))
# if i % 10 == 0:
# j, data = next(enumerate(testdataloader, 0))
# points, target = data
# points, target = Variable(points), Variable(target)
# points = points.transpose(2,1)
# points, target = points.cuda(), target.cuda()
# classifier = classifier.eval()
# pred, _ = classifier(points)
# pred = pred.view(-1, num_classes)
# target = target.view(-1,1)[:,0] - 1
# loss = F.nll_loss(pred, target)
# pred_choice = pred.data.max(1)[1]
# correct = pred_choice.eq(target.data).cpu().sum()
# print('[%d: %d/%d] %s loss: %f accuracy: %f' %(epoch, i, num_batch, blue('test'), loss.item(), correct.item()/float(opt.batchSize * 2500)))
torch.save(classifier.state_dict(), '%s/seg_model_%d.pth' % (opt.outf, epoch))