-
Notifications
You must be signed in to change notification settings - Fork 15
/
preprocess-unlabeled.py
172 lines (137 loc) · 5.08 KB
/
preprocess-unlabeled.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
import argparse
import csv
import h5py
import re
import numpy as np
from os.path import join
from sklearn.cross_validation import train_test_split
np.random.seed(1)
class Indexer:
def __init__(self):
self.counter = 2
self.d = {"<unk>": 1}
self.rev = {}
self._lock = False
def convert(self, w):
if w not in self.d:
if self._lock:
return self.d["<unk>"]
self.d[w] = self.counter
self.rev[self.counter] = w
self.counter += 1
return self.d[w]
def lock(self):
self._lock = True
def write(self, outfile):
out = open(outfile, "w")
items = [(v, k) for k, v in self.d.iteritems()]
items.sort()
for v, k in items:
print >> out, k, v
out.close()
def load(self, dictfile):
with open(dictfile, 'r') as f:
for line in f:
self.convert(line.split()[0])
self.lock()
print("SUCCESSFULLY LOADED DICTIONARY FILE")
def parse_input_csv(filename, textfield):
"""
Loads a CSV file and returns the texts as well as the condition-labels
"""
texts = []
print "Parsing", filename
with open(filename, 'r') as f:
reader = csv.reader(f)#, dialect=csv.excel_tab)
field2id = {}
for i, row in enumerate(reader):
if i == 0:
field2id = {fieldname: index for index, fieldname in enumerate(row)}
print field2id
else:
texts.append("<padding> " * args.padding + row[field2id[textfield]] + " <padding>" * args.padding)
return texts
def clean_str(string):
"""
Tokenization/string cleaning.
"""
string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
string = re.sub(r"\'s", " \'s", string)
string = re.sub(r"\'ve", " \'ve", string)
string = re.sub(r"n\'t", " n\'t", string)
string = re.sub(r"\'re", " \'re", string)
string = re.sub(r"\'d", " \'d", string)
string = re.sub(r"\'ll", " \'ll", string)
string = re.sub(r",", " , ", string)
string = re.sub(r"!", " ! ", string)
string = re.sub(r"\(", " ( ", string)
string = re.sub(r"\)", " ) ", string)
string = re.sub(r"\?", " ? ", string)
string = re.sub(r"\s{2,}", " ", string)
return string.strip() # .lower() word2vec is case sensitive
# FILE_PATHS = [# 'nursingNotesClean.csv',
# # 'dischargeSummariesClean.csv',
# 'AllDischargeFinal24Oct16.csv']
args = {}
def main():
global args
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('source', help="Source Input file", type=str)
parser.add_argument('dictfile', help="Dictionary file", type=str)
parser.add_argument('--padding', help="padding around each text", type=int, default=4)
parser.add_argument('--batchsize', help="batchsize if you want to batch the data", type=int, default=1)
parser.add_argument('--max_note_len', help="Cut off all notes longer than this (0 = no cutoff).", type=int, default=0)
parser.add_argument('--filename', help="File name for output file", type=str, default="testdata.h5")
args = parser.parse_args()
# FIELDNAMES IN CSV FILE
textfield = 'text'
# LOAD ALL THE DATA INTO ARRAY
inputs = parse_input_csv(args.source, textfield)
print "FOUND {} DATA POINTS".format(len(inputs))
# CONVERT ALL THE TEXT
lbl = []
tokenizer = Indexer()
tokenizer.load(args.dictfile)
max_len_sent = args.max_note_len
for i, t in enumerate(inputs):
current_convert = [tokenizer.convert(w) for w in clean_str(t).split()]
current_convert = current_convert[:max_len_sent]
lbl.append(current_convert)
if i % 100 == 0:
print "CONVERTING ROW {}".format(i)
print "MAXIMUM TEXT LENGTH IS {}".format(max_len_sent)
# ADD PADDING TO GET TEXT INTO EQUAL LENGTH
for sent in lbl:
if len(sent) < max_len_sent:
sent.extend([2] * (max_len_sent - len(sent)))
# TAKING CARE OF DATA TYPE
lbl = np.array(lbl, dtype=int)
filename = args.filename
if args.batchsize > 1:
#CALCULATE NUMBER OF BATCHES
blocks = lbl.shape[0] / args.batchsize
print "{} batches".format(blocks)
size = blocks * args.batchsize
print "using {} data points".format(size)
lbl = lbl[:size]
train_size = int(blocks * args.batchsize)
print "using {} examples".format(train_size)
with h5py.File(filename, "w") as f:
b = args.batchsize
f['test'] = np.zeros((train_size/b, b, max_len_sent), dtype=int)
#STORE BATCHES
pos = 0
vpos = 0
tpos = 0
#DIFFERENT THAN USUAL PREPROCESSING!!!
for row in range(train_size / b):
for batch in xrange(b):
f['test'][row, batch] = lbl[pos]
pos+=1
else:
with h5py.File(filename, "w") as f:
f['test'] = lbl
if __name__ == '__main__':
main()