-
Notifications
You must be signed in to change notification settings - Fork 88
/
testing_c16.py
140 lines (127 loc) · 6.14 KB
/
testing_c16.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
import dsmil as mil
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torchvision.models as models
import torchvision.transforms.functional as VF
from torchvision import transforms
import sys, argparse, os, glob
import pandas as pd
import numpy as np
from PIL import Image
from collections import OrderedDict
from skimage import exposure, io, img_as_ubyte, transform
import warnings
class BagDataset():
def __init__(self, csv_file, transform=None):
self.files_list = csv_file
self.transform = transform
def __len__(self):
return len(self.files_list)
def __getitem__(self, idx):
path = self.files_list[idx]
img = Image.open(path)
img_name = path.split(os.sep)[-1]
img_pos = np.asarray([int(img_name.split('.')[0].split('_')[0]), int(img_name.split('.')[0].split('_')[1])]) # row, col
sample = {'input': img, 'position': img_pos}
if self.transform:
sample = self.transform(sample)
return sample
class ToTensor(object):
def __call__(self, sample):
img = sample['input']
img = VF.to_tensor(img)
sample['input'] = img
return sample
class Compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, img):
for t in self.transforms:
img = t(img)
return img
def bag_dataset(args, csv_file_path):
transformed_dataset = BagDataset(csv_file=csv_file_path,
transform=Compose([
ToTensor()
]))
dataloader = DataLoader(transformed_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, drop_last=False)
return dataloader, len(transformed_dataset)
def test(args, bags_list, milnet):
milnet.eval()
num_bags = len(bags_list)
Tensor = torch.FloatTensor
for i in range(0, num_bags):
feats_list = []
pos_list = []
classes_list = []
csv_file_path = glob.glob(os.path.join(bags_list[i], '*.jpg'))
dataloader, bag_size = bag_dataset(args, csv_file_path)
with torch.no_grad():
for iteration, batch in enumerate(dataloader):
patches = batch['input'].float().cuda()
patch_pos = batch['position']
feats, classes = milnet.i_classifier(patches)
feats = feats.cpu().numpy()
classes = classes.cpu().numpy()
feats_list.extend(feats)
pos_list.extend(patch_pos)
classes_list.extend(classes)
pos_arr = np.vstack(pos_list)
feats_arr = np.vstack(feats_list)
classes_arr = np.vstack(classes_list)
bag_feats = torch.from_numpy(feats_arr).cuda()
ins_classes = torch.from_numpy(classes_arr).cuda()
bag_prediction, A, _ = milnet.b_classifier(bag_feats, ins_classes)
bag_prediction = torch.sigmoid(bag_prediction).squeeze().cpu().numpy()
color = [0, 0, 0]
if bag_prediction >= args.thres_tumor:
print(bags_list[i] + ' is detected as malignant')
color = [1, 0, 0]
attentions = A
else:
attentions = A
print(bags_list[i] + ' is detected as benign')
color_map = np.zeros((np.amax(pos_arr, 0)[0]+1, np.amax(pos_arr, 0)[1]+1, 3))
attentions = attentions.cpu().numpy()
attentions = exposure.rescale_intensity(attentions, out_range=(0, 1))
for k, pos in enumerate(pos_arr):
tile_color = np.asarray(color) * attentions[k]
color_map[pos[0], pos[1]] = tile_color
slide_name = bags_list[i].split(os.sep)[-1]
color_map = transform.resize(color_map, (color_map.shape[0]*32, color_map.shape[1]*32), order=0)
io.imsave(os.path.join('test-c16', 'output', slide_name+'.png'), img_as_ubyte(color_map), check_contrast=False)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Testing workflow includes attention computing and color map production')
parser.add_argument('--num_classes', type=int, default=1, help='Number of output classes')
parser.add_argument('--batch_size', type=int, default=64, help='Batch size of feeding patches')
parser.add_argument('--num_workers', type=int, default=0)
parser.add_argument('--feats_size', type=int, default=512)
parser.add_argument('--thres_tumor', type=float, default=0.5282700061798096)
args = parser.parse_args()
resnet = models.resnet18(weights=None, norm_layer=nn.InstanceNorm2d)
for param in resnet.parameters():
param.requires_grad = False
resnet.fc = nn.Identity()
i_classifier = mil.IClassifier(resnet, args.feats_size, output_class=args.num_classes).cuda()
b_classifier = mil.BClassifier(input_size=args.feats_size, output_class=args.num_classes).cuda()
milnet = mil.MILNet(i_classifier, b_classifier).cuda()
# milnet.load_state_dict(torch.load('test/mil_weights_fold_4.pth'), strict=False)
aggregator_weights = torch.load('example_aggregator_weights/c16_aggregator.pth')
milnet.load_state_dict(aggregator_weights, strict=False)
state_dict_weights = torch.load(os.path.join('test-c16', 'weights', 'embedder.pth'))
new_state_dict = OrderedDict()
i_classifier = mil.IClassifier(resnet, args.feats_size, output_class=args.num_classes).cuda()
for i in range(4):
state_dict_weights.popitem()
state_dict_init = i_classifier.state_dict()
for (k, v), (k_0, v_0) in zip(state_dict_weights.items(), state_dict_init.items()):
name = k_0
new_state_dict[name] = v
new_state_dict["fc.weight"] = aggregator_weights["i_classifier.fc.0.weight"]
new_state_dict["fc.bias"] = aggregator_weights["i_classifier.fc.0.bias"]
i_classifier.load_state_dict(new_state_dict, strict=True)
milnet.i_classifier = i_classifier
bags_list = glob.glob(os.path.join('test-c16', 'patches', '*'))
os.makedirs(os.path.join('test-c16', 'output'), exist_ok=True)
test(args, bags_list, milnet)