-
Notifications
You must be signed in to change notification settings - Fork 0
/
RNN_test.py
174 lines (138 loc) · 5.49 KB
/
RNN_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
166
167
168
169
170
171
172
173
174
import os
import sys
import openslide
from PIL import Image
import numpy as np
import random
import argparse
import torch
import torch.nn as nn
import torch.utils.data as data
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
import torchvision.transforms as transforms
import torchvision.models as models
parser = argparse.ArgumentParser(description='MIL-nature-medicine-2019 RNN aggregator training script')
parser.add_argument('--lib', type=str, default='', help='path to train MIL library binary')
parser.add_argument('--output', type=str, default='.', help='name of output file')
parser.add_argument('--batch_size', type=int, default=128, help='mini-batch size (default: 128)')
parser.add_argument('--workers', default=4, type=int, help='number of data loading workers (default: 4)')
parser.add_argument('--s', default=10, type=int, help='how many top k tiles to consider (default: 10)')
parser.add_argument('--ndims', default=128, type=int, help='length of hidden representation (default: 128)')
parser.add_argument('--model', type=str, help='path to trained model checkpoint')
parser.add_argument('--rnn', type=str, help='path to trained RNN model checkpoint')
def main():
global args
args = parser.parse_args()
#load libraries
normalize = transforms.Normalize(mean=[0.5,0.5,0.5],std=[0.1,0.1,0.1])
trans = transforms.Compose([
transforms.ToTensor(),
normalize
])
dset = rnndata(args.lib, args.s, False, trans)
loader = torch.utils.data.DataLoader(
dset,
batch_size=args.batch_size, shuffle=False,
num_workers=args.workers, pin_memory=False)
#make model
embedder = ResNetEncoder(args.model)
for param in embedder.parameters():
param.requires_grad = False
embedder = embedder.cuda()
embedder.eval()
rnn = rnn_single(args.ndims)
rnn_dict = torch.load(args.rnn)
rnn.load_state_dict(rnn_dict['state_dict'])
rnn = rnn.cuda()
cudnn.benchmark = True
#
probs = test_single(embedder, rnn, loader)
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, probs):
fp.write('{},{},{},{}\n'.format(name, target, int(prob>=0.5), prob))
fp.close()
def test_single(embedder, rnn, loader):
rnn.eval()
probs = torch.FloatTensor(len(loader.dataset))
with torch.no_grad():
for i, (inputs, target) in enumerate(loader):
print('Validating - Batch: [{}/{}]'.format(i+1,len(loader)))
batch_size = inputs[0].size(0)
state = rnn.init_hidden(batch_size).cuda()
for s in range(len(inputs)):
input = inputs[s].cuda()
_, input = embedder(input)
output, state = rnn(input, state)
output = F.softmax(output, dim=1)
probs[i*args.batch_size:i*args.batch_size+batch_size] = output.detach()[:,1].clone()
return probs.cpu().numpy()
class ResNetEncoder(nn.Module):
def __init__(self, path):
super(ResNetEncoder, self).__init__()
temp = models.resnet34()
temp.fc = nn.Linear(temp.fc.in_features, 2)
ch = torch.load(path)
temp.load_state_dict(ch['state_dict'])
self.features = nn.Sequential(*list(temp.children())[:-1])
self.fc = temp.fc
def forward(self,x):
x = self.features(x)
x = x.view(x.size(0),-1)
return self.fc(x), x
class rnn_single(nn.Module):
def __init__(self, ndims):
super(rnn_single, self).__init__()
self.ndims = ndims
self.fc1 = nn.Linear(512, ndims)
self.fc2 = nn.Linear(ndims, ndims)
self.fc3 = nn.Linear(ndims, 2)
self.activation = nn.ReLU()
def forward(self, input, state):
input = self.fc1(input)
state = self.fc2(state)
state = self.activation(state+input)
output = self.fc3(state)
return output, state
def init_hidden(self, batch_size):
return torch.zeros(batch_size, self.ndims)
class rnndata(data.Dataset):
def __init__(self, path, s, shuffle=False, transform=None):
lib = torch.load(path)
self.s = s
self.transform = transform
self.slidenames = lib['slides']
self.targets = lib['targets']
self.grid = lib['grid']
self.level = lib['level']
self.mult = lib['mult']
self.size = int(224*lib['mult'])
self.shuffle = shuffle
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('')
self.slides = slides
def __getitem__(self,index):
slide = self.slides[index]
grid = self.grid[index]
if self.shuffle:
grid = random.sample(grid,len(grid))
out = []
s = min(self.s, len(grid))
for i in range(s):
img = slide.read_region(grid[i], 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)
out.append(img)
return out, self.targets[index]
def __len__(self):
return len(self.targets)
if __name__ == '__main__':
main()