|
a |
|
b/chexbert/src/label.py |
|
|
1 |
import os |
|
|
2 |
import argparse |
|
|
3 |
import torch |
|
|
4 |
import torch.nn as nn |
|
|
5 |
import pandas as pd |
|
|
6 |
import numpy as np |
|
|
7 |
import utils |
|
|
8 |
from models.bert_labeler import bert_labeler |
|
|
9 |
from bert_tokenizer import tokenize |
|
|
10 |
from transformers import BertTokenizer |
|
|
11 |
from collections import OrderedDict |
|
|
12 |
from datasets.unlabeled_dataset import UnlabeledDataset |
|
|
13 |
from constants import * |
|
|
14 |
from tqdm import tqdm |
|
|
15 |
|
|
|
16 |
def collate_fn_no_labels(sample_list): |
|
|
17 |
"""Custom collate function to pad reports in each batch to the max len, |
|
|
18 |
where the reports have no associated labels |
|
|
19 |
@param sample_list (List): A list of samples. Each sample is a dictionary with |
|
|
20 |
keys 'imp', 'len' as returned by the __getitem__ |
|
|
21 |
function of ImpressionsDataset |
|
|
22 |
|
|
|
23 |
@returns batch (dictionary): A dictionary with keys 'imp' and 'len' but now |
|
|
24 |
'imp' is a tensor with padding and batch size as the |
|
|
25 |
first dimension. 'len' is a list of the length of |
|
|
26 |
each sequence in batch |
|
|
27 |
""" |
|
|
28 |
tensor_list = [s['imp'] for s in sample_list] |
|
|
29 |
batched_imp = torch.nn.utils.rnn.pad_sequence(tensor_list, |
|
|
30 |
batch_first=True, |
|
|
31 |
padding_value=PAD_IDX) |
|
|
32 |
len_list = [s['len'] for s in sample_list] |
|
|
33 |
batch = {'imp': batched_imp, 'len': len_list} |
|
|
34 |
return batch |
|
|
35 |
|
|
|
36 |
def load_unlabeled_data(csv_path, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS, |
|
|
37 |
shuffle=False): |
|
|
38 |
""" Create UnlabeledDataset object for the input reports |
|
|
39 |
@param csv_path (string): path to csv file containing reports |
|
|
40 |
@param batch_size (int): the batch size. As per the BERT repository, the max batch size |
|
|
41 |
that can fit on a TITAN XP is 6 if the max sequence length |
|
|
42 |
is 512, which is our case. We have 3 TITAN XP's |
|
|
43 |
@param num_workers (int): how many worker processes to use to load data |
|
|
44 |
@param shuffle (bool): whether to shuffle the data or not |
|
|
45 |
|
|
|
46 |
@returns loader (dataloader): dataloader object for the reports |
|
|
47 |
""" |
|
|
48 |
collate_fn = collate_fn_no_labels |
|
|
49 |
dset = UnlabeledDataset(csv_path) |
|
|
50 |
loader = torch.utils.data.DataLoader(dset, batch_size=batch_size, shuffle=shuffle, |
|
|
51 |
num_workers=NUM_WORKERS, collate_fn=collate_fn) |
|
|
52 |
return loader |
|
|
53 |
|
|
|
54 |
def label(checkpoint_path, csv_path): |
|
|
55 |
"""Labels a dataset of reports |
|
|
56 |
@param checkpoint_path (string): location of saved model checkpoint |
|
|
57 |
@param csv_path (string): location of csv with reports |
|
|
58 |
|
|
|
59 |
@returns y_pred (List[List[int]]): Labels for each of the 14 conditions, per report |
|
|
60 |
""" |
|
|
61 |
ld = load_unlabeled_data(csv_path) |
|
|
62 |
|
|
|
63 |
model = bert_labeler() |
|
|
64 |
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") |
|
|
65 |
if torch.cuda.device_count() > 0: #works even if only 1 GPU available |
|
|
66 |
print("Using", torch.cuda.device_count(), "GPUs!") |
|
|
67 |
model = nn.DataParallel(model, device_ids=list(range(torch.cuda.device_count()))) #to utilize multiple GPU's |
|
|
68 |
model = model.to(device) |
|
|
69 |
checkpoint = torch.load(checkpoint_path) |
|
|
70 |
model.load_state_dict(checkpoint['model_state_dict']) |
|
|
71 |
else: |
|
|
72 |
checkpoint = torch.load(checkpoint_path, map_location=torch.device('cpu')) |
|
|
73 |
new_state_dict = OrderedDict() |
|
|
74 |
for k, v in checkpoint['model_state_dict'].items(): |
|
|
75 |
name = k[7:] # remove `module.` |
|
|
76 |
new_state_dict[name] = v |
|
|
77 |
model.load_state_dict(new_state_dict) |
|
|
78 |
|
|
|
79 |
was_training = model.training |
|
|
80 |
model.eval() |
|
|
81 |
y_pred = [[] for _ in range(len(CONDITIONS))] |
|
|
82 |
|
|
|
83 |
print("\nBegin report impression labeling. The progress bar counts the # of batches completed:") |
|
|
84 |
print("The batch size is %d" % BATCH_SIZE) |
|
|
85 |
with torch.no_grad(): |
|
|
86 |
for i, data in enumerate(tqdm(ld)): |
|
|
87 |
batch = data['imp'] #(batch_size, max_len) |
|
|
88 |
batch = batch.to(device) |
|
|
89 |
src_len = data['len'] |
|
|
90 |
batch_size = batch.shape[0] |
|
|
91 |
attn_mask = utils.generate_attention_masks(batch, src_len, device) |
|
|
92 |
|
|
|
93 |
out = model(batch, attn_mask) |
|
|
94 |
|
|
|
95 |
for j in range(len(out)): |
|
|
96 |
curr_y_pred = out[j].argmax(dim=1) #shape is (batch_size) |
|
|
97 |
y_pred[j].append(curr_y_pred) |
|
|
98 |
|
|
|
99 |
for j in range(len(y_pred)): |
|
|
100 |
y_pred[j] = torch.cat(y_pred[j], dim=0) |
|
|
101 |
|
|
|
102 |
if was_training: |
|
|
103 |
model.train() |
|
|
104 |
|
|
|
105 |
y_pred = [t.tolist() for t in y_pred] |
|
|
106 |
return y_pred |
|
|
107 |
|
|
|
108 |
def save_preds(y_pred, csv_path, out_path): |
|
|
109 |
"""Save predictions as out_path/labeled_reports.csv |
|
|
110 |
@param y_pred (List[List[int]]): list of predictions for each report |
|
|
111 |
@param csv_path (string): path to csv containing reports |
|
|
112 |
@param out_path (string): path to output directory |
|
|
113 |
""" |
|
|
114 |
y_pred = np.array(y_pred) |
|
|
115 |
y_pred = y_pred.T |
|
|
116 |
|
|
|
117 |
df = pd.DataFrame(y_pred, columns=CONDITIONS) |
|
|
118 |
findings = pd.read_csv(csv_path, header=None)[0] |
|
|
119 |
|
|
|
120 |
# dicom was used for labeling training set, but is not available for labeling predictions |
|
|
121 |
# dicom_ids = pd.read_csv(csv_path)['dicom_id'] |
|
|
122 |
|
|
|
123 |
# df['dicom_id'] = dicom_ids.tolist() |
|
|
124 |
df['findings'] = findings.tolist() |
|
|
125 |
new_cols = ['findings'] +CONDITIONS #['dicom_id'] |
|
|
126 |
df = df[new_cols] |
|
|
127 |
|
|
|
128 |
df.replace(0, np.nan, inplace=True) #blank class is NaN |
|
|
129 |
df.replace(3, -1, inplace=True) #uncertain class is -1 |
|
|
130 |
df.replace(2, 0, inplace=True) #negative class is 0 |
|
|
131 |
|
|
|
132 |
df.to_csv(out_path, index=False) |
|
|
133 |
|
|
|
134 |
if __name__ == '__main__': |
|
|
135 |
parser = argparse.ArgumentParser(description='Label a csv file containing radiology reports') |
|
|
136 |
parser.add_argument('-d', '--data', type=str, nargs='?', required=True, |
|
|
137 |
help='path to csv containing reports. The reports should be \ |
|
|
138 |
under the \"Report Impression\" column') |
|
|
139 |
parser.add_argument('-o', '--output_dir', type=str, nargs='?', required=True, |
|
|
140 |
help='path to intended output folder') |
|
|
141 |
parser.add_argument('-c', '--checkpoint', type=str, nargs='?', required=True, |
|
|
142 |
help='path to the pytorch checkpoint') |
|
|
143 |
args = parser.parse_args() |
|
|
144 |
csv_path = args.data |
|
|
145 |
out_path = args.output_dir |
|
|
146 |
checkpoint_path = args.checkpoint |
|
|
147 |
|
|
|
148 |
y_pred = label(checkpoint_path, csv_path) |
|
|
149 |
save_preds(y_pred, csv_path, out_path) |