-
Notifications
You must be signed in to change notification settings - Fork 1
/
test.py
165 lines (120 loc) · 3.94 KB
/
test.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
from typing import Any
from thinc import config
import torch
from VIT import *
#from vit_pytorch import ViT
from models.binae import BINMODEL
import torchvision.transforms as transforms
import numpy as np
import torch.optim as optim
from einops import rearrange
import loadData2 as loadData
import utils as utils
from config import Configs
import os
cfg = Configs().parse()
FLIPPED = False
THRESHOLD = 0.5
SPLITSIZE = cfg.split_size
SETTING = cfg.vit_model_size
TPS = cfg.vit_patch_size
batch_size = cfg.batch_size
experiment = SETTING +'_'+ str(SPLITSIZE)+'_' + str(TPS)
patch_size = TPS
image_size = (SPLITSIZE,SPLITSIZE)
MASKINGRATIO = 0.5
VIS_RESULTS = True
TEST_DIBCO = cfg.testing_dataset
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
count_psnr = utils.count_psnr
imvisualize = utils.imvisualize
load_data_func = loadData.loadData_sets
best_psnr = 0
best_epoch = 0
def sort_batch(batch):
n_batch = len(batch)
train_index = []
train_in = []
train_out = []
for i in range(n_batch):
idx, img, gt_img = batch[i]
train_index.append(idx)
train_in.append(img)
train_out.append(gt_img)
train_index = np.array(train_index)
train_in = np.array(train_in, dtype='float32')
train_out = np.array(train_out, dtype='float32')
train_in = torch.from_numpy(train_in)
train_out = torch.from_numpy(train_out)
return train_index, train_in, train_out
def test_data_loader():
_, _, data_test = load_data_func(flipped=FLIPPED)
test_loader = torch.utils.data.DataLoader(data_test, collate_fn=sort_batch, batch_size=batch_size, shuffle=False, num_workers=2, pin_memory=True)
return test_loader
test_loader = test_data_loader()
patch_size = 16
word_size = 8
if SETTING == 'base':
ENCODERLAYERS = 6
ENCODERHEADS = 8
ENCODERDIM = 768
v = ViT(
image_size = 256,
patch_size = patch_size,
word_size = word_size,
num_classes = 1000,
dim = ENCODERDIM,
depth = ENCODERLAYERS,
heads = ENCODERHEADS,
mlp_dim = 2048
)
IN = ViT(
image_size = 256,
patch_size = patch_size,
word_size = word_size,
num_classes = 1000,
dim = 768,
depth = 4,
heads = 6,
mlp_dim = 2048
)
MASKINGRATIO = 0.5
model = BINMODEL(
encoder = v,
inner_encoder = IN,
masking_ratio = MASKINGRATIO, ## __ doesnt matter for binarization
decoder_dim = ENCODERDIM,
decoder_depth = ENCODERLAYERS,
decoder_heads = ENCODERHEADS # anywhere from 1 to
)
model = model.to(device)
optimizer = optim.AdamW(model.parameters(),lr=1.5e-4, betas=(0.9, 0.95), eps=1e-08, weight_decay=0.05, amsgrad=False)
def visualize(epoch):
losses = 0
for i, (test_index, test_in, test_out) in enumerate(test_loader):
# inputs, labels = data
bs = len(test_in)
inputs = test_in.to(device)
outputs = test_out.to(device)
with torch.no_grad():
loss, pred_pixel_values = model(inputs,outputs)
rec_patches = pred_pixel_values
rec_images = rearrange(rec_patches, 'b (h w) (p1 p2 c) -> b c (h p1) (w p2)', p1 = patch_size, p2 = patch_size, h=image_size[0]//patch_size)
for j in range (0,bs):
imvisualize(inputs[j].cpu(),outputs[j].cpu(),rec_images[j].cpu(),test_index[j],epoch,experiment)
losses += loss.item()
print('valid loss: ', losses / len(test_loader))
def valid_model(epoch):
psnr = count_psnr(epoch,valid_data=TEST_DIBCO,setting=experiment,flipped=FLIPPED , thresh=THRESHOLD)
print('Test PSNR: ', psnr)
#model_name = cfg.model_weights_path
if __name__ == '__main__':
model.load_state_dict(
torch.load(
'C:/Users/Risab/Desktop/Research/Image_Binarization/T2T_Bin_ViT/weights/best-model_16_2016base_256_16.pt',
map_location=device))
a = 457
#count_parameters(model)
epoch = "_testing"
visualize(str(epoch))
valid_model(epoch)