-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathcreate_batches.lua
executable file
·301 lines (258 loc) · 13.1 KB
/
create_batches.lua
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
------------------------------------------------------------------------------------------------
-- If using this code or its variant please cite:
-- Narges Razavian, David Sontag, "Temporal Convolutional Neural Networks
-- for Diagnosis from Lab Tests", ICLR 2016 Workshop track.
-- Link: http://arxiv.org/abs/1511.07938
-- For questions about the code contact Narges ([email protected])
-----------------------------------------------------------------------------------------------
require 'cutorch'
require 'os'
torch.setdefaulttensortype('torch.FloatTensor')
torch.manualSeed(2)
local opt = lapp[[
--gpuid (default 1),
--task (default 'train'),
--exclude_already_onset (default 1),
--imputation_type (default 'none'),
--normalize_each_timeseries (default 1),
--input_dir (default './sampledata'),
--batch_output_dir (default './sampleBatchDir/'),
--batchSize (default 256),
--diagnosis_gap (default 3),
--diagnosis_window (default 6),
--min_icd9_cnt (default 2),
--min_icd9_cnt_exclude (default 1),
--backward_window (default 24),
--min_lab_months_measured (default 0),
--staged_training (default 0),
--min_data_for_training_stage_y (default {20, 5, 0}),
--min_data_for_training_stage_x (default {50, 10, 0}),
]]
cutorch.setDevice(opt.gpuid)
print(opt)
function init()
input_dir = opt.input_dir
batch_output_dir = opt.batch_output_dir .. '/' ..opt.task ..'/'
if (opt.task == 'train' or opt.task =='test' or opt.task =='valid') then
data_torch_bin_filename = input_dir..'/'.. opt.task ..'/x'.. opt.task ..'_normalized.bin'
data_torch_bin_filename_outcomes = input_dir..'/'.. opt.task ..'/y'.. opt.task ..'_outcomes_binary.bin'
elseif (opt.task == 'scoretrain') then
data_torch_bin_filename = input_dir..'/train/xtrain_normalized.bin'
data_torch_bin_filename_outcomes = input_dir..'/train/ytrain_outcomes_binary.bin'
end
os.execute('mkdir -p '.. batch_output_dir)
os.execute('cp ./create_batches.lua ' .. batch_output_dir..'/../')
batchSize = opt.batchSize
imputation_type = opt.imputation_type
normalize_each_timeseries = opt.normalize_each_timeseries
diagnosis_gap = opt.diagnosis_gap --3 months -previously it was 0
diagnosis_window = opt.diagnosis_window --2 years -previously it was 1
exclude_already_onset = opt.exclude_already_onset
min_icd9_cnt = opt.min_icd9_cnt
min_icd9_cnt_exclude = opt.min_icd9_cnt_exclude
backward_window = opt.backward_window -- backward window is the how many months we will look for certain patterns. It is 3 years now
min_lab_months_measured = opt.min_lab_months_measured --i.e. at least measured 3+1 times in the backward window
staged_training = opt.staged_training
if (staged_training == 1) then
min_data_for_training_stage_y = string.gsub(string.gsub(opt.min_data_for_training_stage_y, '{', ''), '}',''):split(',') --{20, 5, 0}
min_data_for_training_stage_x = string.gsub(string.gsub(opt.min_data_for_training_stage_x, '{', ''), '}',''):split(',') --{50, 10, 0}
else
min_data_for_training_stage_y = {-1}
min_data_for_training_stage_x = {-1}
end
if (opt.task=='scoretrain' or opt.task=='test' or opt.task=='valid') then
min_data_for_training_stage_y = {-1}
min_data_for_training_stage_x = {-1}
end
print('attempting to load data from:\n'.. data_torch_bin_filename ..'\nand:'..data_torch_bin_filename_outcomes..'\nThis might take some time. Please wait...')
datax = fromfile(data_torch_bin_filename)
datay = fromfile(data_torch_bin_filename_outcomes)
print('data successfully loaded!')
print(datax:size())
print(datay:size())
labcounts = datax:size(1)
peoplecounts = datax:size(2)
timecounts = datax:size(3)
diseasecount = datay:size(1)
if (datay:size():size() == 2) then
input_format = 2
print('Y is detected to be of size |diseases| x |people|')
print('The following options are not used anymore: staged_training, exclusion, min_data_for_training_stage_y, min_icd9_cnt, diagnosis_gap, diagnosis_window,min_icd9_cnt_exclude.')
if backward_window >= timecounts then
backward_window = timecounts
min_icd9_cnt_exclude = 0
exclude_already_onset = 0
staged_training = 0
normalize_each_timeseries = 0
print('just to remind you - the parameters are updated to --backward_window=' .. backward_window .. ' --min_icd9_cnt_exclude='.. min_icd9_cnt_exclude ..' --exclude_already_onset='.. exclude_already_onset .. ' --staged_training='..staged_training .. ' --normalize_each_timeseries='..normalize_each_timeseries)
end
elseif (timecounts == datay:size(3)) then
input_format = 1
print('Y is detected to be of size |diseases| x |people| x |cohort time|.')
print('If specified, staged_training, exclusion and min_data_for_training_stage_y and min_icd9_cnt and min_icd9_cnt_exclude will be used appropriately.')
end
if (peoplecounts ~= datay:size(2) and input_format == 2 ) then
print ('There is a problem with the size. X should be of size |labs| x |people| x |cohort time| and y should be of size |diseases| x |people|. Aborting.')
os.exit()
end
if (peoplecounts ~= datay:size(2) and input_format == 1 ) then
print ('There is a problem with the size. X should be of size |labs| x |people| x |cohort time| and y should be of size |diseases| x |people| x |time|. Aborting.')
os.exit()
end
end
function normalize(input)
local inputnnx = input:ne(0):clone():typeAs(input)
local mean = torch.cdiv(input:sum(4):clone(), inputnnx:sum(4):clone()):squeeze() --size labcounts
mean[inputnnx:sum(4):clone():squeeze():abs():eq(0)] = 0.0
local std = torch.cdiv(torch.pow(input,2):clone():sum(4):clone(), inputnnx:sum(4):clone()):squeeze():clone() - torch.cmul(mean,mean):clone()
std[inputnnx:sum(4):clone():squeeze():eq(0)] = 1.0 -- we dont' divide or mult by zero std. replace it by 1.0
std[std:lt(0)] = 1.0 --sometimes it's -0.0 don't know why..
std = torch.sqrt(std):clone()
std = std:view(std:size(1),1):clone() -- size labcountsx1
mean = mean:view(mean:size(1),1):clone() --size labcountsx1
input = input - mean:repeatTensor(1, input:size(4)):clone()
input = torch.cmul(input, inputnnx)
stdtmp = std:clone()
stdtmp[stdtmp:lt(0.2)] = 1.0 --if std is small, don't divide and then don't multiply. it's ok if the range is a bit high.
input = torch.cdiv(input, stdtmp:repeatTensor(1,input:size(4)):clone()):clone()
return input:clone(), inputnnx:clone(), mean:clone(), stdtmp:clone()
end
function build()
print('creating batches for task ' .. opt.task..' begins')
collectgarbage()
local batch_input = torch.Tensor(batchSize, 1, labcounts, backward_window):fill(0)
local batch_input_nnx = torch.Tensor(batchSize, 1, labcounts, backward_window):fill(0)
local batch_target = torch.Tensor(batchSize, diseasecount, 1, 1):fill(0)
local batch_tobe_excluded_outcomes = torch.Tensor(batchSize, diseasecount, 1, 1):fill(0)
local batch_mu = torch.Tensor(batchSize, 1, labcounts, backward_window):fill(0)
local batch_std = torch.Tensor(batchSize, 1 ,labcounts, backward_window):fill(0)
local bix = 0
local bcntr = 0
if input_format == 1 then
local training_stage = 0
for epoch = 1, #min_data_for_training_stage_x do
print('epoch:' .. epoch .. 'batch counter:'..bcntr)
training_stage = training_stage + 1
if training_stage > #min_data_for_training_stage_x then
training_stage = #min_data_for_training_stage_x
end
local shuffled_ix = torch.randperm(peoplecounts)
local shuffled_it = torch.randperm(timecounts)
for ox = 1, peoplecounts * timecounts -1 do
local tx = math.fmod(ox, timecounts); if tx == 0 then; tx = timecounts; end;
local ix = math.floor(ox/timecounts) + 1
local t = shuffled_it[tx]
local i = shuffled_ix[ix]
if (exclude_already_onset == 1) then
tmax = timecounts + 1 - diagnosis_gap - diagnosis_window
else
tmax = timecounts + 1
end
if (i > 0) and (t > backward_window)
and (t < tmax)
and (datax[{{},{i},{t}}]:ne(0):sum() > 0)
and (datax[{{},{i},{t-backward_window + 1, t-1}}]:ne(0):sum(1):clone():ne(0):sum() > min_lab_months_measured)
and (torch.sum(datay[{{},{i},{t+diagnosis_gap, t+diagnosis_gap+diagnosis_window}}]:clone()) > tonumber(min_data_for_training_stage_y[training_stage]))
and (torch.sum(datax[{{},{i},{t-backward_window + 1, t}}]:clone():ne(0):clone())> tonumber(min_data_for_training_stage_x[training_stage] ))
then
local input1 = datax[{{},{i},{t- backward_window + 1, t}}]:clone():view(1, 1, labcounts, backward_window)
local input = input1:clone()
local inputnnx = input:ne(0):clone():typeAs(input)
local mean = torch.Tensor(labcounts, 1):fill(0)
local std = torch.Tensor(labcounts, 1):fill(0)
if (opt.normalize_each_timeseries == 1) then
input, inputnnx, mean, std = normalize(input1)
end
local target = datay[{{},{i}, {t+diagnosis_gap, t+diagnosis_gap+diagnosis_window}}]:clone():sum(3):clone():view(1,diseasecount,1,1):ge(min_icd9_cnt)
local tobe_excluded_outcomes = datay[{{},{i}, {t- backward_window + 1, t+diagnosis_gap}}]:clone():sum(3):clone():view(1,diseasecount,1,1):ge(min_icd9_cnt_exclude)
bix = bix + 1
batch_input[{{bix},{1},{},{}}] = input:clone()
batch_input_nnx[{{bix},{1},{},{}}] = inputnnx:clone()
batch_target[{{bix},{},{1},{}}] = target:clone()
batch_tobe_excluded_outcomes[{{bix},{},{1},{}}] = tobe_excluded_outcomes:clone()
batch_mu[{{bix},{1},{},{}}] = mean:view(1,labcounts,1,1):clone():repeatTensor(1, 1, 1, backward_window):clone()
batch_std[{{bix},{1},{},{}}] = std:view(1,labcounts,1,1):clone():repeatTensor(1, 1, 1, backward_window):clone()
if (bix == batchSize or ox == datax:size(2)*datax:size(3) - 1) then
collectgarbage()
print('---'.. bcntr ..'---')
bix = 0
bcntr = bcntr + 1
torch.save(batch_output_dir..'bix'..bcntr..'_batch_input', batch_input)
torch.save(batch_output_dir..'bix'..bcntr..'_batch_input_nnx', batch_input_nnx)
torch.save(batch_output_dir..'bix'..bcntr..'_batch_target', batch_target)
torch.save(batch_output_dir..'bix'..bcntr..'_batch_tobe_excluded_outcomes', batch_tobe_excluded_outcomes)
torch.save(batch_output_dir..'bix'..bcntr..'_batch_mu', batch_mu)
torch.save(batch_output_dir..'bix'..bcntr..'_batch_std', batch_std)
end
end
end
end
end
if input_format == 2 then
print('epoch:' .. 0 .. ' batch counter:'..bcntr)
local shuffled_ix = torch.randperm(peoplecounts)
local shuffled_it = torch.randperm(timecounts)
for ox = 1, peoplecounts * timecounts -1 do
local tx = math.fmod(ox, timecounts); if tx == 0 then; tx = timecounts; end;
local ix = math.floor(ox/timecounts) + 1
local t = shuffled_it[tx]
local i = shuffled_ix[ix]
tmax = timecounts + 1
if (i > 0) and (t >= backward_window) and (t < tmax) and (datax[{{},{i},{t}}]:ne(0):sum() > 0) then
local input1 = datax[{{},{i},{t- backward_window + 1, t}}]:clone():view(1, 1, labcounts, backward_window)
local input = input1:clone()
local inputnnx = input:ne(0):clone():typeAs(input)
local mean = torch.Tensor(labcounts, 1):fill(0)
local std = torch.Tensor(labcounts, 1):fill(0)
if (opt.normalize_each_timeseries == 1) then
input, inputnnx, mean, std = normalize(input1)
end
local target = datay[{{},{i}}]:clone():view(1,diseasecount,1,1):clone()
local tobe_excluded_outcomes = target:clone():fill(0)
bix = bix + 1
batch_input[{{bix},{1},{},{}}] = input:clone()
batch_input_nnx[{{bix},{1},{},{}}] = inputnnx:clone()
batch_target[{{bix},{},{1},{}}] = target:clone()
batch_tobe_excluded_outcomes[{{bix},{},{1},{}}] = tobe_excluded_outcomes:clone()
batch_mu[{{bix},{1},{},{}}] = mean:view(1,labcounts,1,1):clone():repeatTensor(1, 1, 1, backward_window):clone()
batch_std[{{bix},{1},{},{}}] = std:view(1,labcounts,1,1):clone():repeatTensor(1, 1, 1, backward_window):clone()
if (bix == batchSize or ox == peoplecounts*timecounts - 1) then
collectgarbage()
print('---'.. bcntr ..'---')
bix = 0
bcntr = bcntr + 1
torch.save(batch_output_dir..'bix'..bcntr..'_batch_input', batch_input)
torch.save(batch_output_dir..'bix'..bcntr..'_batch_input_nnx', batch_input_nnx)
torch.save(batch_output_dir..'bix'..bcntr..'_batch_target', batch_target)
torch.save(batch_output_dir..'bix'..bcntr..'_batch_tobe_excluded_outcomes', batch_tobe_excluded_outcomes)
torch.save(batch_output_dir..'bix'..bcntr..'_batch_mu', batch_mu)
torch.save(batch_output_dir..'bix'..bcntr..'_batch_std', batch_std)
end
end
end
end
end
function fromfile(fname) --Credit for this function goes to Jure Zbontar
local file = io.open(fname .. '.type')
local type = file:read('*all')
local x
if type == 'float32' then
x = torch.FloatTensor(torch.FloatStorage(fname))
elseif type == 'int32' then
x = torch.IntTensor(torch.IntStorage(fname))
elseif type == 'int64' then
x = torch.LongTensor(torch.LongStorage(fname))
else
print(fname, type)
assert(false)
end
local file = io.open(fname .. '.dim')
local dim = {}
for line in file:lines() do
table.insert(dim, tonumber(line))
end
x = x:reshape(torch.LongStorage(dim))
return x:float()
end
init()
build()