|
a |
|
b/CRCNet/predict.py |
|
|
1 |
from __future__ import print_function |
|
|
2 |
import torch |
|
|
3 |
import torch.nn.functional as F |
|
|
4 |
from torchvision import datasets, transforms, models |
|
|
5 |
import torch.utils.data.dataset |
|
|
6 |
import numpy as np |
|
|
7 |
from tqdm import tqdm |
|
|
8 |
|
|
|
9 |
import pandas as pd |
|
|
10 |
import utils |
|
|
11 |
|
|
|
12 |
|
|
|
13 |
def predict(checkpoint, test_file, gpu_id=0): |
|
|
14 |
|
|
|
15 |
torch.cuda.set_device(gpu_id) |
|
|
16 |
|
|
|
17 |
model = models.densenet169(num_classes = 2).cuda() |
|
|
18 |
# Load the pretrained model |
|
|
19 |
model.load_state_dict(torch.load(checkpoint, map_location='cpu')) |
|
|
20 |
# Set the model in evaluation mode. In this case this is for the Dropout layers |
|
|
21 |
model = model.half() |
|
|
22 |
model.eval() |
|
|
23 |
|
|
|
24 |
normalize = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) |
|
|
25 |
dataset_test = utils.CSVDataset( |
|
|
26 |
test_file, |
|
|
27 |
transforms.Compose([ |
|
|
28 |
transforms.Resize(256), |
|
|
29 |
transforms.CenterCrop(224), |
|
|
30 |
transforms.ToTensor(), |
|
|
31 |
normalize, |
|
|
32 |
])) |
|
|
33 |
test_loader = torch.utils.data.DataLoader(dataset_test, batch_size=32, shuffle=False, num_workers=4) |
|
|
34 |
|
|
|
35 |
probs = [] |
|
|
36 |
targets = [] |
|
|
37 |
|
|
|
38 |
for data, target in tqdm(test_loader): |
|
|
39 |
# Send the data and label to the device |
|
|
40 |
data, target = data.half().cuda(), target.cuda() |
|
|
41 |
|
|
|
42 |
# Forward pass the data through the model |
|
|
43 |
output = model(data) |
|
|
44 |
output = F.softmax(output, dim=1) |
|
|
45 |
|
|
|
46 |
probs.extend(output.detach().cpu().numpy()) |
|
|
47 |
targets.extend(target.detach().cpu().numpy()) |
|
|
48 |
|
|
|
49 |
return probs, targets |
|
|
50 |
|
|
|
51 |
if __name__ == '__main__': |
|
|
52 |
pass |