-
Notifications
You must be signed in to change notification settings - Fork 2
/
fuse_4cost.py
154 lines (126 loc) · 6.42 KB
/
fuse_4cost.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
# pytorch
import torch, torchvision
import torch.nn.functional as F
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader, ConcatDataset
from torchvision import transforms
# tools
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os, argparse, time, cv2
from PIL import Image
from network import FuseNetwork
from dataloader import MBdatalist
from dataloader import MBloader
from fuse_utils import train, test4, eval
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Cost Fusing')
parser.add_argument('--name', type=str,
help='log name (default: "1")', default="1")
parser.add_argument('--trainpath', default='dataset/TRAIN/',
help='training data set path')
parser.add_argument('--testpath', default='dataset/TEST/',
help='test data set path')
parser.add_argument('--evalpath', default='dataset/EVAL/',
help='evaluate data set path')
parser.add_argument('--batch_size', type=int, default=4,
help='batch size')
parser.add_argument('--learning_rate', type=float, default=1e-4,
help='learning rate')
parser.add_argument('--epochs', type=int, default=1000,
help='maxium epochs')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='enables CUDA training')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--resume', type=int, default=0,
help='if resume from previous model (default: Non)')
parser.add_argument('--resume_model', default=None,
help='previous model to resume (default: None)')
parser.add_argument('--maxdisp', type=int, default=60,
help='maxium disparity')
args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)
log_path = 'log/' + args.name + '/'
args.output_path = log_path + "output/"
output_path = args.output_path
if not os.path.exists(output_path):
os.makedirs(output_path)
if not os.path.exists(output_path + 'train/'):
os.makedirs(output_path + 'train/')
if not os.path.exists(output_path + 'test/'):
os.makedirs(output_path + 'test/')
if not os.path.exists(output_path + 'eval/'):
os.makedirs(output_path + 'eval/')
model = FuseNetwork(args.maxdisp, 4)
model = nn.DataParallel(model, device_ids=[0, 1])
if args.cuda:
model = model.cuda()
print('Number of model parameters: {}'.format(sum([p.data.nelement() for p in model.parameters()])))
epoch_begin = 0
if args.resume:
epoch_begin = args.resume
if args.resume_model:
model.load_state_dict(torch.load(args.resume_model))
else:
model.load_state_dict(torch.load(log_path + 'model' + str(args.resume) + '.pth'))
train_left_bin, train_right_bin, train_bottom_bin, train_top_bin, train_img, train_disp = \
MBdatalist.dataloader(args.trainpath, mode='5view')
test_left_bin, test_right_bin, test_bottom_bin, test_top_bin, test_img, test_disp = \
MBdatalist.dataloader(args.testpath, mode='5view')
TrainImgLoader = torch.utils.data.DataLoader(
MBloader.myImageFloder([train_left_bin, train_right_bin, train_bottom_bin, train_top_bin],
train_img, train_disp, mode='5view', dispRange=args.maxdisp, training=True, augment=False),
batch_size=args.batch_size, shuffle=True, num_workers=4, drop_last=False)
TestImgLoader = torch.utils.data.DataLoader(
MBloader.myImageFloder([test_left_bin, test_right_bin, test_bottom_bin, test_top_bin],
test_img, test_disp, mode='5view', dispRange=args.maxdisp, training=False, augment=False),
batch_size=1, shuffle=False, num_workers=4, drop_last=False)
print("Train dataset size:", len(train_left_bin))
print("Test dataset size:", len(test_left_bin))
# ========================= Optimization Setup ==============================
optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate, betas=(0.9, 0.999))
train_loss_record = []
test_record = []
eval_record = []
for epoch in range(epoch_begin+1, args.epochs+1):
total_train_loss = 0
total_test_loss = 0
time_epoch = 0
# ====================== training =======================
for batch_idx, (costL_crop, costR_crop, costB_crop, costT_crop, img_crop, disp_crop) in enumerate(TrainImgLoader):
start_time = time.time()
# normalization
img_crop = img_crop.float() / 255.0
loss = train(model, optimizer, [costL_crop, costR_crop, costB_crop, costT_crop],
img_crop, disp_crop, args=args)
total_train_loss += loss
time_epoch += time.time() - start_time
loss_mean = [total_train_loss/len(TrainImgLoader)]
train_loss_record.append(loss_mean)
plt.figure(0)
plt.plot(range(1, len(train_loss_record) + 1), np.asarray(train_loss_record)[:, 0], color='blue', linewidth=0.5, linestyle='-')
plt.title("loss--epoch")
plt.legend(['train loss'])
plt.savefig(log_path + "train_loss.png")
print('epoch %d mean training loss = %.3f, one batch time = %.2f'
% (epoch, loss_mean[0], time_epoch/len(TrainImgLoader)) )
# ======================== TEST ============================
if epoch % 10 == 0:
test_res = test4(model, args, epoch)
test_record.append(test_res)
plt.figure(1)
plt.plot(range(1, len(test_record) + 1), np.asarray(test_record)[:, 0], color='blue', linewidth=0.5, linestyle='-')
plt.plot(range(1, len(test_record) + 1), np.asarray(test_record)[:, 1], color='green', linewidth=0.5, linestyle='-')
plt.title("loss--epoch")
plt.legend(['test avgerr', 'test rms'])
plt.savefig(log_path + "test_record.png")
# ========================= SAVE ===================================
if epoch % 10 == 0:
torch.save(model.state_dict(), log_path + 'model' + str(epoch) + '.pth')