-
Notifications
You must be signed in to change notification settings - Fork 0
/
MIL_test.py
138 lines (126 loc) · 4.91 KB
/
MIL_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
import sys
import os
import numpy as np
import argparse
import random
import openslide
import PIL.Image as Image
import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
import torch.utils.data as data
import torchvision.transforms as transforms
import torchvision.models as models
parser = argparse.ArgumentParser(description='')
parser.add_argument('--lib', type=str, default='filelist', help='path to data file')
parser.add_argument('--output', type=str, default='.', help='name of output directory')
parser.add_argument('--model', type=str, default='', help='path to pretrained model')
parser.add_argument('--batch_size', type=int, default=100, help='how many images to sample per slide (default: 100)')
parser.add_argument('--workers', default=4, type=int, help='number of data loading workers (default: 4)')
def main():
global args
args = parser.parse_args()
#load model
model = models.resnet34(True)
model.fc = nn.Linear(model.fc.in_features, 2)
ch = torch.load(args.model)
model.load_state_dict(ch['state_dict'])
model = model.cuda()
cudnn.benchmark = True
#normalization
normalize = transforms.Normalize(mean=[0.5,0.5,0.5],std=[0.1,0.1,0.1])
trans = transforms.Compose([transforms.ToTensor(),normalize])
#load data
dset = MILdataset(args.lib, trans)
loader = torch.utils.data.DataLoader(
dset,
batch_size=args.batch_size, shuffle=False,
num_workers=args.workers, pin_memory=False)
dset.setmode(1)
probs = inference(loader, model)
maxs = group_max(np.array(dset.slideIDX), probs, len(dset.targets))
fp = open(os.path.join(args.output, 'predictions.csv'), 'w')
fp.write('file,target,prediction,probability\n')
for name, target, prob in zip(dset.slidenames, dset.targets, maxs):
fp.write('{},{},{},{}\n'.format(name, target, int(prob>=0.5), prob))
fp.close()
def inference(loader, model):
model.eval()
probs = torch.FloatTensor(len(loader.dataset))
with torch.no_grad():
for i, input in enumerate(loader):
print('Batch: [{}/{}]'.format(i+1, len(loader)))
input = input.cuda()
output = F.softmax(model(input), dim=1)
probs[i*args.batch_size:i*args.batch_size+input.size(0)] = output.detach()[:,1].clone()
return probs.cpu().numpy()
def group_max(groups, data, nmax):
out = np.empty(nmax)
out[:] = np.nan
order = np.lexsort((data, groups))
groups = groups[order]
data = data[order]
index = np.empty(len(groups), 'bool')
index[-1] = True
index[:-1] = groups[1:] != groups[:-1]
out[groups[index]] = data[index]
return list(out)
class MILdataset(data.Dataset):
def __init__(self, libraryfile='', transform=None):
lib = torch.load(libraryfile)
slides = []
for i,name in enumerate(lib['slides']):
sys.stdout.write('Opening SVS headers: [{}/{}]\r'.format(i+1, len(lib['slides'])))
sys.stdout.flush()
slides.append(openslide.OpenSlide(name))
print('')
#Flatten grid
grid = []
slideIDX = []
for i,g in enumerate(lib['grid']):
grid.extend(g)
slideIDX.extend([i]*len(g))
print('Number of tiles: {}'.format(len(grid)))
self.slidenames = lib['slides']
self.slides = slides
self.targets = lib['targets']
self.grid = grid
self.slideIDX = slideIDX
self.transform = transform
self.mode = None
self.mult = lib['mult']
self.size = int(np.round(224*lib['mult']))
self.level = lib['level']
def setmode(self,mode):
self.mode = mode
def maketraindata(self, idxs):
self.t_data = [(self.slideIDX[x],self.grid[x],self.targets[self.slideIDX[x]]) for x in idxs]
def shuffletraindata(self):
self.t_data = random.sample(self.t_data, len(self.t_data))
def __getitem__(self,index):
if self.mode == 1:
slideIDX = self.slideIDX[index]
coord = self.grid[index]
img = self.slides[slideIDX].read_region(coord,self.level,(self.size,self.size)).convert('RGB')
if self.mult != 1:
img = img.resize((224,224),Image.BILINEAR)
if self.transform is not None:
img = self.transform(img)
return img
elif self.mode == 2:
slideIDX, coord, target = self.t_data[index]
img = self.slides[slideIDX].read_region(coord,self.level,(self.size,self.size)).convert('RGB')
if self.mult != 1:
img = img.resize((224,224),Image.BILINEAR)
if self.transform is not None:
img = self.transform(img)
return img, target
def __len__(self):
if self.mode == 1:
return len(self.grid)
elif self.mode == 2:
return len(self.t_data)
if __name__ == '__main__':
main()