Upload folder using huggingface_hub
Browse files- LICENSE.md +674 -0
- ORIGINAL_README.md +153 -0
- configurations/fastai_configs.py +137 -0
- configurations/wavelet_configs.py +17 -0
- evaluation/Model_Evaluation.ipynb +0 -0
- experiments/scp_experiment.py +226 -0
- exploratory_data_analysis/AutoECG_EDA.ipynb +0 -0
- get_dataset.sh +12 -0
- main.py +35 -0
- models/base_model.py +10 -0
- models/basicconv1d.py +224 -0
- models/fastaiModel.py +491 -0
- models/inception1d.py +122 -0
- models/resnet1d.py +299 -0
- models/rnn1d.py +67 -0
- models/wavelet.py +158 -0
- models/xresnet1d.py +239 -0
- output/.getkeep +0 -0
- requirements.yml +0 -0
- utilities/stratify.py +173 -0
- utilities/timeseries_utils.py +649 -0
- utilities/utils.py +509 -0
LICENSE.md
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<https://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
ORIGINAL_README.md
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Automated ECG Interpretation
|
2 |
+
|
3 |
+
[![Contributors][contributors-shield]][contributors-url]
|
4 |
+
[](https://github.com/AutoECG/Automated-ECG-Interpretation/network)
|
5 |
+
[](https://github.com/AutoECG/Automated-ECG-Interpretation/stargazers)
|
6 |
+
[](https://github.com/AutoECG/Automated-ECG-Interpretation/issues)
|
7 |
+
|
8 |
+
<br>
|
9 |
+
|
10 |
+
<div align="center">
|
11 |
+
<img src="https://user-images.githubusercontent.com/46399191/191921241-495090db-a088-46b6-bd09-0f7f21170b0a.png" height="350"/>
|
12 |
+
</div>
|
13 |
+
|
14 |
+
## Summary
|
15 |
+
|
16 |
+
Electrocardiography (ECG) is a key diagnostic tool to assess the cardiac condition of a patient. Automatic ECG interpretation algorithms as diagnosis support systems promise large reliefs for the medical personnel - only based on the number of ECGs that are routinely taken. However, the development of such algorithms requires large training datasets and clear benchmark procedures.
|
17 |
+
|
18 |
+
## Data Description
|
19 |
+
|
20 |
+
The [PTB-XL ECG dataset](https://physionet.org/content/ptb-xl/1.0.1/) is a large dataset of 21837 clinical 12-lead ECGs from 18885 patients of 10 second length. The raw waveform data was annotated by up to two cardiologists, who assigned potentially multiple ECG statements to each record. In total 71 different ECG statements conform to the SCP-ECG standard and cover diagnostic, form, and rhythm statements. Combined with the extensive annotation, this turns the dataset into a rich resource for training and evaluating automatic ECG interpretation algorithms. The dataset is complemented by extensive metadata on demographics, infarction characteristics, likelihoods for diagnostic ECG statements, and annotated signal properties.
|
21 |
+
|
22 |
+
In general, the dataset is organized as follows:
|
23 |
+
|
24 |
+
```
|
25 |
+
ptbxl
|
26 |
+
├── ptbxl_database.csv
|
27 |
+
├── scp_statements.csv
|
28 |
+
├── records100
|
29 |
+
├── 00000
|
30 |
+
│ │ ├── 00001_lr.dat
|
31 |
+
│ │ ├── 00001_lr.hea
|
32 |
+
│ │ ├── ...
|
33 |
+
│ │ ├── 00999_lr.dat
|
34 |
+
│ │ └── 00999_lr.hea
|
35 |
+
│ ├── ...
|
36 |
+
│ └── 21000
|
37 |
+
│ ├── 21001_lr.dat
|
38 |
+
│ ├── 21001_lr.hea
|
39 |
+
│ ├── ...
|
40 |
+
│ ├── 21837_lr.dat
|
41 |
+
│ └── 21837_lr.hea
|
42 |
+
└── records500
|
43 |
+
├── 00000
|
44 |
+
│ ├── 00001_hr.dat
|
45 |
+
│ ├── 00001_hr.hea
|
46 |
+
│ ├── ...
|
47 |
+
│ ├── 00999_hr.dat
|
48 |
+
│ └── 00999_hr.hea
|
49 |
+
├── ...
|
50 |
+
└── 21000
|
51 |
+
├── 21001_hr.dat
|
52 |
+
├── 21001_hr.hea
|
53 |
+
├── ...
|
54 |
+
├── 21837_hr.dat
|
55 |
+
└── 21837_hr.hea
|
56 |
+
```
|
57 |
+
|
58 |
+
The dataset comprises 21837 clinical 12-lead ECG records of 10 seconds length from 18885 patients, where 52% are male and 48% are female with ages covering the whole range from 0 to 95 years (median 62 and interquantile range of 22). The value of the dataset results from the comprehensive collection of many different co-occurring pathologies, but also from a large proportion of healthy control samples.
|
59 |
+
|
60 |
+
| Records | Superclass | Description |
|
61 |
+
|:---|:---|:---|
|
62 |
+
9528 | NORM | Normal ECG |
|
63 |
+
5486 | MI | Myocardial Infarction |
|
64 |
+
5250 | STTC | ST/T Change |
|
65 |
+
4907 | CD | Conduction Disturbance |
|
66 |
+
2655 | HYP | Hypertrophy |
|
67 |
+
|
68 |
+
The waveform files are stored in WaveForm DataBase (WFDB) format with 16-bit precision at a resolution of 1μV/LSB and a sampling frequency of 500Hz (records500/) beside downsampled versions of the waveform data at a sampling frequency of 100Hz (records100/).
|
69 |
+
|
70 |
+
All relevant metadata is stored in ptbxldatabase.csv with one row per record identified by ecgid and it contains 28 columns.
|
71 |
+
|
72 |
+
All information related to the used annotation scheme is stored in a dedicated scp_statements.csv that was enriched with mappings to other annotation standards.
|
73 |
+
|
74 |
+
## Setup
|
75 |
+
|
76 |
+
### Install dependencies
|
77 |
+
Install the dependencies (wfdb, pytorch, torchvision, cudatoolkit, fastai, fastprogress) by creating a conda environment:
|
78 |
+
|
79 |
+
conda env create -f requirements.yml
|
80 |
+
conda activate autoecg_env
|
81 |
+
|
82 |
+
### Get data
|
83 |
+
Download the dataset (PTB-XL) via the follwing bash-script:
|
84 |
+
|
85 |
+
get_dataset.sh
|
86 |
+
|
87 |
+
This script first downloads [PTB-XL from PhysioNet](https://physionet.org/content/ptb-xl/) and stores it in `data/ptbxl/`.
|
88 |
+
|
89 |
+
## Usage
|
90 |
+
|
91 |
+
python main.py
|
92 |
+
|
93 |
+
This will perform all experiments for inception1d.
|
94 |
+
Depending on the executing environment, this will take up to several hours.
|
95 |
+
Once finished, all trained models, predictions and results are stored in `output/`,
|
96 |
+
where for each experiment a sub-folder is created each with `data/`, `models/` and `results/` sub-sub-folders.
|
97 |
+
|
98 |
+
| Model | AUC ↓ | Experiment |
|
99 |
+
|:---|:---|:---|
|
100 |
+
| inception1d | 0.927(00) | All statements |
|
101 |
+
| inception1d | 0.929(00) | Diagnostic statements |
|
102 |
+
| inception1d | 0.926(00) | Diagnostic subclasses |
|
103 |
+
| inception1d | 0.919(00) | Diagnostic superclasses |
|
104 |
+
| inception1d | 0.883(00) | Form statements |
|
105 |
+
| inception1d | 0.949(00) | Rhythm statements |
|
106 |
+
|
107 |
+
### Download model and results
|
108 |
+
|
109 |
+
We also provide a [compressed zip-archive](https://drive.google.com/drive/folders/17za6IanRm7rpb1ZGHLQ80mJvBj_53LXJ?usp=sharing) containing the `output` folder corresponding to our runs including trained model and predictions.
|
110 |
+
|
111 |
+
## Results for Inception1d Model
|
112 |
+
|
113 |
+
| Experiment name | Accuracy | Precision | Recall | F1_Score | Specificity |
|
114 |
+
| ------------- | ------------- | ------------- | ------------- | ------------- | ------------- |
|
115 |
+
| All | 0.9792 | 0.8949 | 0.1408 | 0.4824 | 0.9921 |
|
116 |
+
| Diagnostic | 0.9806 | 0.8440 | 0.1556 | 0.4746 | 0.9952 |
|
117 |
+
| Sub-Diagnostic | 0.9660 | 0.8315 | 0.3021 | 0.5119 | 0.9887 |
|
118 |
+
| Super-Diagnostic | 0.8847 | 0.7938 | 0.6757 | 0.7157 | 0.9251 |
|
119 |
+
| Form | 0.9452 | 0.5619 | 0.1420 | 0.3843 | 0.9916 |
|
120 |
+
| Rhythm | 0.9844 | 0.7676 | 0.4489 | 0.7290 | 0.9722 |
|
121 |
+
|
122 |
+
For more evaluation (Confusion Matrix, ROC curve) information and visualizations visit: [Model Evaluation](https://github.com/AutoECG/Automated-ECG-Interpretation/blob/main/evaluation/Model_Evaluation.ipynb)
|
123 |
+
|
124 |
+
## Contribution
|
125 |
+
|
126 |
+
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**.
|
127 |
+
|
128 |
+
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".
|
129 |
+
Don't forget to give the project a star! Thanks again!
|
130 |
+
|
131 |
+
1. [Fork the Project](https://github.com/AutoECG/Automated-ECG-Interpretation/fork)
|
132 |
+
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
|
133 |
+
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
|
134 |
+
4. Push to the Branch (`git push origin feature/AmazingFeature`)
|
135 |
+
5. Open a Pull Request
|
136 |
+
|
137 |
+
## Future Works
|
138 |
+
|
139 |
+
1. Model Deployment.
|
140 |
+
2. Continue Preprocessing new ECG data from hospitals to test model reliability and accuracy.
|
141 |
+
3. Figure out different parsing options for xml ecg files from different ECG machines versions.
|
142 |
+
|
143 |
+
|
144 |
+
## Contact
|
145 |
+
|
146 |
+
Feel free to reach out to us:
|
147 |
+
- DM [Zaki Kurdya](https://twitter.com/ZakiKurdya)
|
148 |
+
- DM [Zeina Saadeddin](https://twitter.com/jszeina)
|
149 |
+
- DM [Salam Thabit](https://twitter.com/salamThabetDo)
|
150 |
+
|
151 |
+
<!-- MARKDOWN LINKS -->
|
152 |
+
[contributors-shield]: https://img.shields.io/github/contributors/AutoECG/Automated-ECG-Interpretation.svg?style=flat-square&color=blue
|
153 |
+
[contributors-url]: https://github.com/AutoECG/Automated-ECG-Interpretation/graphs/contributors
|
configurations/fastai_configs.py
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
conf_fastai_resnet1d18 = {'model_name': 'fastai_resnet1d18', 'model_type': 'FastaiModel',
|
2 |
+
'parameters': dict()}
|
3 |
+
|
4 |
+
conf_fastai_resnet1d34 = {'model_name': 'fastai_resnet1d34', 'model_type': 'FastaiModel',
|
5 |
+
'parameters': dict()}
|
6 |
+
|
7 |
+
conf_fastai_resnet1d50 = {'model_name': 'fastai_resnet1d50', 'model_type': 'FastaiModel',
|
8 |
+
'parameters': dict()}
|
9 |
+
|
10 |
+
conf_fastai_resnet1d101 = {'model_name': 'fastai_resnet1d101', 'model_type': 'FastaiModel',
|
11 |
+
'parameters': dict()}
|
12 |
+
|
13 |
+
conf_fastai_resnet1d152 = {'model_name': 'fastai_resnet1d152', 'model_type': 'FastaiModel',
|
14 |
+
'parameters': dict()}
|
15 |
+
|
16 |
+
conf_fastai_resnet1d_wang = {'model_name': 'fastai_resnet1d_wang', 'model_type': 'FastaiModel',
|
17 |
+
'parameters': dict()}
|
18 |
+
|
19 |
+
conf_fastai_wrn1d_22 = {'model_name': 'fastai_wrn1d_22', 'model_type': 'FastaiModel',
|
20 |
+
'parameters': dict()}
|
21 |
+
|
22 |
+
conf_fastai_xresnet1d18 = {'model_name': 'fastai_xresnet1d18', 'model_type': 'FastaiModel',
|
23 |
+
'parameters': dict()}
|
24 |
+
|
25 |
+
conf_fastai_xresnet1d34 = {'model_name': 'fastai_xresnet1d34', 'model_type': 'FastaiModel',
|
26 |
+
'parameters': dict()}
|
27 |
+
|
28 |
+
conf_fastai_xresnet1d50 = {'model_name': 'fastai_xresnet1d50', 'model_type': 'FastaiModel',
|
29 |
+
'parameters': dict()}
|
30 |
+
|
31 |
+
# more xresnet50s
|
32 |
+
conf_fastai_xresnet1d50_ep30 = {'model_name': 'fastai_xresnet1d50_ep30', 'model_type': 'FastaiModel',
|
33 |
+
'parameters': dict(epochs=30)}
|
34 |
+
|
35 |
+
conf_fastai_xresnet1d50_validloss_ep30 = {'model_name': 'fastai_xresnet1d50_validloss_ep30',
|
36 |
+
'model_type': 'FastaiModel',
|
37 |
+
'parameters': dict(early_stopping="valid_loss", epochs=30)}
|
38 |
+
|
39 |
+
conf_fastai_xresnet1d50_macroauc_ep30 = {'model_name': 'fastai_xresnet1d50_macroauc_ep30', 'model_type': 'FastaiModel',
|
40 |
+
'parameters': dict(early_stopping="macro_auc", epochs=30)}
|
41 |
+
|
42 |
+
conf_fastai_xresnet1d50_fmax_ep30 = {'model_name': 'fastai_xresnet1d50_fmax_ep30', 'model_type': 'FastaiModel',
|
43 |
+
'parameters': dict(early_stopping="fmax", epochs=30)}
|
44 |
+
|
45 |
+
conf_fastai_xresnet1d50_ep50 = {'model_name': 'fastai_xresnet1d50_ep50', 'model_type': 'FastaiModel',
|
46 |
+
'parameters': dict(epochs=50)}
|
47 |
+
|
48 |
+
conf_fastai_xresnet1d50_validloss_ep50 = {'model_name': 'fastai_xresnet1d50_validloss_ep50',
|
49 |
+
'model_type': 'FastaiModel',
|
50 |
+
'parameters': dict(early_stopping="valid_loss", epochs=50)}
|
51 |
+
|
52 |
+
conf_fastai_xresnet1d50_macroauc_ep50 = {'model_name': 'fastai_xresnet1d50_macroauc_ep50', 'model_type': 'FastaiModel',
|
53 |
+
'parameters': dict(early_stopping="macro_auc", epochs=50)}
|
54 |
+
|
55 |
+
conf_fastai_xresnet1d50_fmax_ep50 = {'model_name': 'fastai_xresnet1d50_fmax_ep50', 'model_type': 'FastaiModel',
|
56 |
+
'parameters': dict(early_stopping="fmax", epochs=50)}
|
57 |
+
|
58 |
+
conf_fastai_xresnet1d101 = {'model_name': 'fastai_xresnet1d101', 'model_type': 'FastaiModel',
|
59 |
+
'parameters': dict()}
|
60 |
+
|
61 |
+
conf_fastai_xresnet1d152 = {'model_name': 'fastai_xresnet1d152', 'model_type': 'FastaiModel',
|
62 |
+
'parameters': dict()}
|
63 |
+
|
64 |
+
conf_fastai_xresnet1d18_deep = {'model_name': 'fastai_xresnet1d18_deep', 'model_type': 'FastaiModel',
|
65 |
+
'parameters': dict()}
|
66 |
+
|
67 |
+
conf_fastai_xresnet1d34_deep = {'model_name': 'fastai_xresnet1d34_deep', 'model_type': 'FastaiModel',
|
68 |
+
'parameters': dict()}
|
69 |
+
|
70 |
+
conf_fastai_xresnet1d50_deep = {'model_name': 'fastai_xresnet1d50_deep', 'model_type': 'FastaiModel',
|
71 |
+
'parameters': dict()}
|
72 |
+
|
73 |
+
conf_fastai_xresnet1d18_deeper = {'model_name': 'fastai_xresnet1d18_deeper', 'model_type': 'FastaiModel',
|
74 |
+
'parameters': dict()}
|
75 |
+
|
76 |
+
conf_fastai_xresnet1d34_deeper = {'model_name': 'fastai_xresnet1d34_deeper', 'model_type': 'FastaiModel',
|
77 |
+
'parameters': dict()}
|
78 |
+
|
79 |
+
conf_fastai_xresnet1d50_deeper = {'model_name': 'fastai_xresnet1d50_deeper', 'model_type': 'FastaiModel',
|
80 |
+
'parameters': dict()}
|
81 |
+
|
82 |
+
conf_fastai_inception1d = {'model_name': 'fastai_inception1d', 'model_type': 'FastaiModel',
|
83 |
+
'parameters': dict()}
|
84 |
+
|
85 |
+
conf_fastai_inception1d_input256 = {'model_name': 'fastai_inception1d_input256', 'model_type': 'FastaiModel',
|
86 |
+
'parameters': dict(input_size=256)}
|
87 |
+
|
88 |
+
conf_fastai_inception1d_input512 = {'model_name': 'fastai_inception1d_input512', 'model_type': 'FastaiModel',
|
89 |
+
'parameters': dict(input_size=512)}
|
90 |
+
|
91 |
+
conf_fastai_inception1d_input1000 = {'model_name': 'fastai_inception1d_input1000', 'model_type': 'FastaiModel',
|
92 |
+
'parameters': dict(input_size=1000)}
|
93 |
+
|
94 |
+
conf_fastai_inception1d_no_residual = {'model_name': 'fastai_inception1d_no_residual', 'model_type': 'FastaiModel',
|
95 |
+
'parameters': dict()}
|
96 |
+
|
97 |
+
conf_fastai_fcn = {'model_name': 'fastai_fcn', 'model_type': 'FastaiModel',
|
98 |
+
'parameters': dict()}
|
99 |
+
|
100 |
+
conf_fastai_fcn_wang = {'model_name': 'fastai_fcn_wang', 'model_type': 'FastaiModel',
|
101 |
+
'parameters': dict()}
|
102 |
+
|
103 |
+
conf_fastai_schirrmeister = {'model_name': 'fastai_schirrmeister', 'model_type': 'FastaiModel',
|
104 |
+
'parameters': dict()}
|
105 |
+
|
106 |
+
conf_fastai_sen = {'model_name': 'fastai_sen', 'model_type': 'FastaiModel',
|
107 |
+
'parameters': dict()}
|
108 |
+
|
109 |
+
conf_fastai_basic1d = {'model_name': 'fastai_basic1d', 'model_type': 'FastaiModel',
|
110 |
+
'parameters': dict()}
|
111 |
+
|
112 |
+
conf_fastai_lstm = {'model_name': 'fastai_lstm', 'model_type': 'FastaiModel',
|
113 |
+
'parameters': dict(lr=1e-3)}
|
114 |
+
|
115 |
+
conf_fastai_gru = {'model_name': 'fastai_gru', 'model_type': 'FastaiModel',
|
116 |
+
'parameters': dict(lr=1e-3)}
|
117 |
+
|
118 |
+
conf_fastai_lstm_bidir = {'model_name': 'fastai_lstm_bidir', 'model_type': 'FastaiModel',
|
119 |
+
'parameters': dict(lr=1e-3)}
|
120 |
+
|
121 |
+
conf_fastai_gru_bidir = {'model_name': 'fastai_gru', 'model_type': 'FastaiModel',
|
122 |
+
'parameters': dict(lr=1e-3)}
|
123 |
+
|
124 |
+
conf_fastai_lstm_input1000 = {'model_name': 'fastai_lstm_input1000', 'model_type': 'FastaiModel',
|
125 |
+
'parameters': dict(input_size=1000, lr=1e-3)}
|
126 |
+
|
127 |
+
conf_fastai_gru_input1000 = {'model_name': 'fastai_gru_input1000', 'model_type': 'FastaiModel',
|
128 |
+
'parameters': dict(input_size=1000, lr=1e-3)}
|
129 |
+
|
130 |
+
conf_fastai_schirrmeister_input500 = {'model_name': 'fastai_schirrmeister_input500', 'model_type': 'FastaiModel',
|
131 |
+
'parameters': dict(input_size=500)}
|
132 |
+
|
133 |
+
conf_fastai_inception1d_input500 = {'model_name': 'fastai_inception1d_input500', 'model_type': 'FastaiModel',
|
134 |
+
'parameters': dict(input_size=500)}
|
135 |
+
|
136 |
+
conf_fastai_fcn_wang_input500 = {'model_name': 'fastai_fcn_wang_input500', 'model_type': 'FastaiModel',
|
137 |
+
'parameters': dict(input_size=500)}
|
configurations/wavelet_configs.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
conf_wavelet_standard_lr = {'model_name': 'Wavelet+LR', 'model_type': 'WAVELET',
|
2 |
+
'parameters': dict(
|
3 |
+
regularizer_C=.001,
|
4 |
+
classifier='LR'
|
5 |
+
)}
|
6 |
+
|
7 |
+
conf_wavelet_standard_rf = {'model_name': 'Wavelet+RF', 'model_type': 'WAVELET',
|
8 |
+
'parameters': dict(
|
9 |
+
regularizer_C=.001,
|
10 |
+
classifier='RF'
|
11 |
+
)}
|
12 |
+
|
13 |
+
conf_wavelet_standard_nn = {'model_name': 'Wavelet+NN', 'model_type': 'WAVELET',
|
14 |
+
'parameters': dict(
|
15 |
+
regularizer_C=.001,
|
16 |
+
classifier='NN'
|
17 |
+
)}
|
evaluation/Model_Evaluation.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
experiments/scp_experiment.py
ADDED
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import multiprocessing
|
2 |
+
from itertools import repeat
|
3 |
+
|
4 |
+
from models import fastaiModel
|
5 |
+
from models.wavelet import WaveletModel
|
6 |
+
from utilities.utils import *
|
7 |
+
|
8 |
+
|
9 |
+
class SCPExperiment:
|
10 |
+
"""
|
11 |
+
Experiment on SCP-ECG statements.
|
12 |
+
All experiments based on SCP are performed and evaluated the same way.
|
13 |
+
"""
|
14 |
+
|
15 |
+
def __init__(self, experiment_name, task, data_folder, output_folder, models,
|
16 |
+
sampling_frequency=100, min_samples=0, train_fold=8, val_fold=9,
|
17 |
+
test_fold=10, folds_type='strat'):
|
18 |
+
self.models = models
|
19 |
+
self.min_samples = min_samples
|
20 |
+
self.task = task
|
21 |
+
self.train_fold = train_fold
|
22 |
+
self.val_fold = val_fold
|
23 |
+
self.test_fold = test_fold
|
24 |
+
self.folds_type = folds_type
|
25 |
+
self.experiment_name = experiment_name
|
26 |
+
self.output_folder = output_folder
|
27 |
+
self.data_folder = data_folder
|
28 |
+
self.sampling_frequency = sampling_frequency
|
29 |
+
|
30 |
+
# create folder structure if needed
|
31 |
+
if not os.path.exists(self.output_folder + self.experiment_name):
|
32 |
+
os.makedirs(self.output_folder + self.experiment_name)
|
33 |
+
if not os.path.exists(self.output_folder + self.experiment_name + '/results/'):
|
34 |
+
os.makedirs(self.output_folder + self.experiment_name + '/results/')
|
35 |
+
if not os.path.exists(output_folder + self.experiment_name + '/models/'):
|
36 |
+
os.makedirs(self.output_folder + self.experiment_name + '/models/')
|
37 |
+
if not os.path.exists(output_folder + self.experiment_name + '/data/'):
|
38 |
+
os.makedirs(self.output_folder + self.experiment_name + '/data/')
|
39 |
+
|
40 |
+
def prepare(self):
|
41 |
+
# Load PTB-XL data
|
42 |
+
self.data, self.raw_labels = load_dataset(self.data_folder, self.sampling_frequency)
|
43 |
+
|
44 |
+
# Preprocess label data
|
45 |
+
self.labels = compute_label_aggregations(self.raw_labels, self.data_folder, self.task)
|
46 |
+
|
47 |
+
# Select relevant data and convert to one-hot
|
48 |
+
self.data, self.labels, self.Y, _ = select_data(self.data, self.labels, self.task, self.min_samples,
|
49 |
+
self.output_folder + self.experiment_name + '/data/')
|
50 |
+
self.input_shape = self.data[0].shape
|
51 |
+
|
52 |
+
# 10th fold for testing (9th for now)
|
53 |
+
self.X_test = self.data[self.labels.strat_fold == self.test_fold]
|
54 |
+
self.y_test = self.Y[self.labels.strat_fold == self.test_fold]
|
55 |
+
# 9th fold for validation (8th for now)
|
56 |
+
self.X_val = self.data[self.labels.strat_fold == self.val_fold]
|
57 |
+
self.y_val = self.Y[self.labels.strat_fold == self.val_fold]
|
58 |
+
# rest for training
|
59 |
+
self.X_train = self.data[self.labels.strat_fold <= self.train_fold]
|
60 |
+
self.y_train = self.Y[self.labels.strat_fold <= self.train_fold]
|
61 |
+
|
62 |
+
# Preprocess signal data
|
63 |
+
self.X_train, self.X_val, self.X_test = preprocess_signals(self.X_train, self.X_val, self.X_test,
|
64 |
+
self.output_folder + self.experiment_name + '/data/')
|
65 |
+
self.n_classes = self.y_train.shape[1]
|
66 |
+
|
67 |
+
# save train and test labels
|
68 |
+
self.y_train.dump(self.output_folder + self.experiment_name + '/data/y_train.npy')
|
69 |
+
self.y_val.dump(self.output_folder + self.experiment_name + '/data/y_val.npy')
|
70 |
+
self.y_test.dump(self.output_folder + self.experiment_name + '/data/y_test.npy')
|
71 |
+
|
72 |
+
model_name = 'naive'
|
73 |
+
# create most naive predictions via simple mean in training
|
74 |
+
mpath = self.output_folder + self.experiment_name + '/models/' + model_name + '/'
|
75 |
+
# create folder for model outputs
|
76 |
+
if not os.path.exists(mpath):
|
77 |
+
os.makedirs(mpath)
|
78 |
+
if not os.path.exists(mpath + 'results/'):
|
79 |
+
os.makedirs(mpath + 'results/')
|
80 |
+
|
81 |
+
mean_y = np.mean(self.y_train, axis=0)
|
82 |
+
np.array([mean_y] * len(self.y_train)).dump(mpath + 'y_train_pred.npy')
|
83 |
+
np.array([mean_y] * len(self.y_test)).dump(mpath + 'y_test_pred.npy')
|
84 |
+
np.array([mean_y] * len(self.y_val)).dump(mpath + 'y_val_pred.npy')
|
85 |
+
|
86 |
+
def perform(self):
|
87 |
+
for model_description in self.models:
|
88 |
+
model_name = model_description['model_name']
|
89 |
+
model_type = model_description['model_type']
|
90 |
+
model_params = model_description['parameters']
|
91 |
+
|
92 |
+
mpath = self.output_folder + self.experiment_name + '/models/' + model_name + '/'
|
93 |
+
# create folder for model outputs
|
94 |
+
if not os.path.exists(mpath):
|
95 |
+
os.makedirs(mpath)
|
96 |
+
if not os.path.exists(mpath + 'results/'):
|
97 |
+
os.makedirs(mpath + 'results/')
|
98 |
+
|
99 |
+
n_classes = self.Y.shape[1]
|
100 |
+
# load respective model
|
101 |
+
if model_type == 'WAVELET':
|
102 |
+
model = WaveletModel(model_name, n_classes, self.sampling_frequency, mpath, self.input_shape,
|
103 |
+
**model_params)
|
104 |
+
elif model_type == "FastaiModel":
|
105 |
+
model = fastaiModel.FastaiModel(model_name, n_classes, self.sampling_frequency, mpath, self.input_shape,
|
106 |
+
**model_params)
|
107 |
+
else:
|
108 |
+
assert True
|
109 |
+
break
|
110 |
+
|
111 |
+
# fit model
|
112 |
+
model.fit(self.X_train, self.y_train, self.X_val, self.y_val)
|
113 |
+
# predict and dump
|
114 |
+
model.predict(self.X_train).dump(mpath + 'y_train_pred.npy')
|
115 |
+
model.predict(self.X_val).dump(mpath + 'y_val_pred.npy')
|
116 |
+
model.predict(self.X_test).dump(mpath + 'y_test_pred.npy')
|
117 |
+
|
118 |
+
model_name = 'ensemble'
|
119 |
+
# create ensemble predictions via simple mean across model predictions (except naive predictions)
|
120 |
+
ensemblepath = self.output_folder + self.experiment_name + '/models/' + model_name + '/'
|
121 |
+
# create folder for model outputs
|
122 |
+
if not os.path.exists(ensemblepath):
|
123 |
+
os.makedirs(ensemblepath)
|
124 |
+
if not os.path.exists(ensemblepath + 'results/'):
|
125 |
+
os.makedirs(ensemblepath + 'results/')
|
126 |
+
# load all predictions
|
127 |
+
ensemble_train, ensemble_val, ensemble_test = [], [], []
|
128 |
+
for model_description in os.listdir(self.output_folder + self.experiment_name + '/models/'):
|
129 |
+
if not model_description in ['ensemble', 'naive']:
|
130 |
+
mpath = self.output_folder + self.experiment_name + '/models/' + model_description + '/'
|
131 |
+
ensemble_train.append(np.load(mpath + 'y_train_pred.npy', allow_pickle=True))
|
132 |
+
ensemble_val.append(np.load(mpath + 'y_val_pred.npy', allow_pickle=True))
|
133 |
+
ensemble_test.append(np.load(mpath + 'y_test_pred.npy', allow_pickle=True))
|
134 |
+
# dump mean predictions
|
135 |
+
np.array(ensemble_train).mean(axis=0).dump(ensemblepath + 'y_train_pred.npy')
|
136 |
+
np.array(ensemble_test).mean(axis=0).dump(ensemblepath + 'y_test_pred.npy')
|
137 |
+
np.array(ensemble_val).mean(axis=0).dump(ensemblepath + 'y_val_pred.npy')
|
138 |
+
|
139 |
+
def evaluate(self, n_bootstraping_samples=100, n_jobs=20, bootstrap_eval=False, dumped_bootstraps=True):
|
140 |
+
# get labels
|
141 |
+
global train_samples, val_samples
|
142 |
+
y_train = np.load(self.output_folder + self.experiment_name + '/data/y_train.npy', allow_pickle=True)
|
143 |
+
y_val = np.load(self.output_folder + self.experiment_name + '/data/y_val.npy', allow_pickle=True)
|
144 |
+
y_test = np.load(self.output_folder + self.experiment_name + '/data/y_test.npy', allow_pickle=True)
|
145 |
+
|
146 |
+
# if bootstrapping then generate appropriate samples for each
|
147 |
+
if bootstrap_eval:
|
148 |
+
if not dumped_bootstraps:
|
149 |
+
train_samples = np.array(get_appropriate_bootstrap_samples(y_train, n_bootstraping_samples))
|
150 |
+
test_samples = np.array(get_appropriate_bootstrap_samples(y_test, n_bootstraping_samples))
|
151 |
+
val_samples = np.array(get_appropriate_bootstrap_samples(y_val, n_bootstraping_samples))
|
152 |
+
else:
|
153 |
+
test_samples = np.load(self.output_folder + self.experiment_name + '/test_bootstrap_ids.npy',
|
154 |
+
allow_pickle=True)
|
155 |
+
else:
|
156 |
+
train_samples = np.array([range(len(y_train))])
|
157 |
+
test_samples = np.array([range(len(y_test))])
|
158 |
+
val_samples = np.array([range(len(y_val))])
|
159 |
+
|
160 |
+
# store samples for future evaluations
|
161 |
+
train_samples.dump(self.output_folder + self.experiment_name + '/train_bootstrap_ids.npy')
|
162 |
+
test_samples.dump(self.output_folder + self.experiment_name + '/test_bootstrap_ids.npy')
|
163 |
+
val_samples.dump(self.output_folder + self.experiment_name + '/val_bootstrap_ids.npy')
|
164 |
+
|
165 |
+
# iterate over all models fitted so far
|
166 |
+
for m in sorted(os.listdir(self.output_folder + self.experiment_name + '/models')):
|
167 |
+
print(m)
|
168 |
+
mpath = self.output_folder + self.experiment_name + '/models/' + m + '/'
|
169 |
+
rpath = self.output_folder + self.experiment_name + '/models/' + m + '/results/'
|
170 |
+
|
171 |
+
# load predictions
|
172 |
+
y_train_pred = np.load(mpath + 'y_train_pred.npy', allow_pickle=True)
|
173 |
+
y_val_pred = np.load(mpath + 'y_val_pred.npy', allow_pickle=True)
|
174 |
+
y_test_pred = np.load(mpath + 'y_test_pred.npy', allow_pickle=True)
|
175 |
+
|
176 |
+
if self.experiment_name == 'exp_ICBEB':
|
177 |
+
# compute classwise thresholds such that recall-focused Gbeta is optimized
|
178 |
+
thresholds = find_optimal_cutoff_thresholds_for_Gbeta(y_train, y_train_pred)
|
179 |
+
else:
|
180 |
+
thresholds = None
|
181 |
+
|
182 |
+
pool = multiprocessing.Pool(n_jobs)
|
183 |
+
|
184 |
+
tr_df = pd.concat(pool.starmap(generate_results,
|
185 |
+
zip(train_samples, repeat(y_train), repeat(y_train_pred),
|
186 |
+
repeat(thresholds))))
|
187 |
+
tr_df_point = generate_results(range(len(y_train)), y_train, y_train_pred, thresholds)
|
188 |
+
tr_df_result = pd.DataFrame(
|
189 |
+
np.array([
|
190 |
+
tr_df_point.mean().values,
|
191 |
+
tr_df.mean().values,
|
192 |
+
tr_df.quantile(0.05).values,
|
193 |
+
tr_df.quantile(0.95).values]),
|
194 |
+
columns=tr_df.columns,
|
195 |
+
index=['point', 'mean', 'lower', 'upper'])
|
196 |
+
|
197 |
+
te_df = pd.concat(pool.starmap(generate_results,
|
198 |
+
zip(test_samples, repeat(y_test), repeat(y_test_pred), repeat(thresholds))))
|
199 |
+
te_df_point = generate_results(range(len(y_test)), y_test, y_test_pred, thresholds)
|
200 |
+
te_df_result = pd.DataFrame(
|
201 |
+
np.array([
|
202 |
+
te_df_point.mean().values,
|
203 |
+
te_df.mean().values,
|
204 |
+
te_df.quantile(0.05).values,
|
205 |
+
te_df.quantile(0.95).values]),
|
206 |
+
columns=te_df.columns,
|
207 |
+
index=['point', 'mean', 'lower', 'upper'])
|
208 |
+
|
209 |
+
val_df = pd.concat(pool.starmap(generate_results,
|
210 |
+
zip(val_samples, repeat(y_val), repeat(y_val_pred), repeat(thresholds))))
|
211 |
+
val_df_point = generate_results(range(len(y_val)), y_val, y_val_pred, thresholds)
|
212 |
+
val_df_result = pd.DataFrame(
|
213 |
+
np.array([
|
214 |
+
val_df_point.mean().values,
|
215 |
+
val_df.mean().values,
|
216 |
+
val_df.quantile(0.05).values,
|
217 |
+
val_df.quantile(0.95).values]),
|
218 |
+
columns=val_df.columns,
|
219 |
+
index=['point', 'mean', 'lower', 'upper'])
|
220 |
+
|
221 |
+
pool.close()
|
222 |
+
|
223 |
+
# dump results
|
224 |
+
tr_df_result.to_csv(rpath + 'tr_results.csv')
|
225 |
+
val_df_result.to_csv(rpath + 'val_results.csv')
|
226 |
+
te_df_result.to_csv(rpath + 'te_results.csv')
|
exploratory_data_analysis/AutoECG_EDA.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
get_dataset.sh
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
####################################
|
4 |
+
# GET PTB-XL DATABASE
|
5 |
+
####################################
|
6 |
+
|
7 |
+
mkdir -p data
|
8 |
+
cd data || return
|
9 |
+
wget https://storage.googleapis.com/ptb-xl-1.0.1.physionet.org/ptb-xl-a-large-publicly-available-electrocardiography-dataset-1.0.1.zip --no-check-certificate
|
10 |
+
unzip ptb-xl-a-large-publicly-available-electrocardiography-dataset-1.0.1.zip
|
11 |
+
mv ptb-xl-a-large-publicly-available-electrocardiography-dataset-1.0.1 ptbxl
|
12 |
+
cd ..
|
main.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# model configs
|
2 |
+
from configurations.fastai_configs import conf_fastai_inception1d
|
3 |
+
from experiments.scp_experiment import SCPExperiment
|
4 |
+
from utilities.utils import generate_ptbxl_summary_table
|
5 |
+
|
6 |
+
|
7 |
+
def main():
|
8 |
+
data_folder = 'data/ptbxl/'
|
9 |
+
output_folder = 'output/'
|
10 |
+
|
11 |
+
models = [conf_fastai_inception1d]
|
12 |
+
|
13 |
+
# STANDARD SCP EXPERIMENTS ON PTB-XL
|
14 |
+
|
15 |
+
experiments = [
|
16 |
+
('exp0', 'all'),
|
17 |
+
('exp1', 'diagnostic'),
|
18 |
+
('exp1.1', 'subdiagnostic'),
|
19 |
+
('exp1.1.1', 'superdiagnostic'),
|
20 |
+
('exp2', 'form'),
|
21 |
+
('exp3', 'rhythm')
|
22 |
+
]
|
23 |
+
|
24 |
+
for name, task in experiments:
|
25 |
+
e = SCPExperiment(name, task, data_folder, output_folder, models)
|
26 |
+
e.prepare()
|
27 |
+
e.perform()
|
28 |
+
e.evaluate()
|
29 |
+
|
30 |
+
# generate summary table
|
31 |
+
generate_ptbxl_summary_table()
|
32 |
+
|
33 |
+
|
34 |
+
if __name__ == "__main__":
|
35 |
+
main()
|
models/base_model.py
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
class ClassificationModel(object):
|
2 |
+
|
3 |
+
def __init__(self):
|
4 |
+
pass
|
5 |
+
|
6 |
+
def fit(self, X_train, y_train, X_val, y_val):
|
7 |
+
pass
|
8 |
+
|
9 |
+
def predict(self, X, full_sequence=True):
|
10 |
+
pass
|
models/basicconv1d.py
ADDED
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
|
5 |
+
from fastai.layers import *
|
6 |
+
from fastai.core import *
|
7 |
+
|
8 |
+
'''
|
9 |
+
This layer creates a convolution kernel that is convolved with the layer input
|
10 |
+
over a single spatial (or temporal) dimension to produce a tensor of outputs.
|
11 |
+
If use_bias is True, a bias vector is created and added to the outputs.
|
12 |
+
Finally, if activation is not None, it is applied to the outputs as well.
|
13 |
+
https://keras.io/api/layers/convolution_layers/convolution1d/
|
14 |
+
'''
|
15 |
+
|
16 |
+
|
17 |
+
def _conv1d(in_planes, out_planes, kernel_size=3, stride=1, dilation=1, act="relu", bn=True, drop_p=0):
|
18 |
+
lst = []
|
19 |
+
if (drop_p > 0):
|
20 |
+
lst.append(nn.Dropout(drop_p))
|
21 |
+
lst.append(nn.Conv1d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=(kernel_size - 1) // 2,
|
22 |
+
dilation=dilation, bias=not bn))
|
23 |
+
if bn:
|
24 |
+
lst.append(nn.BatchNorm1d(out_planes))
|
25 |
+
if act == "relu":
|
26 |
+
lst.append(nn.ReLU(True))
|
27 |
+
if act == "elu":
|
28 |
+
lst.append(nn.ELU(True))
|
29 |
+
if act == "prelu":
|
30 |
+
lst.append(nn.PReLU(True))
|
31 |
+
return nn.Sequential(*lst)
|
32 |
+
|
33 |
+
|
34 |
+
def _fc(in_planes, out_planes, act="relu", bn=True):
|
35 |
+
lst = [nn.Linear(in_planes, out_planes, bias=not (bn))]
|
36 |
+
if bn:
|
37 |
+
lst.append(nn.BatchNorm1d(out_planes))
|
38 |
+
if act == "relu":
|
39 |
+
lst.append(nn.ReLU(True))
|
40 |
+
if act == "elu":
|
41 |
+
lst.append(nn.ELU(True))
|
42 |
+
if act == "prelu":
|
43 |
+
lst.append(nn.PReLU(True))
|
44 |
+
return nn.Sequential(*lst)
|
45 |
+
|
46 |
+
|
47 |
+
def cd_adaptive_concat_pool(relevant, irrelevant, module):
|
48 |
+
mpr, mpi = module.mp.attrib(relevant, irrelevant)
|
49 |
+
apr, api = module.ap.attrib(relevant, irrelevant)
|
50 |
+
return torch.cat([mpr, apr], 1), torch.cat([mpi, api], 1)
|
51 |
+
|
52 |
+
|
53 |
+
def attrib_adaptive_concat_pool(self, relevant, irrelevant):
|
54 |
+
return cd_adaptive_concat_pool(relevant, irrelevant, self)
|
55 |
+
|
56 |
+
|
57 |
+
class AdaptiveConcatPool1d(nn.Module):
|
58 |
+
"""Layer that concat `AdaptiveAvgPool1d` and `AdaptiveMaxPool1d`."""
|
59 |
+
|
60 |
+
def __init__(self, sz: Optional[int] = None):
|
61 |
+
"""Output will be 2*sz or 2 if sz is None"""
|
62 |
+
super().__init__()
|
63 |
+
sz = sz or 1
|
64 |
+
self.ap, self.mp = nn.AdaptiveAvgPool1d(sz), nn.AdaptiveMaxPool1d(sz)
|
65 |
+
|
66 |
+
def forward(self, x): return torch.cat([self.mp(x), self.ap(x)], 1)
|
67 |
+
|
68 |
+
def attrib(self, relevant, irrelevant):
|
69 |
+
return attrib_adaptive_concat_pool(self, relevant, irrelevant)
|
70 |
+
|
71 |
+
|
72 |
+
class SqueezeExcite1d(nn.Module):
|
73 |
+
"""squeeze excite block as used for example in LSTM FCN"""
|
74 |
+
|
75 |
+
def __init__(self, channels, reduction=16):
|
76 |
+
super().__init__()
|
77 |
+
channels_reduced = channels // reduction
|
78 |
+
self.w1 = torch.nn.Parameter(torch.randn(channels_reduced, channels).unsqueeze(0))
|
79 |
+
self.w2 = torch.nn.Parameter(torch.randn(channels, channels_reduced).unsqueeze(0))
|
80 |
+
|
81 |
+
def forward(self, x):
|
82 |
+
# input is bs,ch,seq
|
83 |
+
z = torch.mean(x, dim=2, keepdim=True) # bs,ch
|
84 |
+
intermed = F.relu(torch.matmul(self.w1, z)) # (1,ch_red,ch * bs,ch,1) = (bs, ch_red, 1)
|
85 |
+
s = F.sigmoid(torch.matmul(self.w2, intermed)) # (1,ch,ch_red * bs, ch_red, 1=bs, ch, 1
|
86 |
+
return s * x # bs,ch,seq * bs, ch,1 = bs,ch,seq
|
87 |
+
|
88 |
+
|
89 |
+
def weight_init(m):
|
90 |
+
"""call weight initialization for model n via n.apply(weight_init)"""
|
91 |
+
if isinstance(m, nn.Conv1d) or isinstance(m, nn.Linear):
|
92 |
+
nn.init.kaiming_normal_(m.weight)
|
93 |
+
if m.bias is not None:
|
94 |
+
nn.init.zeros_(m.bias)
|
95 |
+
if isinstance(m, nn.BatchNorm1d):
|
96 |
+
nn.init.constant_(m.weight, 1)
|
97 |
+
nn.init.constant_(m.bias, 0)
|
98 |
+
if isinstance(m, SqueezeExcite1d):
|
99 |
+
stdv1 = math.sqrt(2. / m.w1.size[0])
|
100 |
+
nn.init.normal_(m.w1, 0., stdv1)
|
101 |
+
stdv2 = math.sqrt(1. / m.w2.size[1])
|
102 |
+
nn.init.normal_(m.w2, 0., stdv2)
|
103 |
+
|
104 |
+
|
105 |
+
def create_head1d(nf: int, nc: int, lin_ftrs: Optional[Collection[int]] = None, ps: Floats = 0.5,
|
106 |
+
bn_final: bool = False, bn: bool = True, act="relu", concat_pooling=True):
|
107 |
+
"""Model head that takes `nf` features, runs through `lin_ftrs`, and about `nc` classes; added bn and act here"""
|
108 |
+
lin_ftrs = [2 * nf if concat_pooling else nf, nc] if lin_ftrs is None else [
|
109 |
+
2 * nf if concat_pooling else nf] + lin_ftrs + [
|
110 |
+
nc] # was [nf, 512,nc]
|
111 |
+
ps = listify(ps)
|
112 |
+
if len(ps) == 1: ps = [ps[0] / 2] * (len(lin_ftrs) - 2) + ps
|
113 |
+
actns = [nn.ReLU(inplace=True) if act == "relu" else nn.ELU(inplace=True)] * (len(lin_ftrs) - 2) + [None]
|
114 |
+
layers = [AdaptiveConcatPool1d() if concat_pooling else nn.MaxPool1d(2), Flatten()]
|
115 |
+
for ni, no, p, actn in zip(lin_ftrs[:-1], lin_ftrs[1:], ps, actns):
|
116 |
+
layers += bn_drop_lin(ni, no, bn, p, actn)
|
117 |
+
if bn_final: layers.append(nn.BatchNorm1d(lin_ftrs[-1], momentum=0.01))
|
118 |
+
return nn.Sequential(*layers)
|
119 |
+
|
120 |
+
|
121 |
+
# basic convolutional architecture
|
122 |
+
|
123 |
+
class BasicConv1d(nn.Sequential):
|
124 |
+
"""basic conv1d"""
|
125 |
+
|
126 |
+
def __init__(self, filters=None, kernel_size=3, stride=2, dilation=1, pool=0, pool_stride=1,
|
127 |
+
squeeze_excite_reduction=0, num_classes=2, input_channels=8, act="relu", bn=True, headless=False,
|
128 |
+
split_first_layer=False, drop_p=0., lin_ftrs_head=None, ps_head=0.5, bn_final_head=False, bn_head=True,
|
129 |
+
act_head="relu", concat_pooling=True):
|
130 |
+
if filters is None:
|
131 |
+
filters = [128, 128, 128, 128]
|
132 |
+
layers = []
|
133 |
+
if isinstance(kernel_size, int):
|
134 |
+
kernel_size = [kernel_size] * len(filters)
|
135 |
+
for i in range(len(filters)):
|
136 |
+
layers_tmp = [_conv1d(input_channels if i == 0 else filters[i - 1], filters[i], kernel_size=kernel_size[i],
|
137 |
+
stride=(1 if (split_first_layer is True and i == 0) else stride), dilation=dilation,
|
138 |
+
act="none" if ((headless is True and i == len(filters) - 1) or (
|
139 |
+
split_first_layer is True and i == 0)) else act,
|
140 |
+
bn=False if (headless is True and i == len(filters) - 1) else bn,
|
141 |
+
drop_p=(0. if i == 0 else drop_p))]
|
142 |
+
|
143 |
+
if split_first_layer is True and i == 0:
|
144 |
+
layers_tmp.append(_conv1d(filters[0], filters[0], kernel_size=1, stride=1, act=act, bn=bn, drop_p=0.))
|
145 |
+
# layers_tmp.append(nn.Linear(filters[0],filters[0],bias=not(bn)))
|
146 |
+
# layers_tmp.append(_fc(filters[0],filters[0],act=act,bn=bn))
|
147 |
+
if pool > 0 and i < len(filters) - 1:
|
148 |
+
layers_tmp.append(nn.MaxPool1d(pool, stride=pool_stride, padding=(pool - 1) // 2))
|
149 |
+
if squeeze_excite_reduction > 0:
|
150 |
+
layers_tmp.append(SqueezeExcite1d(filters[i], squeeze_excite_reduction))
|
151 |
+
layers.append(nn.Sequential(*layers_tmp))
|
152 |
+
|
153 |
+
# head layers.append(nn.AdaptiveAvgPool1d(1)) layers.append(nn.Linear(filters[-1],num_classes)) head
|
154 |
+
# #inplace=True leads to a runtime error see ReLU+ dropout
|
155 |
+
# https://discuss.pytorch.org/t/relu-dropout-inplace/13467/5
|
156 |
+
self.headless = headless
|
157 |
+
if headless is True:
|
158 |
+
head = nn.Sequential(nn.AdaptiveAvgPool1d(1), Flatten())
|
159 |
+
else:
|
160 |
+
head = create_head1d(filters[-1], nc=num_classes, lin_ftrs=lin_ftrs_head, ps=ps_head,
|
161 |
+
bn_final=bn_final_head, bn=bn_head, act=act_head, concat_pooling=concat_pooling)
|
162 |
+
layers.append(head)
|
163 |
+
|
164 |
+
super().__init__(*layers)
|
165 |
+
|
166 |
+
def get_layer_groups(self):
|
167 |
+
return self[2], self[-1]
|
168 |
+
|
169 |
+
def get_output_layer(self):
|
170 |
+
if self.headless is False:
|
171 |
+
return self[-1][-1]
|
172 |
+
else:
|
173 |
+
return None
|
174 |
+
|
175 |
+
def set_output_layer(self, x):
|
176 |
+
if self.headless is False:
|
177 |
+
self[-1][-1] = x
|
178 |
+
|
179 |
+
|
180 |
+
# convenience functions for basic convolutional architectures
|
181 |
+
def fcn(filters=None, num_classes=2, input_channels=8):
|
182 |
+
if filters is None:
|
183 |
+
filters = [128] * 5
|
184 |
+
filters_in = filters + [num_classes]
|
185 |
+
return BasicConv1d(filters=filters_in, kernel_size=3, stride=1, pool=2, pool_stride=2,
|
186 |
+
input_channels=input_channels, act="relu", bn=True, headless=True)
|
187 |
+
|
188 |
+
|
189 |
+
def fcn_wang(num_classes=2, input_channels=8, lin_ftrs_head=None, ps_head=0.5, bn_final_head=False, bn_head=True,
|
190 |
+
act_head="relu", concat_pooling=True):
|
191 |
+
return BasicConv1d(filters=[128, 256, 128], kernel_size=[8, 5, 3], stride=1, pool=0, pool_stride=2,
|
192 |
+
num_classes=num_classes, input_channels=input_channels, act="relu", bn=True,
|
193 |
+
lin_ftrs_head=lin_ftrs_head, ps_head=ps_head, bn_final_head=bn_final_head, bn_head=bn_head,
|
194 |
+
act_head=act_head, concat_pooling=concat_pooling)
|
195 |
+
|
196 |
+
|
197 |
+
def schirrmeister(num_classes=2, input_channels=8, lin_ftrs_head=None, ps_head=0.5, bn_final_head=False, bn_head=True,
|
198 |
+
act_head="relu", concat_pooling=True):
|
199 |
+
return BasicConv1d(filters=[25, 50, 100, 200], kernel_size=10, stride=3, pool=3, pool_stride=1,
|
200 |
+
num_classes=num_classes, input_channels=input_channels, act="relu", bn=True, headless=False,
|
201 |
+
split_first_layer=True, drop_p=0.5, lin_ftrs_head=lin_ftrs_head, ps_head=ps_head,
|
202 |
+
bn_final_head=bn_final_head, bn_head=bn_head, act_head=act_head, concat_pooling=concat_pooling)
|
203 |
+
|
204 |
+
|
205 |
+
def sen(filters=None, num_classes=2, input_channels=8, squeeze_excite_reduction=16, drop_p=0., lin_ftrs_head=None,
|
206 |
+
ps_head=0.5, bn_final_head=False, bn_head=True, act_head="relu", concat_pooling=True):
|
207 |
+
if filters is None:
|
208 |
+
filters = [128] * 5
|
209 |
+
return BasicConv1d(filters=filters, kernel_size=3, stride=2, pool=0, pool_stride=0, input_channels=input_channels,
|
210 |
+
act="relu", bn=True, num_classes=num_classes, squeeze_excite_reduction=squeeze_excite_reduction,
|
211 |
+
drop_p=drop_p, lin_ftrs_head=lin_ftrs_head, ps_head=ps_head, bn_final_head=bn_final_head,
|
212 |
+
bn_head=bn_head, act_head=act_head, concat_pooling=concat_pooling)
|
213 |
+
|
214 |
+
|
215 |
+
def basic1d(filters=None, kernel_size=3, stride=2, dilation=1, pool=0, pool_stride=1, squeeze_excite_reduction=0,
|
216 |
+
num_classes=2, input_channels=8, act="relu", bn=True, headless=False, drop_p=0., lin_ftrs_head=None,
|
217 |
+
ps_head=0.5, bn_final_head=False, bn_head=True, act_head="relu", concat_pooling=True):
|
218 |
+
if filters is None:
|
219 |
+
filters = [128] * 5
|
220 |
+
return BasicConv1d(filters=filters, kernel_size=kernel_size, stride=stride, dilation=dilation, pool=pool,
|
221 |
+
pool_stride=pool_stride, squeeze_excite_reduction=squeeze_excite_reduction,
|
222 |
+
num_classes=num_classes, input_channels=input_channels, act=act, bn=bn, headless=headless,
|
223 |
+
drop_p=drop_p, lin_ftrs_head=lin_ftrs_head, ps_head=ps_head, bn_final_head=bn_final_head,
|
224 |
+
bn_head=bn_head, act_head=act_head, concat_pooling=concat_pooling)
|
models/fastaiModel.py
ADDED
@@ -0,0 +1,491 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastai.basic_data import *
|
2 |
+
from fastai.basic_train import *
|
3 |
+
from fastai.train import *
|
4 |
+
from fastai.torch_core import *
|
5 |
+
from fastai.callbacks.tracker import SaveModelCallback
|
6 |
+
from pathlib import Path
|
7 |
+
from functools import partial
|
8 |
+
import math
|
9 |
+
import torch
|
10 |
+
import numpy as np
|
11 |
+
import matplotlib
|
12 |
+
import matplotlib.pyplot as plt
|
13 |
+
from fastai.callback import Callback
|
14 |
+
|
15 |
+
from models.base_model import ClassificationModel
|
16 |
+
from models.basicconv1d import weight_init, fcn_wang, fcn, schirrmeister, sen, basic1d
|
17 |
+
from models.inception1d import inception1d
|
18 |
+
from models.resnet1d import resnet1d18, resnet1d34, resnet1d50, resnet1d101, resnet1d152, resnet1d_wang, \
|
19 |
+
wrn1d_22
|
20 |
+
from models.rnn1d import RNN1d
|
21 |
+
from utilities.timeseries_utils import TimeseriesDatasetCrops, ToTensor, aggregate_predictions
|
22 |
+
from models.xresnet1d import xresnet1d18_deeper, xresnet1d34_deeper, xresnet1d50_deeper, xresnet1d18_deep, \
|
23 |
+
xresnet1d34_deep, xresnet1d50_deep, xresnet1d18, xresnet1d34, xresnet1d101, xresnet1d50, xresnet1d152
|
24 |
+
from utilities.utils import evaluate_experiment
|
25 |
+
|
26 |
+
|
27 |
+
class MetricFunc(Callback):
|
28 |
+
"""Obtains score using user-supplied function func (potentially ignoring targets with ignore_idx)"""
|
29 |
+
|
30 |
+
def __init__(self, func, name="MetricFunc", ignore_idx=None, one_hot_encode_target=True, argmax_pred=False,
|
31 |
+
softmax_pred=True, flatten_target=True, sigmoid_pred=False, metric_component=None):
|
32 |
+
super().__init__()
|
33 |
+
self.metric_complete = self.func(self.y_true, self.y_pred)
|
34 |
+
self.y_true = None
|
35 |
+
self.y_pred = None
|
36 |
+
self.func = func
|
37 |
+
self.ignore_idx = ignore_idx
|
38 |
+
self.one_hot_encode_target = one_hot_encode_target
|
39 |
+
self.argmax_pred = argmax_pred
|
40 |
+
self.softmax_pred = softmax_pred
|
41 |
+
self.flatten_target = flatten_target
|
42 |
+
self.sigmoid_pred = sigmoid_pred
|
43 |
+
self.metric_component = metric_component
|
44 |
+
self.name = name
|
45 |
+
|
46 |
+
def on_epoch_begin(self, **kwargs):
|
47 |
+
pass
|
48 |
+
|
49 |
+
def on_batch_end(self, last_output, last_target, **kwargs):
|
50 |
+
# flatten everything (to make it also work for annotation tasks)
|
51 |
+
y_pred_flat = last_output.view((-1, last_output.size()[-1]))
|
52 |
+
|
53 |
+
if self.flatten_target:
|
54 |
+
last_target.view(-1)
|
55 |
+
y_true_flat = last_target
|
56 |
+
|
57 |
+
# optionally take argmax of predictions
|
58 |
+
if self.argmax_pred is True:
|
59 |
+
y_pred_flat = y_pred_flat.argmax(dim=1)
|
60 |
+
elif self.softmax_pred is True:
|
61 |
+
y_pred_flat = F.softmax(y_pred_flat, dim=1)
|
62 |
+
elif self.sigmoid_pred is True:
|
63 |
+
y_pred_flat = torch.sigmoid(y_pred_flat)
|
64 |
+
|
65 |
+
# potentially remove ignore_idx entries
|
66 |
+
if self.ignore_idx is not None:
|
67 |
+
selected_indices = (y_true_flat != self.ignore_idx).nonzero().squeeze()
|
68 |
+
y_pred_flat = y_pred_flat[selected_indices]
|
69 |
+
y_true_flat = y_true_flat[selected_indices]
|
70 |
+
|
71 |
+
y_pred_flat = to_np(y_pred_flat)
|
72 |
+
y_true_flat = to_np(y_true_flat)
|
73 |
+
|
74 |
+
if self.one_hot_encode_target is True:
|
75 |
+
y_true_flat = np.one_hot_np(y_true_flat, last_output.size()[-1])
|
76 |
+
|
77 |
+
if self.y_pred is None:
|
78 |
+
self.y_pred = y_pred_flat
|
79 |
+
self.y_true = y_true_flat
|
80 |
+
else:
|
81 |
+
self.y_pred = np.concatenate([self.y_pred, y_pred_flat], axis=0)
|
82 |
+
self.y_true = np.concatenate([self.y_true, y_true_flat], axis=0)
|
83 |
+
|
84 |
+
def on_epoch_end(self, last_metrics, **kwargs):
|
85 |
+
# access full metric (possibly multiple components) via self.metric_complete
|
86 |
+
if self.metric_component is not None:
|
87 |
+
return add_metrics(last_metrics, self.metric_complete[self.metric_component])
|
88 |
+
else:
|
89 |
+
return add_metrics(last_metrics, self.metric_complete)
|
90 |
+
|
91 |
+
|
92 |
+
def fmax_metric(targs, preds):
|
93 |
+
return evaluate_experiment(targs, preds)["Fmax"]
|
94 |
+
|
95 |
+
|
96 |
+
def auc_metric(targs, preds):
|
97 |
+
return evaluate_experiment(targs, preds)["macro_auc"]
|
98 |
+
|
99 |
+
|
100 |
+
def mse_flat(preds, targs):
|
101 |
+
return torch.mean(torch.pow(preds.view(-1) - targs.view(-1), 2))
|
102 |
+
|
103 |
+
|
104 |
+
def nll_regression(preds, targs):
|
105 |
+
# preds: bs, 2
|
106 |
+
# targs: bs, 1
|
107 |
+
preds_mean = preds[:, 0]
|
108 |
+
# warning: output goes through exponential map to ensure positivity
|
109 |
+
preds_var = torch.clamp(torch.exp(preds[:, 1]), 1e-4, 1e10)
|
110 |
+
# print(to_np(preds_mean)[0],to_np(targs)[0,0],to_np(torch.sqrt(preds_var))[0])
|
111 |
+
return torch.mean(torch.log(2 * math.pi * preds_var) / 2) + torch.mean(
|
112 |
+
torch.pow(preds_mean - targs[:, 0], 2) / 2 / preds_var)
|
113 |
+
|
114 |
+
|
115 |
+
def nll_regression_init(m):
|
116 |
+
assert (isinstance(m, nn.Linear))
|
117 |
+
nn.init.normal_(m.weight, 0., 0.001)
|
118 |
+
nn.init.constant_(m.bias, 4)
|
119 |
+
|
120 |
+
|
121 |
+
def lr_find_plot(learner, path, filename="lr_find", n_skip=10, n_skip_end=2):
|
122 |
+
"""
|
123 |
+
saves lr_find plot as file (normally only jupyter output)
|
124 |
+
on the x-axis is lrs[-1]
|
125 |
+
"""
|
126 |
+
learner.lr_find()
|
127 |
+
|
128 |
+
backend_old = matplotlib.get_backend()
|
129 |
+
plt.switch_backend('agg')
|
130 |
+
plt.ylabel("loss")
|
131 |
+
plt.xlabel("learning rate (log scale)")
|
132 |
+
losses = [to_np(x) for x in learner.recorder.losses[n_skip:-(n_skip_end + 1)]]
|
133 |
+
# print(learner.recorder.val_losses)
|
134 |
+
# val_losses = [ to_np(x) for x in learner.recorder.val_losses[n_skip:-(n_skip_end+1)]]
|
135 |
+
|
136 |
+
plt.plot(learner.recorder.lrs[n_skip:-(n_skip_end + 1)], losses)
|
137 |
+
# plt.plot(learner.recorder.lrs[n_skip:-(n_skip_end+1)],val_losses )
|
138 |
+
|
139 |
+
plt.xscale('log')
|
140 |
+
plt.savefig(str(path / (filename + '.png')))
|
141 |
+
plt.switch_backend(backend_old)
|
142 |
+
|
143 |
+
|
144 |
+
def losses_plot(learner, path, filename="losses", last: int = None):
|
145 |
+
"""
|
146 |
+
saves lr_find plot as file (normally only jupyter output)
|
147 |
+
on the x-axis is lrs[-1]
|
148 |
+
"""
|
149 |
+
backend_old = matplotlib.get_backend()
|
150 |
+
plt.switch_backend('agg')
|
151 |
+
plt.ylabel("loss")
|
152 |
+
plt.xlabel("Batches processed")
|
153 |
+
|
154 |
+
last = ifnone(last, len(learner.recorder.nb_batches))
|
155 |
+
l_b = np.sum(learner.recorder.nb_batches[-last:])
|
156 |
+
iterations = range_of(learner.recorder.losses)[-l_b:]
|
157 |
+
plt.plot(iterations, learner.recorder.losses[-l_b:], label='Train')
|
158 |
+
val_iter = learner.recorder.nb_batches[-last:]
|
159 |
+
val_iter = np.cumsum(val_iter) + np.sum(learner.recorder.nb_batches[:-last])
|
160 |
+
plt.plot(val_iter, learner.recorder.val_losses[-last:], label='Validation')
|
161 |
+
plt.legend()
|
162 |
+
|
163 |
+
plt.savefig(str(path / (filename + '.png')))
|
164 |
+
plt.switch_backend(backend_old)
|
165 |
+
|
166 |
+
|
167 |
+
class FastaiModel(ClassificationModel):
|
168 |
+
def __init__(self, name, n_classes, freq, output_folder, input_shape, pretrained=False, input_size=2.5,
|
169 |
+
input_channels=12, chunkify_train=False, chunkify_valid=True, bs=128, ps_head=0.5, lin_ftrs_head=None,
|
170 |
+
wd=1e-2, epochs=50, lr=1e-2, kernel_size=5, loss="binary_cross_entropy", pretrained_folder=None,
|
171 |
+
n_classes_pretrained=None, gradual_unfreezing=True, discriminative_lrs=True, epochs_finetuning=30,
|
172 |
+
early_stopping=None, aggregate_fn="max", concat_train_val=False):
|
173 |
+
super().__init__()
|
174 |
+
|
175 |
+
if lin_ftrs_head is None:
|
176 |
+
lin_ftrs_head = [128]
|
177 |
+
self.name = name
|
178 |
+
self.num_classes = n_classes if loss != "nll_regression" else 2
|
179 |
+
self.target_fs = freq
|
180 |
+
self.output_folder = Path(output_folder)
|
181 |
+
|
182 |
+
self.input_size = int(input_size * self.target_fs)
|
183 |
+
self.input_channels = input_channels
|
184 |
+
|
185 |
+
self.chunkify_train = chunkify_train
|
186 |
+
self.chunkify_valid = chunkify_valid
|
187 |
+
|
188 |
+
self.chunk_length_train = 2 * self.input_size # target_fs*6
|
189 |
+
self.chunk_length_valid = self.input_size
|
190 |
+
|
191 |
+
self.min_chunk_length = self.input_size # chunk_length
|
192 |
+
|
193 |
+
self.stride_length_train = self.input_size # chunk_length_train//8
|
194 |
+
self.stride_length_valid = self.input_size // 2 # chunk_length_valid
|
195 |
+
|
196 |
+
self.copies_valid = 0 # >0 should only be used with chunkify_valid=False
|
197 |
+
|
198 |
+
self.bs = bs
|
199 |
+
self.ps_head = ps_head
|
200 |
+
self.lin_ftrs_head = lin_ftrs_head
|
201 |
+
self.wd = wd
|
202 |
+
self.epochs = epochs
|
203 |
+
self.lr = lr
|
204 |
+
self.kernel_size = kernel_size
|
205 |
+
self.loss = loss
|
206 |
+
self.input_shape = input_shape
|
207 |
+
|
208 |
+
if pretrained:
|
209 |
+
if pretrained_folder is None:
|
210 |
+
pretrained_folder = Path('../output/exp0/models/' + name.split("_pretrained")[0] + '/')
|
211 |
+
# pretrained_folder = Path('/output/exp0/models/'+name.split("_pretrained")[0]+'/')
|
212 |
+
|
213 |
+
if n_classes_pretrained is None:
|
214 |
+
n_classes_pretrained = 71
|
215 |
+
|
216 |
+
self.pretrained_folder = None if pretrained_folder is None else Path(pretrained_folder)
|
217 |
+
self.n_classes_pretrained = n_classes_pretrained
|
218 |
+
self.discriminative_lrs = discriminative_lrs
|
219 |
+
self.gradual_unfreezing = gradual_unfreezing
|
220 |
+
self.epochs_finetuning = epochs_finetuning
|
221 |
+
|
222 |
+
self.early_stopping = early_stopping
|
223 |
+
self.aggregate_fn = aggregate_fn
|
224 |
+
self.concat_train_val = concat_train_val
|
225 |
+
|
226 |
+
def fit(self, X_train, y_train, X_val, y_val):
|
227 |
+
# convert everything to float32
|
228 |
+
X_train = [l.astype(np.float32) for l in X_train]
|
229 |
+
X_val = [l.astype(np.float32) for l in X_val]
|
230 |
+
y_train = [l.astype(np.float32) for l in y_train]
|
231 |
+
y_val = [l.astype(np.float32) for l in y_val]
|
232 |
+
|
233 |
+
if self.concat_train_val:
|
234 |
+
X_train += X_val
|
235 |
+
y_train += y_val
|
236 |
+
|
237 |
+
if self.pretrained_folder is None: # from scratch
|
238 |
+
print("Training from scratch...")
|
239 |
+
learn = self._get_learner(X_train, y_train, X_val, y_val)
|
240 |
+
|
241 |
+
# if(self.discriminative_lrs):
|
242 |
+
# layer_groups=learn.model.get_layer_groups()
|
243 |
+
# learn.split(layer_groups)
|
244 |
+
learn.model.apply(weight_init)
|
245 |
+
|
246 |
+
# initialization for regression output
|
247 |
+
if self.loss == "nll_regression" or self.loss == "mse":
|
248 |
+
output_layer_new = learn.model.get_output_layer()
|
249 |
+
output_layer_new.apply(nll_regression_init)
|
250 |
+
learn.model.set_output_layer(output_layer_new)
|
251 |
+
|
252 |
+
lr_find_plot(learn, self.output_folder)
|
253 |
+
learn.fit_one_cycle(self.epochs, self.lr) # slice(self.lr) if self.discriminative_lrs else self.lr)
|
254 |
+
losses_plot(learn, self.output_folder)
|
255 |
+
else: # finetuning
|
256 |
+
print("Finetuning...")
|
257 |
+
# create learner
|
258 |
+
learn = self._get_learner(X_train, y_train, X_val, y_val, self.n_classes_pretrained)
|
259 |
+
|
260 |
+
# load pretrained model
|
261 |
+
learn.path = self.pretrained_folder
|
262 |
+
learn.load(self.pretrained_folder.stem)
|
263 |
+
learn.path = self.output_folder
|
264 |
+
|
265 |
+
# exchange top layer
|
266 |
+
output_layer = learn.model.get_output_layer()
|
267 |
+
output_layer_new = nn.Linear(output_layer.in_features, self.num_classes).cuda()
|
268 |
+
apply_init(output_layer_new, nn.init.kaiming_normal_)
|
269 |
+
learn.model.set_output_layer(output_layer_new)
|
270 |
+
|
271 |
+
# layer groups
|
272 |
+
if self.discriminative_lrs:
|
273 |
+
layer_groups = learn.model.get_layer_groups()
|
274 |
+
learn.split(layer_groups)
|
275 |
+
|
276 |
+
learn.train_bn = True # make sure if bn mode is train
|
277 |
+
|
278 |
+
# train
|
279 |
+
lr = self.lr
|
280 |
+
if self.gradual_unfreezing:
|
281 |
+
assert (self.discriminative_lrs is True)
|
282 |
+
learn.freeze()
|
283 |
+
lr_find_plot(learn, self.output_folder, "lr_find0")
|
284 |
+
learn.fit_one_cycle(self.epochs_finetuning, lr)
|
285 |
+
losses_plot(learn, self.output_folder, "losses0")
|
286 |
+
# for n in [0]:#range(len(layer_groups)): learn.freeze_to(-n-1) lr_find_plot(learn,
|
287 |
+
# self.output_folder,"lr_find"+str(n)) learn.fit_one_cycle(self.epochs_gradual_unfreezing,slice(lr))
|
288 |
+
# losses_plot(learn, self.output_folder,"losses"+str(n)) if(n==0):#reduce lr after first step lr/=10.
|
289 |
+
# if(n>0 and (self.name.startswith("fastai_lstm") or self.name.startswith("fastai_gru"))):#reduce lr
|
290 |
+
# further for RNNs lr/=10
|
291 |
+
|
292 |
+
learn.unfreeze()
|
293 |
+
lr_find_plot(learn, self.output_folder, "lr_find" + str(len(layer_groups)))
|
294 |
+
learn.fit_one_cycle(self.epochs_finetuning, slice(lr / 1000, lr / 10))
|
295 |
+
losses_plot(learn, self.output_folder, "losses" + str(len(layer_groups)))
|
296 |
+
|
297 |
+
learn.save(self.name) # even for early stopping the best model will have been loaded again
|
298 |
+
|
299 |
+
def predict(self, X):
|
300 |
+
X = [l.astype(np.float32) for l in X]
|
301 |
+
y_dummy = [np.ones(self.num_classes, dtype=np.float32) for _ in range(len(X))]
|
302 |
+
|
303 |
+
learn = self._get_learner(X, y_dummy, X, y_dummy)
|
304 |
+
learn.load(self.name)
|
305 |
+
|
306 |
+
preds, targs = learn.get_preds()
|
307 |
+
preds = to_np(preds)
|
308 |
+
|
309 |
+
idmap = learn.data.valid_ds.get_id_mapping()
|
310 |
+
|
311 |
+
return aggregate_predictions(preds, idmap=idmap,
|
312 |
+
aggregate_fn=np.mean if self.aggregate_fn == "mean" else np.amax)
|
313 |
+
|
314 |
+
def _get_learner(self, X_train, y_train, X_val, y_val, num_classes=None):
|
315 |
+
df_train = pd.DataFrame({"data": range(len(X_train)), "label": y_train})
|
316 |
+
df_valid = pd.DataFrame({"data": range(len(X_val)), "label": y_val})
|
317 |
+
|
318 |
+
tfms_ptb_xl = [ToTensor()]
|
319 |
+
|
320 |
+
ds_train = TimeseriesDatasetCrops(df_train, self.input_size, num_classes=self.num_classes,
|
321 |
+
chunk_length=self.chunk_length_train if self.chunkify_train else 0,
|
322 |
+
min_chunk_length=self.min_chunk_length,
|
323 |
+
stride=self.stride_length_train, transforms=tfms_ptb_xl,
|
324 |
+
annotation=False, col_lbl="label", npy_data=X_train)
|
325 |
+
ds_valid = TimeseriesDatasetCrops(df_valid, self.input_size, num_classes=self.num_classes,
|
326 |
+
chunk_length=self.chunk_length_valid if self.chunkify_valid else 0,
|
327 |
+
min_chunk_length=self.min_chunk_length,
|
328 |
+
stride=self.stride_length_valid, transforms=tfms_ptb_xl,
|
329 |
+
annotation=False, col_lbl="label", npy_data=X_val)
|
330 |
+
|
331 |
+
db = DataBunch.create(ds_train, ds_valid, bs=self.bs)
|
332 |
+
|
333 |
+
if self.loss == "binary_cross_entropy":
|
334 |
+
loss = F.binary_cross_entropy_with_logits
|
335 |
+
elif self.loss == "cross_entropy":
|
336 |
+
loss = F.cross_entropy
|
337 |
+
elif self.loss == "mse":
|
338 |
+
loss = mse_flat
|
339 |
+
elif self.loss == "nll_regression":
|
340 |
+
loss = nll_regression
|
341 |
+
else:
|
342 |
+
print("loss not found")
|
343 |
+
assert (True)
|
344 |
+
|
345 |
+
self.input_channels = self.input_shape[-1]
|
346 |
+
metrics = []
|
347 |
+
|
348 |
+
print("model:", self.name)
|
349 |
+
# note: all models of a particular kind share the same prefix but potentially a different
|
350 |
+
# postfix such as _input256
|
351 |
+
num_classes = self.num_classes if num_classes is None else num_classes
|
352 |
+
# resnet resnet1d18,resnet1d34,resnet1d50,resnet1d101,resnet1d152,resnet1d_wang,resnet1d,wrn1d_22
|
353 |
+
if self.name.startswith("fastai_resnet1d18"):
|
354 |
+
model = resnet1d18(num_classes=num_classes, input_channels=self.input_channels, inplanes=128,
|
355 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head,
|
356 |
+
lin_ftrs_head=self.lin_ftrs_head)
|
357 |
+
elif self.name.startswith("fastai_resnet1d34"):
|
358 |
+
model = resnet1d34(num_classes=num_classes, input_channels=self.input_channels, inplanes=128,
|
359 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head,
|
360 |
+
lin_ftrs_head=self.lin_ftrs_head)
|
361 |
+
elif self.name.startswith("fastai_resnet1d50"):
|
362 |
+
model = resnet1d50(num_classes=num_classes, input_channels=self.input_channels, inplanes=128,
|
363 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head,
|
364 |
+
lin_ftrs_head=self.lin_ftrs_head)
|
365 |
+
elif self.name.startswith("fastai_resnet1d101"):
|
366 |
+
model = resnet1d101(num_classes=num_classes, input_channels=self.input_channels, inplanes=128,
|
367 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head,
|
368 |
+
lin_ftrs_head=self.lin_ftrs_head)
|
369 |
+
elif self.name.startswith("fastai_resnet1d152"):
|
370 |
+
model = resnet1d152(num_classes=num_classes, input_channels=self.input_channels, inplanes=128,
|
371 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head,
|
372 |
+
lin_ftrs_head=self.lin_ftrs_head)
|
373 |
+
elif self.name.startswith("fastai_resnet1d_wang"):
|
374 |
+
model = resnet1d_wang(num_classes=num_classes, input_channels=self.input_channels,
|
375 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head,
|
376 |
+
lin_ftrs_head=self.lin_ftrs_head)
|
377 |
+
elif self.name.startswith("fastai_wrn1d_22"):
|
378 |
+
model = wrn1d_22(num_classes=num_classes, input_channels=self.input_channels,
|
379 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head,
|
380 |
+
lin_ftrs_head=self.lin_ftrs_head)
|
381 |
+
|
382 |
+
# xresnet ... (order important for string capture)
|
383 |
+
elif self.name.startswith("fastai_xresnet1d18_deeper"):
|
384 |
+
model = xresnet1d18_deeper(num_classes=num_classes, input_channels=self.input_channels,
|
385 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head,
|
386 |
+
lin_ftrs_head=self.lin_ftrs_head)
|
387 |
+
elif self.name.startswith("fastai_xresnet1d34_deeper"):
|
388 |
+
model = xresnet1d34_deeper(num_classes=num_classes, input_channels=self.input_channels,
|
389 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head,
|
390 |
+
lin_ftrs_head=self.lin_ftrs_head)
|
391 |
+
elif self.name.startswith("fastai_xresnet1d50_deeper"):
|
392 |
+
model = xresnet1d50_deeper(num_classes=num_classes, input_channels=self.input_channels,
|
393 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head,
|
394 |
+
lin_ftrs_head=self.lin_ftrs_head)
|
395 |
+
elif self.name.startswith("fastai_xresnet1d18_deep"):
|
396 |
+
model = xresnet1d18_deep(num_classes=num_classes, input_channels=self.input_channels,
|
397 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head,
|
398 |
+
lin_ftrs_head=self.lin_ftrs_head)
|
399 |
+
elif self.name.startswith("fastai_xresnet1d34_deep"):
|
400 |
+
model = xresnet1d34_deep(num_classes=num_classes, input_channels=self.input_channels,
|
401 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head,
|
402 |
+
lin_ftrs_head=self.lin_ftrs_head)
|
403 |
+
elif self.name.startswith("fastai_xresnet1d50_deep"):
|
404 |
+
model = xresnet1d50_deep(num_classes=num_classes, input_channels=self.input_channels,
|
405 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head,
|
406 |
+
lin_ftrs_head=self.lin_ftrs_head)
|
407 |
+
elif self.name.startswith("fastai_xresnet1d18"):
|
408 |
+
model = xresnet1d18(num_classes=num_classes, input_channels=self.input_channels,
|
409 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head, lin_ftrs_head=self.lin_ftrs_head)
|
410 |
+
elif self.name.startswith("fastai_xresnet1d34"):
|
411 |
+
model = xresnet1d34(num_classes=num_classes, input_channels=self.input_channels,
|
412 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head, lin_ftrs_head=self.lin_ftrs_head)
|
413 |
+
elif self.name.startswith("fastai_xresnet1d50"):
|
414 |
+
model = xresnet1d50(num_classes=num_classes, input_channels=self.input_channels,
|
415 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head, lin_ftrs_head=self.lin_ftrs_head)
|
416 |
+
elif self.name.startswith("fastai_xresnet1d101"):
|
417 |
+
model = xresnet1d101(num_classes=num_classes, input_channels=self.input_channels,
|
418 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head, lin_ftrs_head=self.lin_ftrs_head)
|
419 |
+
elif self.name.startswith("fastai_xresnet1d152"):
|
420 |
+
model = xresnet1d152(num_classes=num_classes, input_channels=self.input_channels,
|
421 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head, lin_ftrs_head=self.lin_ftrs_head)
|
422 |
+
|
423 |
+
# inception passing the default kernel size of 5 leads to a max kernel size of 40-1 in the inception model as
|
424 |
+
# proposed in the original paper
|
425 |
+
elif self.name == "fastai_inception1d_no_residual": # note: order important for string capture
|
426 |
+
model = inception1d(num_classes=num_classes, input_channels=self.input_channels,
|
427 |
+
use_residual=False, ps_head=self.ps_head, lin_ftrs_head=self.lin_ftrs_head,
|
428 |
+
kernel_size=8 * self.kernel_size)
|
429 |
+
elif self.name.startswith("fastai_inception1d"):
|
430 |
+
model = inception1d(num_classes=num_classes, input_channels=self.input_channels,
|
431 |
+
use_residual=True, ps_head=self.ps_head, lin_ftrs_head=self.lin_ftrs_head,
|
432 |
+
kernel_size=8 * self.kernel_size)
|
433 |
+
|
434 |
+
|
435 |
+
# BasicConv1d fcn,fcn_wang,schirrmeister,sen,basic1d
|
436 |
+
elif self.name.startswith("fastai_fcn_wang"): # note: order important for string capture
|
437 |
+
model = fcn_wang(num_classes=num_classes, input_channels=self.input_channels,
|
438 |
+
ps_head=self.ps_head, lin_ftrs_head=self.lin_ftrs_head)
|
439 |
+
elif self.name.startswith("fastai_fcn"):
|
440 |
+
model = fcn(num_classes=num_classes, input_channels=self.input_channels)
|
441 |
+
elif self.name.startswith("fastai_schirrmeister"):
|
442 |
+
model = schirrmeister(num_classes=num_classes, input_channels=self.input_channels,
|
443 |
+
ps_head=self.ps_head, lin_ftrs_head=self.lin_ftrs_head)
|
444 |
+
elif self.name.startswith("fastai_sen"):
|
445 |
+
model = sen(num_classes=num_classes, input_channels=self.input_channels, ps_head=self.ps_head,
|
446 |
+
lin_ftrs_head=self.lin_ftrs_head)
|
447 |
+
elif self.name.startswith("fastai_basic1d"):
|
448 |
+
model = basic1d(num_classes=num_classes, input_channels=self.input_channels,
|
449 |
+
kernel_size=self.kernel_size, ps_head=self.ps_head,
|
450 |
+
lin_ftrs_head=self.lin_ftrs_head)
|
451 |
+
# RNN
|
452 |
+
elif self.name.startswith("fastai_lstm_bidir"):
|
453 |
+
model = RNN1d(input_channels=self.input_channels, num_classes=num_classes, lstm=True,
|
454 |
+
bidirectional=True, ps_head=self.ps_head, lin_ftrs_head=self.lin_ftrs_head)
|
455 |
+
elif self.name.startswith("fastai_gru_bidir"):
|
456 |
+
model = RNN1d(input_channels=self.input_channels, num_classes=num_classes, lstm=False,
|
457 |
+
bidirectional=True, ps_head=self.ps_head, lin_ftrs_head=self.lin_ftrs_head)
|
458 |
+
elif self.name.startswith("fastai_lstm"):
|
459 |
+
model = RNN1d(input_channels=self.input_channels, num_classes=num_classes, lstm=True,
|
460 |
+
bidirectional=False, ps_head=self.ps_head, lin_ftrs_head=self.lin_ftrs_head)
|
461 |
+
elif self.name.startswith("fastai_gru"):
|
462 |
+
model = RNN1d(input_channels=self.input_channels, num_classes=num_classes, lstm=False,
|
463 |
+
bidirectional=False, ps_head=self.ps_head, lin_ftrs_head=self.lin_ftrs_head)
|
464 |
+
else:
|
465 |
+
print("Model not found.")
|
466 |
+
assert True
|
467 |
+
|
468 |
+
learn = Learner(db, model, loss_func=loss, metrics=metrics, wd=self.wd, path=self.output_folder)
|
469 |
+
|
470 |
+
if self.name.startswith("fastai_lstm") or self.name.startswith("fastai_gru"):
|
471 |
+
learn.callback_fns.append(partial(GradientClipping, clip=0.25))
|
472 |
+
|
473 |
+
if self.early_stopping is not None:
|
474 |
+
# supported options: valid_loss, macro_auc, fmax
|
475 |
+
if self.early_stopping == "macro_auc" and self.loss != "mse" and self.loss != "nll_regression":
|
476 |
+
metric = MetricFunc(auc_metric, self.early_stopping,
|
477 |
+
one_hot_encode_target=False, argmax_pred=False, softmax_pred=False,
|
478 |
+
sigmoid_pred=True, flatten_target=False)
|
479 |
+
learn.metrics.append(metric)
|
480 |
+
learn.callback_fns.append(
|
481 |
+
partial(SaveModelCallback, monitor=self.early_stopping, every='improvement', name=self.name))
|
482 |
+
elif self.early_stopping == "fmax" and self.loss != "mse" and self.loss != "nll_regression":
|
483 |
+
metric = MetricFunc(fmax_metric, self.early_stopping,
|
484 |
+
one_hot_encode_target=False, argmax_pred=False, softmax_pred=False,
|
485 |
+
sigmoid_pred=True, flatten_target=False)
|
486 |
+
learn.metrics.append(metric)
|
487 |
+
learn.callback_fns.append(partial(SaveModelCallback, monitor=self.early_stopping, every='improvement', name=self.name))
|
488 |
+
elif self.early_stopping == "valid_loss":
|
489 |
+
learn.callback_fns.append(partial(SaveModelCallback, monitor=self.early_stopping, every='improvement', name=self.name))
|
490 |
+
|
491 |
+
return learn
|
models/inception1d.py
ADDED
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from fastai.core import *
|
4 |
+
|
5 |
+
# Inception time inspired by https://github.com/hfawaz/InceptionTime/blob/master/classifiers/inception.py and https://github.com/tcapelle/TimeSeries_fastai/blob/master/inception.py
|
6 |
+
from models.basicconv1d import create_head1d
|
7 |
+
|
8 |
+
|
9 |
+
def conv(in_planes, out_planes, kernel_size=3, stride=1):
|
10 |
+
"convolution with padding"
|
11 |
+
return nn.Conv1d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
|
12 |
+
padding=(kernel_size - 1) // 2, bias=False)
|
13 |
+
|
14 |
+
|
15 |
+
def noop(x): return x
|
16 |
+
|
17 |
+
|
18 |
+
class InceptionBlock1d(nn.Module):
|
19 |
+
def __init__(self, ni, nb_filters, kss, stride=1, act='linear', bottleneck_size=32):
|
20 |
+
super().__init__()
|
21 |
+
self.bottleneck = conv(ni, bottleneck_size, 1, stride) if (bottleneck_size > 0) else noop
|
22 |
+
|
23 |
+
self.convs = nn.ModuleList(
|
24 |
+
[conv(bottleneck_size if (bottleneck_size > 0) else ni, nb_filters, ks) for ks in kss])
|
25 |
+
self.conv_bottle = nn.Sequential(nn.MaxPool1d(3, stride, padding=1), conv(ni, nb_filters, 1))
|
26 |
+
self.bn_relu = nn.Sequential(nn.BatchNorm1d((len(kss) + 1) * nb_filters), nn.ReLU())
|
27 |
+
|
28 |
+
def forward(self, x):
|
29 |
+
# print("block in",x.size())
|
30 |
+
bottled = self.bottleneck(x)
|
31 |
+
out = self.bn_relu(torch.cat([c(bottled) for c in self.convs] + [self.conv_bottle(x)], dim=1))
|
32 |
+
return out
|
33 |
+
|
34 |
+
|
35 |
+
class Shortcut1d(nn.Module):
|
36 |
+
def __init__(self, ni, nf):
|
37 |
+
super().__init__()
|
38 |
+
self.act_fn = nn.ReLU(True)
|
39 |
+
self.conv = conv(ni, nf, 1)
|
40 |
+
self.bn = nn.BatchNorm1d(nf)
|
41 |
+
|
42 |
+
def forward(self, inp, out):
|
43 |
+
# print("sk",out.size(), inp.size(), self.conv(inp).size(), self.bn(self.conv(inp)).size)
|
44 |
+
# input()
|
45 |
+
return self.act_fn(out + self.bn(self.conv(inp)))
|
46 |
+
|
47 |
+
|
48 |
+
class InceptionBackbone(nn.Module):
|
49 |
+
def __init__(self, input_channels, kss, depth, bottleneck_size, nb_filters, use_residual):
|
50 |
+
super().__init__()
|
51 |
+
|
52 |
+
self.depth = depth
|
53 |
+
assert ((depth % 3) == 0)
|
54 |
+
self.use_residual = use_residual
|
55 |
+
|
56 |
+
n_ks = len(kss) + 1
|
57 |
+
self.im = nn.ModuleList([InceptionBlock1d(input_channels if d == 0 else n_ks * nb_filters,
|
58 |
+
nb_filters=nb_filters, kss=kss,
|
59 |
+
bottleneck_size=bottleneck_size) for d in range(depth)])
|
60 |
+
self.sk = nn.ModuleList(
|
61 |
+
[Shortcut1d(input_channels if d == 0 else n_ks * nb_filters, n_ks * nb_filters) for d in
|
62 |
+
range(depth // 3)])
|
63 |
+
|
64 |
+
def forward(self, x):
|
65 |
+
|
66 |
+
input_res = x
|
67 |
+
for d in range(self.depth):
|
68 |
+
x = self.im[d](x)
|
69 |
+
if self.use_residual and d % 3 == 2:
|
70 |
+
x = (self.sk[d // 3])(input_res, x)
|
71 |
+
input_res = x.clone()
|
72 |
+
return x
|
73 |
+
|
74 |
+
|
75 |
+
class Inception1d(nn.Module):
|
76 |
+
"""inception time architecture"""
|
77 |
+
|
78 |
+
def __init__(self, num_classes=2, input_channels=8, kernel_size=40, depth=6, bottleneck_size=32, nb_filters=32,
|
79 |
+
use_residual=True, lin_ftrs_head=None, ps_head=0.5, bn_final_head=False, bn_head=True, act_head="relu",
|
80 |
+
concat_pooling=True):
|
81 |
+
super().__init__()
|
82 |
+
assert (kernel_size >= 40)
|
83 |
+
kernel_size = [k - 1 if k % 2 == 0 else k for k in
|
84 |
+
[kernel_size, kernel_size // 2, kernel_size // 4]] # was 39,19,9
|
85 |
+
|
86 |
+
layers = [InceptionBackbone(input_channels=input_channels, kss=kernel_size, depth=depth,
|
87 |
+
bottleneck_size=bottleneck_size, nb_filters=nb_filters,
|
88 |
+
use_residual=use_residual)]
|
89 |
+
|
90 |
+
n_ks = len(kernel_size) + 1
|
91 |
+
# head
|
92 |
+
head = create_head1d(n_ks * nb_filters, nc=num_classes, lin_ftrs=lin_ftrs_head, ps=ps_head,
|
93 |
+
bn_final=bn_final_head, bn=bn_head, act=act_head,
|
94 |
+
concat_pooling=concat_pooling)
|
95 |
+
layers.append(head)
|
96 |
+
# layers.append(AdaptiveConcatPool1d())
|
97 |
+
# layers.append(Flatten())
|
98 |
+
# layers.append(nn.Linear(2*n_ks*nb_filters, num_classes))
|
99 |
+
self.layers = nn.Sequential(*layers)
|
100 |
+
|
101 |
+
def forward(self, x):
|
102 |
+
return self.layers(x)
|
103 |
+
|
104 |
+
def get_layer_groups(self):
|
105 |
+
depth = self.layers[0].depth
|
106 |
+
if depth > 3:
|
107 |
+
return (self.layers[0].im[3:], self.layers[0].sk[1:]), self.layers[-1]
|
108 |
+
else:
|
109 |
+
return self.layers[-1]
|
110 |
+
|
111 |
+
def get_output_layer(self):
|
112 |
+
return self.layers[-1][-1]
|
113 |
+
|
114 |
+
def set_output_layer(self, x):
|
115 |
+
self.layers[-1][-1] = x
|
116 |
+
|
117 |
+
|
118 |
+
def inception1d(**kwargs):
|
119 |
+
"""
|
120 |
+
Constructs an Inception model
|
121 |
+
"""
|
122 |
+
return Inception1d(**kwargs)
|
models/resnet1d.py
ADDED
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
import torch.nn.functional as F
|
3 |
+
|
4 |
+
# Standard resnet
|
5 |
+
from models.basicconv1d import create_head1d
|
6 |
+
|
7 |
+
|
8 |
+
def conv(in_planes, out_planes, stride=1, kernel_size=3):
|
9 |
+
"""convolution with padding"""
|
10 |
+
return nn.Conv1d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
|
11 |
+
padding=(kernel_size - 1) // 2, bias=False)
|
12 |
+
|
13 |
+
|
14 |
+
class BasicBlock1d(nn.Module):
|
15 |
+
expansion = 1
|
16 |
+
|
17 |
+
def __init__(self, inplanes, planes, stride=1, kernel_size=None, down_sample=None):
|
18 |
+
if kernel_size is None:
|
19 |
+
kernel_size = [3, 3]
|
20 |
+
super().__init__()
|
21 |
+
|
22 |
+
if isinstance(kernel_size, int): kernel_size = [kernel_size, kernel_size // 2 + 1]
|
23 |
+
|
24 |
+
self.conv1 = conv(inplanes, planes, stride=stride, kernel_size=kernel_size[0])
|
25 |
+
self.bn1 = nn.BatchNorm1d(planes)
|
26 |
+
self.relu = nn.ReLU(inplace=True)
|
27 |
+
self.conv2 = conv(planes, planes, kernel_size=kernel_size[1])
|
28 |
+
self.bn2 = nn.BatchNorm1d(planes)
|
29 |
+
self.down_sample = down_sample
|
30 |
+
self.stride = stride
|
31 |
+
|
32 |
+
def forward(self, x):
|
33 |
+
residual = x
|
34 |
+
|
35 |
+
out = self.conv1(x)
|
36 |
+
out = self.bn1(out)
|
37 |
+
out = self.relu(out)
|
38 |
+
|
39 |
+
out = self.conv2(out)
|
40 |
+
out = self.bn2(out)
|
41 |
+
|
42 |
+
if self.down_sample is not None:
|
43 |
+
residual = self.down_sample(x)
|
44 |
+
|
45 |
+
out += residual
|
46 |
+
out = self.relu(out)
|
47 |
+
|
48 |
+
return out
|
49 |
+
|
50 |
+
|
51 |
+
class Bottleneck1d(nn.Module):
|
52 |
+
expansion = 4
|
53 |
+
|
54 |
+
def __init__(self, inplanes, planes, stride=1, kernel_size=3, down_sample=None):
|
55 |
+
super().__init__()
|
56 |
+
|
57 |
+
self.conv1 = nn.Conv1d(inplanes, planes, kernel_size=1, bias=False)
|
58 |
+
self.bn1 = nn.BatchNorm1d(planes)
|
59 |
+
self.conv2 = nn.Conv1d(planes, planes, kernel_size=kernel_size, stride=stride,
|
60 |
+
padding=(kernel_size - 1) // 2, bias=False)
|
61 |
+
self.bn2 = nn.BatchNorm1d(planes)
|
62 |
+
self.conv3 = nn.Conv1d(planes, planes * 4, kernel_size=1, bias=False)
|
63 |
+
self.bn3 = nn.BatchNorm1d(planes * 4)
|
64 |
+
self.relu = nn.ReLU(inplace=True)
|
65 |
+
self.down_sample = down_sample
|
66 |
+
self.stride = stride
|
67 |
+
|
68 |
+
def forward(self, x):
|
69 |
+
residual = x
|
70 |
+
|
71 |
+
out = self.conv1(x)
|
72 |
+
out = self.bn1(out)
|
73 |
+
out = self.relu(out)
|
74 |
+
|
75 |
+
out = self.conv2(out)
|
76 |
+
out = self.bn2(out)
|
77 |
+
out = self.relu(out)
|
78 |
+
|
79 |
+
out = self.conv3(out)
|
80 |
+
out = self.bn3(out)
|
81 |
+
|
82 |
+
if self.down_sample is not None:
|
83 |
+
residual = self.down_sample(x)
|
84 |
+
|
85 |
+
out += residual
|
86 |
+
out = self.relu(out)
|
87 |
+
|
88 |
+
return out
|
89 |
+
|
90 |
+
|
91 |
+
class ResNet1d(nn.Sequential):
|
92 |
+
"""1d adaptation of the torchvision resnet"""
|
93 |
+
|
94 |
+
def __init__(self, block, layers, kernel_size=3, num_classes=2, input_channels=3, inplanes=64, fix_feature_dim=True,
|
95 |
+
kernel_size_stem=None, stride_stem=2, pooling_stem=True, stride=2, lin_ftrs_head=None, ps_head=0.5,
|
96 |
+
bn_final_head=False, bn_head=True, act_head="relu", concat_pooling=True):
|
97 |
+
self.inplanes = inplanes
|
98 |
+
|
99 |
+
layers_tmp = []
|
100 |
+
|
101 |
+
if kernel_size_stem is None:
|
102 |
+
kernel_size_stem = kernel_size[0] if isinstance(kernel_size, list) else kernel_size
|
103 |
+
# stem
|
104 |
+
layers_tmp.append(nn.Conv1d(input_channels, inplanes, kernel_size=kernel_size_stem, stride=stride_stem,
|
105 |
+
padding=(kernel_size_stem - 1) // 2, bias=False))
|
106 |
+
layers_tmp.append(nn.BatchNorm1d(inplanes))
|
107 |
+
layers_tmp.append(nn.ReLU(inplace=True))
|
108 |
+
if pooling_stem is True:
|
109 |
+
layers_tmp.append(nn.MaxPool1d(kernel_size=3, stride=2, padding=1))
|
110 |
+
# backbone
|
111 |
+
for i, l in enumerate(layers):
|
112 |
+
if i == 0:
|
113 |
+
layers_tmp.append(self._make_layer(block, inplanes, layers[0], kernel_size=kernel_size))
|
114 |
+
else:
|
115 |
+
layers_tmp.append(
|
116 |
+
self._make_layer(block, inplanes if fix_feature_dim else (2 ** i) * inplanes, layers[i],
|
117 |
+
stride=stride, kernel_size=kernel_size))
|
118 |
+
|
119 |
+
# head
|
120 |
+
# layers_tmp.append(nn.AdaptiveAvgPool1d(1))
|
121 |
+
# layers_tmp.append(Flatten())
|
122 |
+
# layers_tmp.append(nn.Linear((inplanes if fix_feature_dim else (2**len(layers)*inplanes)) * block.expansion, num_classes))
|
123 |
+
|
124 |
+
head = create_head1d(
|
125 |
+
(inplanes if fix_feature_dim else (2 ** len(layers) * inplanes)) * block.expansion, nc=num_classes,
|
126 |
+
lin_ftrs=lin_ftrs_head, ps=ps_head, bn_final=bn_final_head, bn=bn_head, act=act_head,
|
127 |
+
concat_pooling=concat_pooling)
|
128 |
+
layers_tmp.append(head)
|
129 |
+
|
130 |
+
super().__init__()
|
131 |
+
|
132 |
+
def _make_layer(self, block, planes, blocks, stride=1, kernel_size=3):
|
133 |
+
down_sample = None
|
134 |
+
|
135 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
136 |
+
down_sample = nn.Sequential(
|
137 |
+
nn.Conv1d(self.inplanes, planes * block.expansion,
|
138 |
+
kernel_size=1, stride=stride, bias=False),
|
139 |
+
nn.BatchNorm1d(planes * block.expansion),
|
140 |
+
)
|
141 |
+
|
142 |
+
layers = [block(self.inplanes, planes, stride, kernel_size, down_sample)]
|
143 |
+
self.inplanes = planes * block.expansion
|
144 |
+
for i in range(1, blocks):
|
145 |
+
layers.append(block(self.inplanes, planes))
|
146 |
+
|
147 |
+
return nn.Sequential(*layers)
|
148 |
+
|
149 |
+
def get_layer_groups(self):
|
150 |
+
return self[6], self[-1]
|
151 |
+
|
152 |
+
def get_output_layer(self):
|
153 |
+
return self[-1][-1]
|
154 |
+
|
155 |
+
def set_output_layer(self, x):
|
156 |
+
self[-1][-1] = x
|
157 |
+
|
158 |
+
|
159 |
+
def resnet1d18(**kwargs):
|
160 |
+
"""
|
161 |
+
Constructs a ResNet-18 model.
|
162 |
+
"""
|
163 |
+
return ResNet1d(BasicBlock1d, [2, 2, 2, 2], **kwargs)
|
164 |
+
|
165 |
+
|
166 |
+
def resnet1d34(**kwargs):
|
167 |
+
"""
|
168 |
+
Constructs a ResNet-34 model.
|
169 |
+
"""
|
170 |
+
return ResNet1d(BasicBlock1d, [3, 4, 6, 3], **kwargs)
|
171 |
+
|
172 |
+
|
173 |
+
def resnet1d50(**kwargs):
|
174 |
+
"""
|
175 |
+
Constructs a ResNet-50 model.
|
176 |
+
"""
|
177 |
+
return ResNet1d(Bottleneck1d, [3, 4, 6, 3], **kwargs)
|
178 |
+
|
179 |
+
|
180 |
+
def resnet1d101(**kwargs):
|
181 |
+
"""
|
182 |
+
Constructs a ResNet-101 model.
|
183 |
+
"""
|
184 |
+
return ResNet1d(Bottleneck1d, [3, 4, 23, 3], **kwargs)
|
185 |
+
|
186 |
+
|
187 |
+
def resnet1d152(**kwargs):
|
188 |
+
"""
|
189 |
+
Constructs a ResNet-152 model.
|
190 |
+
"""
|
191 |
+
return ResNet1d(Bottleneck1d, [3, 8, 36, 3], **kwargs)
|
192 |
+
|
193 |
+
|
194 |
+
# original used kernel_size_stem = 8
|
195 |
+
def resnet1d_wang(**kwargs):
|
196 |
+
if not ("kernel_size" in kwargs.keys()):
|
197 |
+
kwargs["kernel_size"] = [5, 3]
|
198 |
+
if not ("kernel_size_stem" in kwargs.keys()):
|
199 |
+
kwargs["kernel_size_stem"] = 7
|
200 |
+
if not ("stride_stem" in kwargs.keys()):
|
201 |
+
kwargs["stride_stem"] = 1
|
202 |
+
if not ("pooling_stem" in kwargs.keys()):
|
203 |
+
kwargs["pooling_stem"] = False
|
204 |
+
if not ("inplanes" in kwargs.keys()):
|
205 |
+
kwargs["inplanes"] = 128
|
206 |
+
|
207 |
+
return ResNet1d(BasicBlock1d, [1, 1, 1], **kwargs)
|
208 |
+
|
209 |
+
|
210 |
+
def resnet1d(**kwargs):
|
211 |
+
"""
|
212 |
+
Constructs a custom ResNet model.
|
213 |
+
"""
|
214 |
+
return ResNet1d(BasicBlock1d, **kwargs)
|
215 |
+
|
216 |
+
|
217 |
+
# wide resnet adopted from fastai wrn
|
218 |
+
|
219 |
+
def noop(x): return x
|
220 |
+
|
221 |
+
|
222 |
+
def conv1d(ni: int, nf: int, ks: int = 3, stride: int = 1, padding: int = None, bias=False) -> nn.Conv1d:
|
223 |
+
"Create `nn.Conv1d` layer: `ni` inputs, `nf` outputs, `ks` kernel size. `padding` defaults to `k//2`."
|
224 |
+
if padding is None: padding = ks // 2
|
225 |
+
return nn.Conv1d(ni, nf, kernel_size=ks, stride=stride, padding=padding, bias=bias)
|
226 |
+
|
227 |
+
|
228 |
+
def _bn1d(ni, init_zero=False):
|
229 |
+
"Batchnorm layer with 0 initialization"
|
230 |
+
m = nn.BatchNorm1d(ni)
|
231 |
+
m.weight.data.fill_(0 if init_zero else 1)
|
232 |
+
m.bias.data.zero_()
|
233 |
+
return m
|
234 |
+
|
235 |
+
|
236 |
+
def bn_relu_conv1d(ni, nf, ks, stride, init_zero=False):
|
237 |
+
bn_initzero = _bn1d(ni, init_zero=init_zero)
|
238 |
+
return nn.Sequential(bn_initzero, nn.ReLU(inplace=True), conv1d(ni, nf, ks, stride))
|
239 |
+
|
240 |
+
|
241 |
+
class BasicBlock1dwrn(nn.Module):
|
242 |
+
def __init__(self, ni, nf, stride, drop_p=0.0, ks=3):
|
243 |
+
super().__init__()
|
244 |
+
if isinstance(ks, int):
|
245 |
+
ks = [ks, ks // 2 + 1]
|
246 |
+
self.bn = nn.BatchNorm1d(ni)
|
247 |
+
self.conv1 = conv1d(ni, nf, ks[0], stride)
|
248 |
+
self.conv2 = bn_relu_conv1d(nf, nf, ks[0], 1)
|
249 |
+
self.drop = nn.Dropout(drop_p, inplace=True) if drop_p else None
|
250 |
+
self.shortcut = conv1d(ni, nf, ks[1], stride) if (
|
251 |
+
ni != nf or stride > 1) else noop # adapted to make it work for fix_feature_dim=True
|
252 |
+
|
253 |
+
def forward(self, x):
|
254 |
+
x2 = F.relu(self.bn(x), inplace=True)
|
255 |
+
r = self.shortcut(x2)
|
256 |
+
x = self.conv1(x2)
|
257 |
+
if self.drop: x = self.drop(x)
|
258 |
+
x = self.conv2(x) * 0.2
|
259 |
+
return x.add_(r)
|
260 |
+
|
261 |
+
|
262 |
+
def _make_group(N, ni, nf, block, stride, drop_p, ks=3):
|
263 |
+
return [block(ni if i == 0 else nf, nf, stride if i == 0 else 1, drop_p, ks=ks) for i in range(N)]
|
264 |
+
|
265 |
+
|
266 |
+
class WideResNet1d(nn.Sequential):
|
267 |
+
def __init__(self, input_channels: int, num_groups: int, N: int, num_classes: int, k: int = 1, drop_p: float = 0.0,
|
268 |
+
start_nf: int = 16, fix_feature_dim=True, kernel_size=5, lin_ftrs_head=None, ps_head=0.5,
|
269 |
+
bn_final_head=False, bn_head=True, act_head="relu", concat_pooling=True):
|
270 |
+
super().__init__()
|
271 |
+
n_channels = [start_nf]
|
272 |
+
|
273 |
+
for i in range(num_groups): n_channels.append(start_nf if fix_feature_dim else start_nf * (2 ** i) * k)
|
274 |
+
|
275 |
+
layers = [conv1d(input_channels, n_channels[0], 3, 1)] # conv1 stem
|
276 |
+
for i in range(num_groups):
|
277 |
+
layers += _make_group(N, n_channels[i], n_channels[i + 1], BasicBlock1dwrn,
|
278 |
+
(1 if i == 0 else 2), drop_p, ks=kernel_size)
|
279 |
+
|
280 |
+
# layers += [nn.BatchNorm1d(n_channels[-1]), nn.ReLU(inplace=True), nn.AdaptiveAvgPool1d(1),
|
281 |
+
# Flatten(), nn.Linear(n_channels[-1], num_classes)]
|
282 |
+
head = create_head1d(n_channels[-1], nc=num_classes, lin_ftrs=lin_ftrs_head, ps=ps_head,
|
283 |
+
bn_final=bn_final_head, bn=bn_head, act=act_head,
|
284 |
+
concat_pooling=concat_pooling)
|
285 |
+
layers.append(head)
|
286 |
+
|
287 |
+
super().__init__()
|
288 |
+
|
289 |
+
def get_layer_groups(self):
|
290 |
+
return self[6], self[-1]
|
291 |
+
|
292 |
+
def get_output_layer(self):
|
293 |
+
return self[-1][-1]
|
294 |
+
|
295 |
+
def set_output_layer(self, x):
|
296 |
+
self[-1][-1] = x
|
297 |
+
|
298 |
+
|
299 |
+
def wrn1d_22(**kwargs): return WideResNet1d(num_groups=3, N=3, k=6, drop_p=0., **kwargs)
|
models/rnn1d.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from fastai.layers import *
|
4 |
+
from fastai.core import *
|
5 |
+
|
6 |
+
|
7 |
+
class AdaptiveConcatPoolRNN(nn.Module):
|
8 |
+
def __init__(self, bidirectional):
|
9 |
+
super().__init__()
|
10 |
+
self.bidirectional = bidirectional
|
11 |
+
|
12 |
+
def forward(self, x):
|
13 |
+
# input shape bs, ch, ts
|
14 |
+
t1 = nn.AdaptiveAvgPool1d(1)(x)
|
15 |
+
t2 = nn.AdaptiveMaxPool1d(1)(x)
|
16 |
+
|
17 |
+
if self.bidirectional is False:
|
18 |
+
t3 = x[:, :, -1]
|
19 |
+
else:
|
20 |
+
channels = x.size()[1]
|
21 |
+
t3 = torch.cat([x[:, :channels, -1], x[:, channels:, 0]], 1)
|
22 |
+
out = torch.cat([t1.squeeze(-1), t2.squeeze(-1), t3], 1) # output shape bs, 3*ch
|
23 |
+
return out
|
24 |
+
|
25 |
+
|
26 |
+
class RNN1d(nn.Sequential):
|
27 |
+
def __init__(self, input_channels, num_classes, lstm=True, hidden_dim=256, num_layers=2, bidirectional=False,
|
28 |
+
ps_head=0.5, act_head="relu", lin_ftrs_head=None, bn=True):
|
29 |
+
# bs, ch, ts -> ts, bs, ch
|
30 |
+
layers_tmp = [Lambda(lambda x: x.transpose(1, 2)), Lambda(lambda x: x.transpose(0, 1))]
|
31 |
+
# LSTM
|
32 |
+
if lstm:
|
33 |
+
layers_tmp.append(nn.LSTM(input_size=input_channels, hidden_size=hidden_dim, num_layers=num_layers,
|
34 |
+
bidirectional=bidirectional))
|
35 |
+
else:
|
36 |
+
layers_tmp.append(nn.GRU(input_size=input_channels, hidden_size=hidden_dim, num_layers=num_layers,
|
37 |
+
bidirectional=bidirectional))
|
38 |
+
# pooling
|
39 |
+
layers_tmp.append(Lambda(lambda x: x[0].transpose(0, 1)))
|
40 |
+
layers_tmp.append(Lambda(lambda x: x.transpose(1, 2)))
|
41 |
+
|
42 |
+
layers_head = [AdaptiveConcatPoolRNN(bidirectional)]
|
43 |
+
|
44 |
+
# classifier
|
45 |
+
nf = 3 * hidden_dim if bidirectional is False else 6 * hidden_dim
|
46 |
+
lin_ftrs_head = [nf, num_classes] if lin_ftrs_head is None else [nf] + lin_ftrs_head + [num_classes]
|
47 |
+
ps_head = listify(ps_head)
|
48 |
+
if len(ps_head) == 1:
|
49 |
+
ps_head = [ps_head[0] / 2] * (len(lin_ftrs_head) - 2) + ps_head
|
50 |
+
actns = [nn.ReLU(inplace=True) if act_head == "relu" else nn.ELU(inplace=True)] * (
|
51 |
+
len(lin_ftrs_head) - 2) + [None]
|
52 |
+
|
53 |
+
for ni, no, p, actn in zip(lin_ftrs_head[:-1], lin_ftrs_head[1:], ps_head, actns):
|
54 |
+
layers_head += bn_drop_lin(ni, no, bn, p, actn)
|
55 |
+
layers_head = nn.Sequential(*layers_head)
|
56 |
+
layers_tmp.append(layers_head)
|
57 |
+
|
58 |
+
super().__init__()
|
59 |
+
|
60 |
+
def get_layer_groups(self):
|
61 |
+
return self[-1],
|
62 |
+
|
63 |
+
def get_output_layer(self):
|
64 |
+
return self[-1][-1]
|
65 |
+
|
66 |
+
def set_output_layer(self, x):
|
67 |
+
self[-1][-1] = x
|
models/wavelet.py
ADDED
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sklearn.linear_model import LogisticRegression
|
2 |
+
from sklearn.multiclass import OneVsRestClassifier
|
3 |
+
from models.base_model import ClassificationModel
|
4 |
+
import pickle
|
5 |
+
from tqdm import tqdm
|
6 |
+
import numpy as np
|
7 |
+
from sklearn.ensemble import RandomForestClassifier
|
8 |
+
import pywt
|
9 |
+
import scipy.stats
|
10 |
+
import multiprocessing
|
11 |
+
from collections import Counter
|
12 |
+
from keras.layers import Dropout, Dense, Input
|
13 |
+
from keras.models import Model
|
14 |
+
from keras.models import load_model
|
15 |
+
from keras.callbacks import ModelCheckpoint
|
16 |
+
from sklearn.preprocessing import StandardScaler
|
17 |
+
|
18 |
+
|
19 |
+
def calculate_entropy(list_values):
|
20 |
+
counter_values = Counter(list_values).most_common()
|
21 |
+
probabilities = [elem[1] / len(list_values) for elem in counter_values]
|
22 |
+
entropy = scipy.stats.entropy(probabilities)
|
23 |
+
return entropy
|
24 |
+
|
25 |
+
|
26 |
+
def calculate_statistics(list_values):
|
27 |
+
n5 = np.nanpercentile(list_values, 5)
|
28 |
+
n25 = np.nanpercentile(list_values, 25)
|
29 |
+
n75 = np.nanpercentile(list_values, 75)
|
30 |
+
n95 = np.nanpercentile(list_values, 95)
|
31 |
+
median = np.nanpercentile(list_values, 50)
|
32 |
+
mean = np.nanmean(list_values)
|
33 |
+
std = np.nanstd(list_values)
|
34 |
+
var = np.nanvar(list_values)
|
35 |
+
rms = np.nanmean(np.sqrt(list_values ** 2))
|
36 |
+
return [n5, n25, n75, n95, median, mean, std, var, rms]
|
37 |
+
|
38 |
+
|
39 |
+
def calculate_crossings(list_values):
|
40 |
+
zero_crossing_indices = np.nonzero(np.diff(np.array(list_values) > 0))[0]
|
41 |
+
no_zero_crossings = len(zero_crossing_indices)
|
42 |
+
mean_crossing_indices = np.nonzero(np.diff(np.array(list_values) > np.nanmean(list_values)))[0]
|
43 |
+
no_mean_crossings = len(mean_crossing_indices)
|
44 |
+
return [no_zero_crossings, no_mean_crossings]
|
45 |
+
|
46 |
+
|
47 |
+
def get_features(list_values):
|
48 |
+
entropy = calculate_entropy(list_values)
|
49 |
+
crossings = calculate_crossings(list_values)
|
50 |
+
statistics = calculate_statistics(list_values)
|
51 |
+
return [entropy] + crossings + statistics
|
52 |
+
|
53 |
+
|
54 |
+
def get_single_ecg_features(signal, waveletname='db6'):
|
55 |
+
features = []
|
56 |
+
for channel in signal.T:
|
57 |
+
list_coeff = pywt.wavedec(channel, wavelet=waveletname, level=5)
|
58 |
+
channel_features = []
|
59 |
+
for coeff in list_coeff:
|
60 |
+
channel_features += get_features(coeff)
|
61 |
+
features.append(channel_features)
|
62 |
+
return np.array(features).flatten()
|
63 |
+
|
64 |
+
|
65 |
+
def get_ecg_features(ecg_data, parallel=True):
|
66 |
+
if parallel:
|
67 |
+
pool = multiprocessing.Pool(18)
|
68 |
+
return np.array(pool.map(get_single_ecg_features, ecg_data))
|
69 |
+
else:
|
70 |
+
list_features = []
|
71 |
+
for signal in tqdm(ecg_data):
|
72 |
+
features = get_single_ecg_features(signal)
|
73 |
+
list_features.append(features)
|
74 |
+
return np.array(list_features)
|
75 |
+
|
76 |
+
|
77 |
+
# for keras models
|
78 |
+
# def keras_macro_auroc(y_true, y_pred):
|
79 |
+
# return tf.py_func(macro_auroc, (y_true, y_pred), tf.double)
|
80 |
+
|
81 |
+
class WaveletModel(ClassificationModel):
|
82 |
+
def __init__(self, name, n_classes, freq, outputfolder, input_shape, regularizer_C=.001, classifier='RF'):
|
83 |
+
# Disclaimer: This model assumes equal shapes across all samples!
|
84 |
+
# standard parameters
|
85 |
+
super().__init__()
|
86 |
+
self.name = name
|
87 |
+
self.outputfolder = outputfolder
|
88 |
+
self.n_classes = n_classes
|
89 |
+
self.freq = freq
|
90 |
+
self.regularizer_C = regularizer_C
|
91 |
+
self.classifier = classifier
|
92 |
+
self.dropout = .25
|
93 |
+
self.activation = 'relu'
|
94 |
+
self.final_activation = 'sigmoid'
|
95 |
+
self.n_dense_dim = 128
|
96 |
+
self.epochs = 30
|
97 |
+
|
98 |
+
def fit(self, X_train, y_train, X_val, y_val):
|
99 |
+
XF_train = get_ecg_features(X_train)
|
100 |
+
XF_val = get_ecg_features(X_val)
|
101 |
+
|
102 |
+
if self.classifier == 'LR':
|
103 |
+
if self.n_classes > 1:
|
104 |
+
clf = OneVsRestClassifier(
|
105 |
+
LogisticRegression(C=self.regularizer_C, solver='lbfgs', max_iter=1000, n_jobs=-1))
|
106 |
+
else:
|
107 |
+
clf = LogisticRegression(C=self.regularizer_C, solver='lbfgs', max_iter=1000, n_jobs=-1)
|
108 |
+
clf.fit(XF_train, y_train)
|
109 |
+
pickle.dump(clf, open(self.outputfolder + 'clf.pkl', 'wb'))
|
110 |
+
elif self.classifier == 'RF':
|
111 |
+
clf = RandomForestClassifier(n_estimators=1000, n_jobs=16)
|
112 |
+
clf.fit(XF_train, y_train)
|
113 |
+
pickle.dump(clf, open(self.outputfolder + 'clf.pkl', 'wb'))
|
114 |
+
elif self.classifier == 'NN':
|
115 |
+
# standardize input data
|
116 |
+
ss = StandardScaler()
|
117 |
+
XFT_train = ss.fit_transform(XF_train)
|
118 |
+
XFT_val = ss.transform(XF_val)
|
119 |
+
pickle.dump(ss, open(self.outputfolder + 'ss.pkl', 'wb'))
|
120 |
+
# classification stage
|
121 |
+
input_x = Input(shape=(XFT_train.shape[1],))
|
122 |
+
x = Dense(self.n_dense_dim, activation=self.activation)(input_x)
|
123 |
+
x = Dropout(self.dropout)(x)
|
124 |
+
y = Dense(self.n_classes, activation=self.final_activation)(x)
|
125 |
+
self.model = Model(input_x, y)
|
126 |
+
|
127 |
+
self.model.compile(optimizer='adamax', loss='binary_crossentropy') # , metrics=[keras_macro_auroc])
|
128 |
+
# monitor validation error
|
129 |
+
mc_loss = ModelCheckpoint(self.outputfolder + 'best_loss_model.h5', monitor='val_loss', mode='min',
|
130 |
+
verbose=1, save_best_only=True)
|
131 |
+
# mc_score = ModelCheckpoint(self.output_folder +'best_score_model.h5', monitor='val_keras_macro_auroc', mode='max', verbose=1, save_best_only=True)
|
132 |
+
self.model.fit(XFT_train, y_train, validation_data=(XFT_val, y_val), epochs=self.epochs, batch_size=128,
|
133 |
+
callbacks=[mc_loss]) # , mc_score])
|
134 |
+
self.model.save(self.outputfolder + 'last_model.h5')
|
135 |
+
|
136 |
+
def predict(self, X):
|
137 |
+
XF = get_ecg_features(X)
|
138 |
+
if self.classifier == 'LR':
|
139 |
+
clf = pickle.load(open(self.outputfolder + 'clf.pkl', 'rb'))
|
140 |
+
if self.n_classes > 1:
|
141 |
+
return clf.predict_proba(XF)
|
142 |
+
else:
|
143 |
+
return clf.predict_proba(XF)[:, 1][:, np.newaxis]
|
144 |
+
elif self.classifier == 'RF':
|
145 |
+
clf = pickle.load(open(self.outputfolder + 'clf.pkl', 'rb'))
|
146 |
+
y_pred = clf.predict_proba(XF)
|
147 |
+
if self.n_classes > 1:
|
148 |
+
return np.array([yi[:, 1] for yi in y_pred]).T
|
149 |
+
else:
|
150 |
+
return y_pred[:, 1][:, np.newaxis]
|
151 |
+
elif self.classifier == 'NN':
|
152 |
+
ss = pickle.load(open(self.outputfolder + 'ss.pkl', 'rb')) #
|
153 |
+
XFT = ss.transform(XF)
|
154 |
+
model = load_model(
|
155 |
+
self.outputfolder + 'best_loss_model.h5')
|
156 |
+
# 'best_score_model.h5', custom_objects={
|
157 |
+
# 'keras_macro_auroc': keras_macro_auroc})
|
158 |
+
return model.predict(XFT)
|
models/xresnet1d.py
ADDED
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from enum import Enum
|
4 |
+
import re
|
5 |
+
# delegates
|
6 |
+
import inspect
|
7 |
+
|
8 |
+
from torch.nn.utils import weight_norm, spectral_norm
|
9 |
+
|
10 |
+
from models.basicconv1d import create_head1d
|
11 |
+
|
12 |
+
|
13 |
+
def delegates(to=None, keep=False):
|
14 |
+
"""Decorator: replace `**kwargs` in signature with params from `to`"""
|
15 |
+
|
16 |
+
def _f(f):
|
17 |
+
if to is None:
|
18 |
+
to_f, from_f = f.__base__.__init__, f.__init__
|
19 |
+
else:
|
20 |
+
to_f, from_f = to, f
|
21 |
+
sig = inspect.signature(from_f)
|
22 |
+
sigd = dict(sig.parameters)
|
23 |
+
k = sigd.pop('kwargs')
|
24 |
+
s2 = {k: v for k, v in inspect.signature(to_f).parameters.items()
|
25 |
+
if v.default != inspect.Parameter.empty and k not in sigd}
|
26 |
+
sigd.update(s2)
|
27 |
+
if keep: sigd['kwargs'] = k
|
28 |
+
from_f.__signature__ = sig.replace(parameters=sigd.values())
|
29 |
+
return f
|
30 |
+
|
31 |
+
return _f
|
32 |
+
|
33 |
+
|
34 |
+
def store_attr(self, nms):
|
35 |
+
"""Store params named in comma-separated `nms` from calling context into attrs in `self`"""
|
36 |
+
mod = inspect.currentframe().f_back.f_locals
|
37 |
+
for n in re.split(', *', nms): setattr(self, n, mod[n])
|
38 |
+
|
39 |
+
|
40 |
+
NormType = Enum('NormType', 'Batch BatchZero Weight Spectral Instance InstanceZero')
|
41 |
+
|
42 |
+
|
43 |
+
def _conv_func(ndim=2, transpose=False):
|
44 |
+
"""Return the proper conv `ndim` function, potentially `transposed`."""
|
45 |
+
assert 1 <= ndim <= 3
|
46 |
+
return getattr(nn, f'Conv{"Transpose" if transpose else ""}{ndim}d')
|
47 |
+
|
48 |
+
|
49 |
+
def init_default(m, func=nn.init.kaiming_normal_):
|
50 |
+
"""Initialize `m` weights with `func` and set `bias` to 0."""
|
51 |
+
if func and hasattr(m, 'weight'): func(m.weight)
|
52 |
+
with torch.no_grad():
|
53 |
+
if getattr(m, 'bias', None) is not None: m.bias.fill_(0.)
|
54 |
+
return m
|
55 |
+
|
56 |
+
|
57 |
+
def _get_norm(prefix, nf, ndim=2, zero=False, **kwargs):
|
58 |
+
"""Norm layer with `nf` features and `ndim` initialized depending on `norm_type`."""
|
59 |
+
assert 1 <= ndim <= 3
|
60 |
+
bn = getattr(nn, f"{prefix}{ndim}d")(nf, **kwargs)
|
61 |
+
if bn.affine:
|
62 |
+
bn.bias.data.fill_(1e-3)
|
63 |
+
bn.weight.data.fill_(0. if zero else 1.)
|
64 |
+
return bn
|
65 |
+
|
66 |
+
|
67 |
+
def BatchNorm(nf, ndim=2, norm_type=NormType.Batch, **kwargs):
|
68 |
+
"""BatchNorm layer with `nf` features and `ndim` initialized depending on `norm_type`."""
|
69 |
+
return _get_norm('BatchNorm', nf, ndim, zero=norm_type == NormType.BatchZero, **kwargs)
|
70 |
+
|
71 |
+
|
72 |
+
class ConvLayer(nn.Sequential):
|
73 |
+
"""Create a sequence of convolutional (`ni` to `nf`), ReLU (if `use_activ`) and `norm_type` layers."""
|
74 |
+
|
75 |
+
def __init__(self, ni, nf, ks=3, stride=1, padding=None, bias=None, ndim=2, norm_type=NormType.Batch, bn_1st=True,
|
76 |
+
act_cls=nn.ReLU, transpose=False, init=nn.init.kaiming_normal_, xtra=None, **kwargs):
|
77 |
+
if padding is None: padding = ((ks - 1) // 2 if not transpose else 0)
|
78 |
+
bn = norm_type in (NormType.Batch, NormType.BatchZero)
|
79 |
+
inn = norm_type in (NormType.Instance, NormType.InstanceZero)
|
80 |
+
if bias is None: bias = not (bn or inn)
|
81 |
+
conv_func = _conv_func(ndim, transpose=transpose)
|
82 |
+
conv = init_default(conv_func(ni, nf, kernel_size=ks, bias=bias, stride=stride, padding=padding, **kwargs),
|
83 |
+
init)
|
84 |
+
if norm_type == NormType.Weight:
|
85 |
+
conv = weight_norm(conv)
|
86 |
+
elif norm_type == NormType.Spectral:
|
87 |
+
conv = spectral_norm(conv)
|
88 |
+
layers = [conv]
|
89 |
+
act_bn = []
|
90 |
+
if act_cls is not None: act_bn.append(act_cls())
|
91 |
+
if bn: act_bn.append(BatchNorm(nf, norm_type=norm_type, ndim=ndim))
|
92 |
+
if inn: act_bn.append(nn.InstanceNorm2d(nf, norm_type=norm_type, ndim=ndim))
|
93 |
+
if bn_1st: act_bn.reverse()
|
94 |
+
layers += act_bn
|
95 |
+
if xtra: layers.append(xtra)
|
96 |
+
super().__init__()
|
97 |
+
|
98 |
+
|
99 |
+
def AdaptiveAvgPool(sz=1, ndim=2):
|
100 |
+
"""nn.AdaptiveAvgPool layer for `ndim`"""
|
101 |
+
assert 1 <= ndim <= 3
|
102 |
+
return getattr(nn, f"AdaptiveAvgPool{ndim}d")(sz)
|
103 |
+
|
104 |
+
|
105 |
+
def MaxPool(ks=2, stride=None, padding=0, ndim=2, ceil_mode=False):
|
106 |
+
"""nn.MaxPool layer for `ndim`"""
|
107 |
+
assert 1 <= ndim <= 3
|
108 |
+
return getattr(nn, f"MaxPool{ndim}d")(ks, stride=stride, padding=padding)
|
109 |
+
|
110 |
+
|
111 |
+
def AvgPool(ks=2, stride=None, padding=0, ndim=2, ceil_mode=False):
|
112 |
+
"""nn.AvgPool layer for `ndim`"""
|
113 |
+
assert 1 <= ndim <= 3
|
114 |
+
return getattr(nn, f"AvgPool{ndim}d")(ks, stride=stride, padding=padding, ceil_mode=ceil_mode)
|
115 |
+
|
116 |
+
|
117 |
+
class ResBlock(nn.Module):
|
118 |
+
"Resnet block from `ni` to `nh` with `stride`"
|
119 |
+
|
120 |
+
@delegates(ConvLayer.__init__)
|
121 |
+
def __init__(self, expansion, ni, nf, stride=1, kernel_size=3, groups=1, reduction=None, nh1=None, nh2=None,
|
122 |
+
dw=False, g2=1,
|
123 |
+
sa=False, sym=False, norm_type=NormType.Batch, act_cls=nn.ReLU, ndim=2,
|
124 |
+
pool=AvgPool, pool_first=True, **kwargs):
|
125 |
+
super().__init__()
|
126 |
+
norm2 = (NormType.BatchZero if norm_type == NormType.Batch else
|
127 |
+
NormType.InstanceZero if norm_type == NormType.Instance else norm_type)
|
128 |
+
if nh2 is None: nh2 = nf
|
129 |
+
if nh1 is None: nh1 = nh2
|
130 |
+
nf, ni = nf * expansion, ni * expansion
|
131 |
+
k0 = dict(norm_type=norm_type, act_cls=act_cls, ndim=ndim, **kwargs)
|
132 |
+
k1 = dict(norm_type=norm2, act_cls=None, ndim=ndim, **kwargs)
|
133 |
+
layers = [ConvLayer(ni, nh2, kernel_size, stride=stride, groups=ni if dw else groups, **k0),
|
134 |
+
ConvLayer(nh2, nf, kernel_size, groups=g2, **k1)
|
135 |
+
] if expansion == 1 else [
|
136 |
+
ConvLayer(ni, nh1, 1, **k0),
|
137 |
+
ConvLayer(nh1, nh2, kernel_size, stride=stride, groups=nh1 if dw else groups, **k0),
|
138 |
+
ConvLayer(nh2, nf, 1, groups=g2, **k1)]
|
139 |
+
self.convs = nn.Sequential(*layers)
|
140 |
+
convpath = [self.convs]
|
141 |
+
if reduction: convpath.append(nn.SEModule(nf, reduction=reduction, act_cls=act_cls))
|
142 |
+
if sa: convpath.append(nn.SimpleSelfAttention(nf, ks=1, sym=sym))
|
143 |
+
self.convpath = nn.Sequential(*convpath)
|
144 |
+
idpath = []
|
145 |
+
if ni != nf: idpath.append(ConvLayer(ni, nf, 1, act_cls=None, ndim=ndim, **kwargs))
|
146 |
+
if stride != 1: idpath.insert((1, 0)[pool_first], pool(2, ndim=ndim, ceil_mode=True))
|
147 |
+
self.idpath = nn.Sequential(*idpath)
|
148 |
+
self.act = nn.ReLU(inplace=True) if act_cls is nn.ReLU else act_cls()
|
149 |
+
|
150 |
+
def forward(self, x):
|
151 |
+
return self.act(self.convpath(x) + self.idpath(x))
|
152 |
+
|
153 |
+
|
154 |
+
######################### adapted from vison.models.xresnet
|
155 |
+
def init_cnn(m):
|
156 |
+
if getattr(m, 'bias', None) is not None: nn.init.constant_(m.bias, 0)
|
157 |
+
if isinstance(m, (nn.Conv1d, nn.Conv2d, nn.Linear)): nn.init.kaiming_normal_(m.weight)
|
158 |
+
for l in m.children(): init_cnn(l)
|
159 |
+
|
160 |
+
|
161 |
+
class XResNet1d(nn.Sequential):
|
162 |
+
@delegates(ResBlock)
|
163 |
+
def __init__(self, block, expansion, layers, p=0.0, input_channels=3, num_classes=1000, stem_szs=(32, 32, 64),
|
164 |
+
kernel_size=5, kernel_size_stem=5,
|
165 |
+
widen=1.0, sa=False, act_cls=nn.ReLU, lin_ftrs_head=None, ps_head=0.5, bn_final_head=False,
|
166 |
+
bn_head=True, act_head="relu", concat_pooling=True, **kwargs):
|
167 |
+
store_attr(self, 'block,expansion,act_cls')
|
168 |
+
stem_szs = [input_channels, *stem_szs]
|
169 |
+
stem = [ConvLayer(stem_szs[i], stem_szs[i + 1], ks=kernel_size_stem, stride=2 if i == 0 else 1, act_cls=act_cls,
|
170 |
+
ndim=1)
|
171 |
+
for i in range(3)]
|
172 |
+
|
173 |
+
# block_szs = [int(o*widen) for o in [64,128,256,512] +[256]*(len(layers)-4)]
|
174 |
+
block_szs = [int(o * widen) for o in [64, 64, 64, 64] + [32] * (len(layers) - 4)]
|
175 |
+
block_szs = [64 // expansion] + block_szs
|
176 |
+
blocks = [self._make_layer(ni=block_szs[i], nf=block_szs[i + 1], blocks=l,
|
177 |
+
stride=1 if i == 0 else 2, kernel_size=kernel_size, sa=sa and i == len(layers) - 4,
|
178 |
+
ndim=1, **kwargs)
|
179 |
+
for i, l in enumerate(layers)]
|
180 |
+
|
181 |
+
head = create_head1d(block_szs[-1] * expansion, nc=num_classes, lin_ftrs=lin_ftrs_head, ps=ps_head,
|
182 |
+
bn_final=bn_final_head, bn=bn_head, act=act_head,
|
183 |
+
concat_pooling=concat_pooling)
|
184 |
+
|
185 |
+
super().__init__(nn.MaxPool1d(kernel_size=3, stride=2, padding=1), head)
|
186 |
+
init_cnn(self)
|
187 |
+
|
188 |
+
def _make_layer(self, ni, nf, blocks, stride, kernel_size, sa, **kwargs):
|
189 |
+
return nn.Sequential(
|
190 |
+
*[self.block(self.expansion, ni if i == 0 else nf, nf, stride=stride if i == 0 else 1,
|
191 |
+
kernel_size=kernel_size, sa=sa and i == (blocks - 1), act_cls=self.act_cls, **kwargs)
|
192 |
+
for i in range(blocks)])
|
193 |
+
|
194 |
+
def get_layer_groups(self):
|
195 |
+
return self[3], self[-1]
|
196 |
+
|
197 |
+
def get_output_layer(self):
|
198 |
+
return self[-1][-1]
|
199 |
+
|
200 |
+
def set_output_layer(self, x):
|
201 |
+
self[-1][-1] = x
|
202 |
+
|
203 |
+
|
204 |
+
# xresnets
|
205 |
+
def _xresnet1d(expansion, layers, **kwargs):
|
206 |
+
return XResNet1d(ResBlock, expansion, layers, **kwargs)
|
207 |
+
|
208 |
+
|
209 |
+
def xresnet1d18(**kwargs): return _xresnet1d(1, [2, 2, 2, 2], **kwargs)
|
210 |
+
|
211 |
+
|
212 |
+
def xresnet1d34(**kwargs): return _xresnet1d(1, [3, 4, 6, 3], **kwargs)
|
213 |
+
|
214 |
+
|
215 |
+
def xresnet1d50(**kwargs): return _xresnet1d(4, [3, 4, 6, 3], **kwargs)
|
216 |
+
|
217 |
+
|
218 |
+
def xresnet1d101(**kwargs): return _xresnet1d(4, [3, 4, 23, 3], **kwargs)
|
219 |
+
|
220 |
+
|
221 |
+
def xresnet1d152(**kwargs): return _xresnet1d(4, [3, 8, 36, 3], **kwargs)
|
222 |
+
|
223 |
+
|
224 |
+
def xresnet1d18_deep(**kwargs): return _xresnet1d(1, [2, 2, 2, 2, 1, 1], **kwargs)
|
225 |
+
|
226 |
+
|
227 |
+
def xresnet1d34_deep(**kwargs): return _xresnet1d(1, [3, 4, 6, 3, 1, 1], **kwargs)
|
228 |
+
|
229 |
+
|
230 |
+
def xresnet1d50_deep(**kwargs): return _xresnet1d(4, [3, 4, 6, 3, 1, 1], **kwargs)
|
231 |
+
|
232 |
+
|
233 |
+
def xresnet1d18_deeper(**kwargs): return _xresnet1d(1, [2, 2, 1, 1, 1, 1, 1, 1], **kwargs)
|
234 |
+
|
235 |
+
|
236 |
+
def xresnet1d34_deeper(**kwargs): return _xresnet1d(1, [3, 4, 6, 3, 1, 1, 1, 1], **kwargs)
|
237 |
+
|
238 |
+
|
239 |
+
def xresnet1d50_deeper(**kwargs): return _xresnet1d(4, [3, 4, 6, 3, 1, 1, 1, 1], **kwargs)
|
output/.getkeep
ADDED
File without changes
|
requirements.yml
ADDED
Binary file (28.6 kB). View file
|
|
utilities/stratify.py
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from tqdm import tqdm
|
3 |
+
|
4 |
+
|
5 |
+
def stratify_df(df, new_col_name, n_folds=10, nr_clean_folds=0):
|
6 |
+
# compute qualities as described in PTB-XL report
|
7 |
+
qualities = []
|
8 |
+
for i, row in df.iterrows():
|
9 |
+
q = 0
|
10 |
+
if 'validated_by_human' in df.columns:
|
11 |
+
if row.validated_by_human:
|
12 |
+
q = 1
|
13 |
+
qualities.append(q)
|
14 |
+
df['quality'] = qualities
|
15 |
+
|
16 |
+
# create stratified folds according to patients
|
17 |
+
pat_ids = np.array(sorted(list(set(df.patient_id.values))))
|
18 |
+
p_labels = []
|
19 |
+
p_qualities = []
|
20 |
+
ecgs_per_patient = []
|
21 |
+
|
22 |
+
for pid in tqdm(pat_ids):
|
23 |
+
sel = df[df.patient_id == pid]
|
24 |
+
l = np.concatenate([list(d.keys()) for d in sel.scp_codes.values])
|
25 |
+
if sel.sex.values[0] == 0:
|
26 |
+
gender = 'male'
|
27 |
+
else:
|
28 |
+
gender = 'female'
|
29 |
+
l = np.concatenate((l, [gender] * len(sel)))
|
30 |
+
for age in sel.age.values:
|
31 |
+
if age < 20:
|
32 |
+
l = np.concatenate((l, ['<20']))
|
33 |
+
elif 20 <= age < 40:
|
34 |
+
l = np.concatenate((l, ['20-40']))
|
35 |
+
elif 40 <= age < 60:
|
36 |
+
l = np.concatenate((l, ['40-60']))
|
37 |
+
elif 60 <= age < 80:
|
38 |
+
l = np.concatenate((l, ['60-80']))
|
39 |
+
elif age >= 80:
|
40 |
+
l = np.concatenate((l, ['>=80']))
|
41 |
+
p_labels.append(l)
|
42 |
+
ecgs_per_patient.append(len(sel))
|
43 |
+
p_qualities.append(sel.quality.min())
|
44 |
+
classes = sorted(list(set([item for sublist in p_labels for item in sublist])))
|
45 |
+
|
46 |
+
stratified_data_ids, stratified_data = stratify(p_labels, classes, [1 / n_folds] * n_folds, p_qualities,
|
47 |
+
ecgs_per_patient, nr_clean_folds)
|
48 |
+
|
49 |
+
df[new_col_name] = np.zeros(len(df)).astype(int)
|
50 |
+
for fold_i, fold_ids in tqdm(enumerate(stratified_data_ids)):
|
51 |
+
ipat_ids = [pat_ids[pid] for pid in fold_ids]
|
52 |
+
df[new_col_name][df.patient_id.isin(ipat_ids)] = fold_i + 1
|
53 |
+
|
54 |
+
return df
|
55 |
+
|
56 |
+
|
57 |
+
def stratify(data, classes, ratios, qualities, ecgs_per_patient, nr_clean_folds=1):
|
58 |
+
"""Stratifying procedure. Modified from https://vict0rs.ch/2018/05/24/sample-multilabel-dataset/ (based on Sechidis 2011)
|
59 |
+
|
60 |
+
data is a list of lists: a list of labels, for each sample.
|
61 |
+
Each sample's labels should be ints, if they are one-hot encoded, use one_hot=True
|
62 |
+
|
63 |
+
classes is the list of classes each label can take
|
64 |
+
|
65 |
+
ratios is a list, summing to 1, of how the dataset should be split
|
66 |
+
|
67 |
+
qualities: quality per entry (only >0 can be assigned to clean folds; 4 will always be assigned to final fold)
|
68 |
+
|
69 |
+
ecgs_per_patient: list with number of ecgs per sample
|
70 |
+
|
71 |
+
nr_clean_folds: the last nr_clean_folds can only take clean entries
|
72 |
+
|
73 |
+
"""
|
74 |
+
np.random.seed(0) # fix the random seed
|
75 |
+
|
76 |
+
# data is now always a list of lists; len(data) is the number of patients; data[i] is the list of all labels for
|
77 |
+
# patient i (possibly multiple identical entries)
|
78 |
+
|
79 |
+
# size is the number of ecgs
|
80 |
+
size = np.sum(ecgs_per_patient)
|
81 |
+
|
82 |
+
# Organize data per label: for each label l, per_label_data[l] contains the list of patients
|
83 |
+
# in data which have this label (potentially multiple identical entries)
|
84 |
+
per_label_data = {c: [] for c in classes}
|
85 |
+
for i, d in enumerate(data):
|
86 |
+
for l in d:
|
87 |
+
per_label_data[l].append(i)
|
88 |
+
|
89 |
+
# In order not to compute lengths each time, they are tracked here.
|
90 |
+
subset_sizes = [r * size for r in ratios] # list of subset_sizes in terms of ecgs
|
91 |
+
per_label_subset_sizes = {c: [r * len(per_label_data[c]) for r in ratios] for c in
|
92 |
+
classes} # dictionary with label: list of subset sizes in terms of patients
|
93 |
+
|
94 |
+
# For each subset we want, the set of sample-ids which should end up in it
|
95 |
+
stratified_data_ids = [set() for _ in range(len(ratios))] # initialize empty
|
96 |
+
|
97 |
+
# For each sample in the data set
|
98 |
+
print("Assigning patients to folds...")
|
99 |
+
size_prev = size + 1 # just for output
|
100 |
+
while size > 0:
|
101 |
+
if int(size_prev / 1000) > int(size / 1000):
|
102 |
+
print("Remaining patients/ecgs to distribute:", size, "non-empty labels:",
|
103 |
+
np.sum([1 for l, label_data in per_label_data.items() if len(label_data) > 0]))
|
104 |
+
size_prev = size
|
105 |
+
# Compute |Di|
|
106 |
+
lengths = {
|
107 |
+
l: len(label_data)
|
108 |
+
for l, label_data in per_label_data.items()
|
109 |
+
} # dictionary label: number of ecgs with this label that have not been assigned to a fold yet
|
110 |
+
try:
|
111 |
+
# Find label of smallest |Di|
|
112 |
+
label = min({k: v for k, v in lengths.items() if v > 0}, key=lengths.get)
|
113 |
+
except ValueError:
|
114 |
+
# If the dictionary in `min` is empty we get a Value Error.
|
115 |
+
# This can happen if there are unlabeled samples.
|
116 |
+
# In this case, `size` would be > 0 but only samples without label would remain.
|
117 |
+
# "No label" could be a class in itself: it's up to you to format your data accordingly.
|
118 |
+
break
|
119 |
+
# For each patient with label `label` get patient and corresponding counts
|
120 |
+
unique_samples, unique_counts = np.unique(per_label_data[label], return_counts=True)
|
121 |
+
idxs_sorted = np.argsort(unique_counts, kind='stable')[::-1]
|
122 |
+
unique_samples = unique_samples[
|
123 |
+
idxs_sorted] # this is a list of all patient ids with this label sort by size descending
|
124 |
+
unique_counts = unique_counts[idxs_sorted] # these are the corresponding counts
|
125 |
+
|
126 |
+
# loop through all patient ids with this label
|
127 |
+
for current_id, current_count in zip(unique_samples, unique_counts):
|
128 |
+
|
129 |
+
subset_sizes_for_label = per_label_subset_sizes[label] # current subset sizes for the chosen label
|
130 |
+
|
131 |
+
# if quality is bad remove clean folds (i.e. sample cannot be assigned to clean folds)
|
132 |
+
if qualities[current_id] < 1:
|
133 |
+
subset_sizes_for_label = subset_sizes_for_label[:len(ratios) - nr_clean_folds]
|
134 |
+
|
135 |
+
# Find argmax clj i.e. subset in greatest need of the current label
|
136 |
+
largest_subsets = np.argwhere(subset_sizes_for_label == np.amax(subset_sizes_for_label)).flatten()
|
137 |
+
|
138 |
+
# if there is a single best choice: assign it
|
139 |
+
if len(largest_subsets) == 1:
|
140 |
+
subset = largest_subsets[0]
|
141 |
+
# If there is more than one such subset, find the one in greatest need of any label
|
142 |
+
else:
|
143 |
+
largest_subsets2 = np.argwhere(np.array(subset_sizes)[largest_subsets] == np.amax(
|
144 |
+
np.array(subset_sizes)[largest_subsets])).flatten()
|
145 |
+
subset = largest_subsets[np.random.choice(largest_subsets2)]
|
146 |
+
|
147 |
+
# Store the sample's id in the selected subset
|
148 |
+
stratified_data_ids[subset].add(current_id)
|
149 |
+
|
150 |
+
# There is current_count fewer samples to distribute
|
151 |
+
size -= ecgs_per_patient[current_id]
|
152 |
+
# The selected subset needs current_count fewer samples
|
153 |
+
subset_sizes[subset] -= ecgs_per_patient[current_id]
|
154 |
+
|
155 |
+
# In the selected subset, there is one more example for each label
|
156 |
+
# the current sample has
|
157 |
+
for l in data[current_id]:
|
158 |
+
per_label_subset_sizes[l][subset] -= 1
|
159 |
+
|
160 |
+
# Remove the sample from the dataset, meaning from all per_label dataset created
|
161 |
+
for x in per_label_data.keys():
|
162 |
+
per_label_data[x] = [y for y in per_label_data[x] if y != current_id]
|
163 |
+
|
164 |
+
# Create the stratified dataset as a list of subsets, each containing the original labels
|
165 |
+
stratified_data_ids = [sorted(strat) for strat in stratified_data_ids]
|
166 |
+
stratified_data = [
|
167 |
+
[data[i] for i in strat] for strat in stratified_data_ids
|
168 |
+
]
|
169 |
+
|
170 |
+
# Return both the stratified indexes, to be used to sample the `features` associated with your labels
|
171 |
+
# And the stratified labels dataset
|
172 |
+
|
173 |
+
return stratified_data_ids, stratified_data
|
utilities/timeseries_utils.py
ADDED
@@ -0,0 +1,649 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
import torch.utils.data
|
4 |
+
from torch import nn
|
5 |
+
from pathlib import Path
|
6 |
+
from scipy.stats import iqr
|
7 |
+
import os
|
8 |
+
#Note: due to issues with the numpy rng for multiprocessing
|
9 |
+
#(https://github.com/pytorch/pytorch/issues/5059) that could be
|
10 |
+
#fixed by a custom worker_init_fn we use random throughout for convenience
|
11 |
+
import random
|
12 |
+
from skimage import transform
|
13 |
+
import warnings
|
14 |
+
warnings.filterwarnings("ignore", category=UserWarning)
|
15 |
+
from scipy.signal import butter, sosfilt, sosfiltfilt, sosfreqz
|
16 |
+
#https://stackoverflow.com/questions/12093594/how-to-implement-band-pass-butterworth-filter-with-scipy-signal-butter
|
17 |
+
|
18 |
+
def butter_filter(lowcut=10, highcut=20, fs=50, order=5, btype='band'): # image processing Butterworth filter
|
19 |
+
"""returns butterworth filter with given specifications"""
|
20 |
+
nyq = 0.5 * fs
|
21 |
+
low = lowcut / nyq
|
22 |
+
high = highcut / nyq
|
23 |
+
|
24 |
+
sos = butter(order, [low, high] if btype == "band" else (low if btype == "low" else high), analog=False,
|
25 |
+
btype=btype, output='sos')
|
26 |
+
return sos
|
27 |
+
|
28 |
+
|
29 |
+
def butter_filter_frequency_response(filter):
|
30 |
+
"""returns frequency response of a given filter (result of call of butter_filter)"""
|
31 |
+
w, h = sosfreqz(filter)
|
32 |
+
# gain vs. freq(Hz)
|
33 |
+
# plt.plot((fs * 0.5 / np.pi) * w, abs(h))
|
34 |
+
return w, h
|
35 |
+
|
36 |
+
|
37 |
+
def apply_butter_filter(data, filter, forwardbackward=True): # The function provides options for handling the edges of the signal.
|
38 |
+
"""pass filter from call of butter_filter to data (assuming time axis at dimension 0)"""
|
39 |
+
if forwardbackward:
|
40 |
+
return sosfiltfilt(filter, data, axis=0)
|
41 |
+
else:
|
42 |
+
data = sosfilt(filter, data, axis=0)
|
43 |
+
|
44 |
+
|
45 |
+
def dataset_add_chunk_col(df, col="data"):
|
46 |
+
"""add a chunk column to the dataset df"""
|
47 |
+
df["chunk"] = df.groupby(col).cumcount()
|
48 |
+
|
49 |
+
|
50 |
+
def dataset_add_length_col(df, col="data", data_folder=None):
|
51 |
+
"""add a length column to the dataset df"""
|
52 |
+
df[col + "_length"] = df[col].apply(lambda x: len(np.load(x if data_folder is None else data_folder / x)))
|
53 |
+
|
54 |
+
|
55 |
+
def dataset_add_labels_col(df, col="label", data_folder=None):
|
56 |
+
"""add a column with unique labels in column col"""
|
57 |
+
df[col + "_labels"] = df[col].apply(
|
58 |
+
lambda x: list(np.unique(np.load(x if data_folder is None else data_folder / x))))
|
59 |
+
|
60 |
+
|
61 |
+
def dataset_add_mean_col(df, col="data", axis=(0), data_folder=None):
|
62 |
+
"""adds a column with mean"""
|
63 |
+
df[col + "_mean"] = df[col].apply(
|
64 |
+
lambda x: np.mean(np.load(x if data_folder is None else data_folder / x), axis=axis))
|
65 |
+
|
66 |
+
|
67 |
+
def dataset_add_median_col(df, col="data", axis=(0), data_folder=None):
|
68 |
+
"""adds a column with median"""
|
69 |
+
df[col + "_median"] = df[col].apply(
|
70 |
+
lambda x: np.median(np.load(x if data_folder is None else data_folder / x), axis=axis))
|
71 |
+
|
72 |
+
|
73 |
+
def dataset_add_std_col(df, col="data", axis=(0), data_folder=None):
|
74 |
+
"""adds a column with mean"""
|
75 |
+
df[col + "_std"] = df[col].apply(
|
76 |
+
lambda x: np.std(np.load(x if data_folder is None else data_folder / x), axis=axis))
|
77 |
+
|
78 |
+
|
79 |
+
def dataset_add_iqr_col(df, col="data", axis=(0), data_folder=None):
|
80 |
+
"""adds a column with mean"""
|
81 |
+
df[col + "_iqr"] = df[col].apply(lambda x: iqr(np.load(x if data_folder is None else data_folder / x), axis=axis))
|
82 |
+
|
83 |
+
|
84 |
+
def dataset_get_stats(df, col="data", median=False):
|
85 |
+
"""creates weighted means and stds from mean, std and length cols of the df"""
|
86 |
+
mean = np.average(np.stack(df[col + ("_median" if median is True else "_mean")], axis=0), axis=0,
|
87 |
+
weights=np.array(df[col + "_length"]))
|
88 |
+
std = np.average(np.stack(df[col + ("_iqr" if median is True else "_std")], axis=0), axis=0,
|
89 |
+
weights=np.array(df[col + "_length"]))
|
90 |
+
return mean, std
|
91 |
+
|
92 |
+
|
93 |
+
def npys_to_memmap(npys, target_filename, delete_npys=False):
|
94 |
+
memmap = None
|
95 |
+
start = []
|
96 |
+
length = []
|
97 |
+
files = []
|
98 |
+
ids = []
|
99 |
+
|
100 |
+
for idx, npy in enumerate(npys):
|
101 |
+
data = np.load(npy)
|
102 |
+
if memmap is None:
|
103 |
+
memmap = np.memmap(target_filename, dtype=data.dtype, mode='w+', shape=data.shape)
|
104 |
+
start.append(0)
|
105 |
+
length.append(data.shape[0])
|
106 |
+
else:
|
107 |
+
start.append(start[-1] + length[-1])
|
108 |
+
length.append(data.shape[0])
|
109 |
+
memmap = np.memmap(target_filename, dtype=data.dtype, mode='r+',
|
110 |
+
shape=tuple([start[-1] + length[-1]] + [l for l in data.shape[1:]]))
|
111 |
+
|
112 |
+
ids.append(idx)
|
113 |
+
memmap[start[-1]:start[-1] + length[-1]] = data[:]
|
114 |
+
memmap.flush()
|
115 |
+
if delete_npys is True:
|
116 |
+
npy.unlink()
|
117 |
+
del memmap
|
118 |
+
|
119 |
+
np.savez(target_filename.parent / (target_filename.stem + "_meta.npz"), start=start, length=length,
|
120 |
+
shape=[start[-1] + length[-1]] + [l for l in data.shape[1:]], dtype=data.dtype)
|
121 |
+
|
122 |
+
|
123 |
+
def reformat_as_memmap(df, target_filename, data_folder=None, annotation=False, delete_npys=False):
|
124 |
+
npys_data = []
|
125 |
+
npys_label = []
|
126 |
+
|
127 |
+
for id, row in df.iterrows():
|
128 |
+
npys_data.append(data_folder / row["data"] if data_folder is not None else row["data"])
|
129 |
+
if annotation:
|
130 |
+
npys_label.append(data_folder / row["label"] if data_folder is not None else row["label"])
|
131 |
+
|
132 |
+
npys_to_memmap(npys_data, target_filename, delete_npys=delete_npys)
|
133 |
+
if annotation:
|
134 |
+
npys_to_memmap(npys_label, target_filename.parent / (target_filename.stem + "_label.npy"),
|
135 |
+
delete_npys=delete_npys)
|
136 |
+
|
137 |
+
# replace data(filename) by integer
|
138 |
+
df_mapped = df.copy()
|
139 |
+
df_mapped["data_original"] = df_mapped.data
|
140 |
+
df_mapped["data"] = np.arange(len(df_mapped))
|
141 |
+
df_mapped.to_pickle(target_filename.parent / ("df_" + target_filename.stem + ".pkl"))
|
142 |
+
return df_mapped
|
143 |
+
|
144 |
+
|
145 |
+
# TimeseriesDatasetCrops
|
146 |
+
|
147 |
+
class TimeseriesDatasetCrops(torch.utils.data.Dataset):
|
148 |
+
"""timeseries dataset with partial crops."""
|
149 |
+
|
150 |
+
def __init__(self, df, output_size, chunk_length, min_chunk_length, memmap_filename=None, npy_data=None,
|
151 |
+
random_crop=True, data_folder=None, num_classes=2, copies=0, col_lbl="label", stride=None, start_idx=0,
|
152 |
+
annotation=False, transforms=None):
|
153 |
+
"""
|
154 |
+
accepts three kinds of input:
|
155 |
+
1) filenames pointing to aligned numpy arrays [timesteps,channels,...] for data and either integer labels or filename pointing to numpy arrays[timesteps,...] e.g. for annotations
|
156 |
+
2) memmap_filename to memmap for data [concatenated,...] and labels- label column in df corresponds to index in this memmap
|
157 |
+
3) npy_data [samples,ts,...] (either path or np.array directly- also supporting variable length input) - label column in df corresponds to sampleid
|
158 |
+
|
159 |
+
transforms: list of callables (transformations) (applied in the specified order i.e. leftmost element first)
|
160 |
+
"""
|
161 |
+
if transforms is None:
|
162 |
+
transforms = []
|
163 |
+
assert not ((memmap_filename is not None) and (npy_data is not None))
|
164 |
+
# require integer entries if using memmap or npy
|
165 |
+
assert (memmap_filename is None and npy_data is None) or df.data.dtype == np.int64
|
166 |
+
|
167 |
+
self.timeseries_df = df
|
168 |
+
self.output_size = output_size
|
169 |
+
self.data_folder = data_folder
|
170 |
+
self.transforms = transforms
|
171 |
+
self.annotation = annotation
|
172 |
+
self.col_lbl = col_lbl
|
173 |
+
|
174 |
+
self.c = num_classes
|
175 |
+
|
176 |
+
self.mode = "files"
|
177 |
+
self.memmap_filename = memmap_filename
|
178 |
+
if memmap_filename is not None:
|
179 |
+
self.mode = "memmap"
|
180 |
+
memmap_meta = np.load(memmap_filename.parent / (memmap_filename.stem + "_meta.npz"))
|
181 |
+
self.memmap_start = memmap_meta["start"]
|
182 |
+
self.memmap_shape = tuple(memmap_meta["shape"])
|
183 |
+
self.memmap_length = memmap_meta["length"]
|
184 |
+
self.memmap_dtype = np.dtype(str(memmap_meta["dtype"]))
|
185 |
+
self.memmap_file_process_dict = {}
|
186 |
+
if annotation:
|
187 |
+
memmap_meta_label = np.load(memmap_filename.parent / (memmap_filename.stem + "_label_meta.npz"))
|
188 |
+
self.memmap_filename_label = memmap_filename.parent / (memmap_filename.stem + "_label.npy")
|
189 |
+
self.memmap_shape_label = tuple(memmap_meta_label["shape"])
|
190 |
+
self.memmap_file_process_dict_label = {}
|
191 |
+
self.memmap_dtype_label = np.dtype(str(memmap_meta_label["dtype"]))
|
192 |
+
elif npy_data is not None:
|
193 |
+
self.mode = "npy"
|
194 |
+
if isinstance(npy_data, np.ndarray) or isinstance(npy_data, list):
|
195 |
+
self.npy_data = np.array(npy_data)
|
196 |
+
assert (annotation is False)
|
197 |
+
else:
|
198 |
+
self.npy_data = np.load(npy_data)
|
199 |
+
if annotation:
|
200 |
+
self.npy_data_label = np.load(npy_data.parent / (npy_data.stem + "_label.npy"))
|
201 |
+
|
202 |
+
self.random_crop = random_crop
|
203 |
+
|
204 |
+
self.df_idx_mapping = []
|
205 |
+
self.start_idx_mapping = []
|
206 |
+
self.end_idx_mapping = []
|
207 |
+
|
208 |
+
for df_idx, (id, row) in enumerate(df.iterrows()):
|
209 |
+
if self.mode == "files":
|
210 |
+
data_length = row["data_length"]
|
211 |
+
elif self.mode == "memmap":
|
212 |
+
data_length = self.memmap_length[row["data"]]
|
213 |
+
else: # npy
|
214 |
+
data_length = len(self.npy_data[row["data"]])
|
215 |
+
|
216 |
+
if chunk_length == 0: # do not split
|
217 |
+
idx_start = [start_idx]
|
218 |
+
idx_end = [data_length]
|
219 |
+
else:
|
220 |
+
idx_start = list(range(start_idx, data_length, chunk_length if stride is None else stride))
|
221 |
+
idx_end = [min(l + chunk_length, data_length) for l in idx_start]
|
222 |
+
|
223 |
+
# remove final chunk(s) if too short
|
224 |
+
for i in range(len(idx_start)):
|
225 |
+
if idx_end[i] - idx_start[i] < min_chunk_length:
|
226 |
+
del idx_start[i:]
|
227 |
+
del idx_end[i:]
|
228 |
+
break
|
229 |
+
# append to lists
|
230 |
+
for _ in range(copies + 1):
|
231 |
+
for i_s, i_e in zip(idx_start, idx_end):
|
232 |
+
self.df_idx_mapping.append(df_idx)
|
233 |
+
self.start_idx_mapping.append(i_s)
|
234 |
+
self.end_idx_mapping.append(i_e)
|
235 |
+
|
236 |
+
def __len__(self):
|
237 |
+
return len(self.df_idx_mapping)
|
238 |
+
|
239 |
+
def __getitem__(self, idx):
|
240 |
+
df_idx = self.df_idx_mapping[idx]
|
241 |
+
start_idx = self.start_idx_mapping[idx]
|
242 |
+
end_idx = self.end_idx_mapping[idx]
|
243 |
+
# determine crop idxs
|
244 |
+
timesteps = end_idx - start_idx
|
245 |
+
assert (timesteps >= self.output_size)
|
246 |
+
if self.random_crop: # random crop
|
247 |
+
if timesteps == self.output_size:
|
248 |
+
start_idx_crop = start_idx
|
249 |
+
else:
|
250 |
+
start_idx_crop = start_idx + random.randint(0, timesteps - self.output_size - 1) # np.random.randint(0, timesteps - self.output_size)
|
251 |
+
else:
|
252 |
+
start_idx_crop = start_idx + (timesteps - self.output_size) // 2
|
253 |
+
end_idx_crop = start_idx_crop + self.output_size
|
254 |
+
|
255 |
+
# print(idx,start_idx,end_idx,start_idx_crop,end_idx_crop)
|
256 |
+
# load the actual data
|
257 |
+
if self.mode == "files": # from separate files
|
258 |
+
data_filename = self.timeseries_df.iloc[df_idx]["data"]
|
259 |
+
if self.data_folder is not None:
|
260 |
+
data_filename = self.data_folder / data_filename
|
261 |
+
data = np.load(data_filename)[
|
262 |
+
start_idx_crop:end_idx_crop] # data type has to be adjusted when saving to npy
|
263 |
+
|
264 |
+
ID = data_filename.stem
|
265 |
+
|
266 |
+
if self.annotation is True:
|
267 |
+
label_filename = self.timeseries_df.iloc[df_idx][self.col_lbl]
|
268 |
+
if self.data_folder is not None:
|
269 |
+
label_filename = self.data_folder / label_filename
|
270 |
+
label = np.load(label_filename)[
|
271 |
+
start_idx_crop:end_idx_crop] # data type has to be adjusted when saving to npy
|
272 |
+
else:
|
273 |
+
label = self.timeseries_df.iloc[df_idx][self.col_lbl] # input type has to be adjusted in the dataframe
|
274 |
+
elif self.mode == "memmap": # from one memmap file
|
275 |
+
ID = self.timeseries_df.iloc[df_idx]["data_original"].stem
|
276 |
+
memmap_idx = self.timeseries_df.iloc[df_idx][
|
277 |
+
"data"] # grab the actual index (Note the df to create the ds might be a subset of the original df used to create the memmap)
|
278 |
+
idx_offset = self.memmap_start[memmap_idx]
|
279 |
+
|
280 |
+
pid = os.getpid()
|
281 |
+
# print("idx",idx,"ID",ID,"idx_offset",idx_offset,"start_idx_crop",start_idx_crop,"df_idx", self.df_idx_mapping[idx],"pid",pid)
|
282 |
+
mem_file = self.memmap_file_process_dict.get(pid, None) # each process owns its handler.
|
283 |
+
if mem_file is None:
|
284 |
+
# print("memmap_shape", self.memmap_shape)
|
285 |
+
mem_file = np.memmap(self.memmap_filename, self.memmap_dtype, mode='r', shape=self.memmap_shape)
|
286 |
+
self.memmap_file_process_dict[pid] = mem_file
|
287 |
+
data = np.copy(mem_file[idx_offset + start_idx_crop: idx_offset + end_idx_crop])
|
288 |
+
# print(mem_file[idx_offset + start_idx_crop: idx_offset + end_idx_crop])
|
289 |
+
if self.annotation:
|
290 |
+
mem_file_label = self.memmap_file_process_dict_label.get(pid, None) # each process owns its handler.
|
291 |
+
if mem_file_label is None:
|
292 |
+
mem_file_label = np.memmap(self.memmap_filename_label, self.memmap_dtype, mode='r',
|
293 |
+
shape=self.memmap_shape_label)
|
294 |
+
self.memmap_file_process_dict_label[pid] = mem_file_label
|
295 |
+
label = np.copy(mem_file_label[idx_offset + start_idx_crop: idx_offset + end_idx_crop])
|
296 |
+
else:
|
297 |
+
label = self.timeseries_df.iloc[df_idx][self.col_lbl]
|
298 |
+
else: # single npy array
|
299 |
+
ID = self.timeseries_df.iloc[df_idx]["data"]
|
300 |
+
|
301 |
+
data = self.npy_data[ID][start_idx_crop:end_idx_crop]
|
302 |
+
|
303 |
+
if self.annotation:
|
304 |
+
label = self.npy_data_label[ID][start_idx_crop:end_idx_crop]
|
305 |
+
else:
|
306 |
+
label = self.timeseries_df.iloc[df_idx][self.col_lbl]
|
307 |
+
sample = {'data': data, 'label': label, 'ID': ID}
|
308 |
+
|
309 |
+
for t in self.transforms:
|
310 |
+
sample = t(sample)
|
311 |
+
|
312 |
+
return sample
|
313 |
+
|
314 |
+
def get_sampling_weights(self, class_weight_dict, length_weighting=False, group_by_col=None):
|
315 |
+
assert (self.annotation is False)
|
316 |
+
assert (length_weighting is False or group_by_col is None)
|
317 |
+
weights = np.zeros(len(self.df_idx_mapping), dtype=np.float32)
|
318 |
+
length_per_class = {}
|
319 |
+
length_per_group = {}
|
320 |
+
for iw, (i, s, e) in enumerate(zip(self.df_idx_mapping, self.start_idx_mapping, self.end_idx_mapping)):
|
321 |
+
label = self.timeseries_df.iloc[i][self.col_lbl]
|
322 |
+
weight = class_weight_dict[label]
|
323 |
+
if length_weighting:
|
324 |
+
if label in length_per_class.keys():
|
325 |
+
length_per_class[label] += e - s
|
326 |
+
else:
|
327 |
+
length_per_class[label] = e - s
|
328 |
+
if group_by_col is not None:
|
329 |
+
group = self.timeseries_df.iloc[i][group_by_col]
|
330 |
+
if group in length_per_group.keys():
|
331 |
+
length_per_group[group] += e - s
|
332 |
+
else:
|
333 |
+
length_per_group[group] = e - s
|
334 |
+
weights[iw] = weight
|
335 |
+
|
336 |
+
if length_weighting: # need second pass to properly take into account the total length per class
|
337 |
+
for iw, (i, s, e) in enumerate(zip(self.df_idx_mapping, self.start_idx_mapping, self.end_idx_mapping)):
|
338 |
+
label = self.timeseries_df.iloc[i][self.col_lbl]
|
339 |
+
weights[iw] = (e - s) / length_per_class[label] * weights[iw]
|
340 |
+
if group_by_col is not None:
|
341 |
+
for iw, (i, s, e) in enumerate(zip(self.df_idx_mapping, self.start_idx_mapping, self.end_idx_mapping)):
|
342 |
+
group = self.timeseries_df.iloc[i][group_by_col]
|
343 |
+
weights[iw] = (e - s) / length_per_group[group] * weights[iw]
|
344 |
+
|
345 |
+
weights = weights / np.min(weights) # normalize smallest weight to 1
|
346 |
+
return weights
|
347 |
+
|
348 |
+
def get_id_mapping(self):
|
349 |
+
return self.df_idx_mapping
|
350 |
+
|
351 |
+
|
352 |
+
class RandomCrop(object):
|
353 |
+
"""
|
354 |
+
Crop randomly the image in a sample (deprecated).
|
355 |
+
"""
|
356 |
+
|
357 |
+
def __init__(self, output_size, annotation=False):
|
358 |
+
self.output_size = output_size
|
359 |
+
self.annotation = annotation
|
360 |
+
|
361 |
+
def __call__(self, sample):
|
362 |
+
data, label, ID = sample['data'], sample['label'], sample['ID']
|
363 |
+
|
364 |
+
timesteps = len(data)
|
365 |
+
assert (timesteps >= self.output_size)
|
366 |
+
if timesteps == self.output_size:
|
367 |
+
start = 0
|
368 |
+
else:
|
369 |
+
start = random.randint(0, timesteps - self.output_size - 1) # np.random.randint(0, timesteps - self.output_size)
|
370 |
+
|
371 |
+
data = data[start: start + self.output_size]
|
372 |
+
if self.annotation:
|
373 |
+
label = label[start: start + self.output_size]
|
374 |
+
|
375 |
+
return {'data': data, 'label': label, "ID": ID}
|
376 |
+
|
377 |
+
|
378 |
+
class CenterCrop(object):
|
379 |
+
"""
|
380 |
+
Center crop the image in a sample (deprecated).
|
381 |
+
"""
|
382 |
+
|
383 |
+
def __init__(self, output_size, annotation=False):
|
384 |
+
self.output_size = output_size
|
385 |
+
self.annotation = annotation
|
386 |
+
|
387 |
+
def __call__(self, sample):
|
388 |
+
data, label, ID = sample['data'], sample['label'], sample['ID']
|
389 |
+
|
390 |
+
timesteps = len(data)
|
391 |
+
|
392 |
+
start = (timesteps - self.output_size) // 2
|
393 |
+
|
394 |
+
data = data[start: start + self.output_size]
|
395 |
+
if self.annotation:
|
396 |
+
label = label[start: start + self.output_size]
|
397 |
+
|
398 |
+
return {'data': data, 'label': label, "ID": ID}
|
399 |
+
|
400 |
+
|
401 |
+
class GaussianNoise(object):
|
402 |
+
"""
|
403 |
+
Add gaussian noise to sample.
|
404 |
+
"""
|
405 |
+
|
406 |
+
def __init__(self, scale=0.1):
|
407 |
+
self.scale = scale
|
408 |
+
|
409 |
+
def __call__(self, sample):
|
410 |
+
if self.scale == 0:
|
411 |
+
return sample
|
412 |
+
else:
|
413 |
+
data, label, ID = sample['data'], sample['label'], sample['ID']
|
414 |
+
data = data + np.reshape(np.array([random.gauss(0, self.scale) for _ in range(np.prod(data.shape))]),
|
415 |
+
data.shape) # np.random.normal(scale=self.scale,size=data.shape).astype(np.float32)
|
416 |
+
return {'data': data, 'label': label, "ID": ID}
|
417 |
+
|
418 |
+
|
419 |
+
class Rescale(object):
|
420 |
+
"""Rescale by factor.
|
421 |
+
"""
|
422 |
+
|
423 |
+
def __init__(self, scale=0.5, interpolation_order=3):
|
424 |
+
self.scale = scale
|
425 |
+
self.interpolation_order = interpolation_order
|
426 |
+
|
427 |
+
def __call__(self, sample):
|
428 |
+
if self.scale == 1:
|
429 |
+
return sample
|
430 |
+
else:
|
431 |
+
data, label, ID = sample['data'], sample['label'], sample['ID']
|
432 |
+
timesteps_new = int(self.scale * len(data))
|
433 |
+
data = transform.resize(data, (timesteps_new, data.shape[1]), order=self.interpolation_order).astype(
|
434 |
+
np.float32)
|
435 |
+
return {'data': data, 'label': label, "ID": ID}
|
436 |
+
|
437 |
+
|
438 |
+
class ToTensor(object):
|
439 |
+
"""Convert ndarrays in sample to Tensors."""
|
440 |
+
|
441 |
+
def __init__(self, transpose_data1d=True):
|
442 |
+
self.transpose_data1d = transpose_data1d
|
443 |
+
|
444 |
+
def __call__(self, sample):
|
445 |
+
def _to_tensor(data, transpose_data1d=False):
|
446 |
+
if (
|
447 |
+
len(data.shape) == 2 and transpose_data1d is True): # swap channel and time axis for direct application of pytorch's 1d convs
|
448 |
+
data = data.transpose((1, 0))
|
449 |
+
if isinstance(data, np.ndarray):
|
450 |
+
return torch.from_numpy(data)
|
451 |
+
else: # default_collate will take care of it
|
452 |
+
return data
|
453 |
+
|
454 |
+
data, label, ID = sample['data'], sample['label'], sample['ID']
|
455 |
+
|
456 |
+
if not isinstance(data, tuple):
|
457 |
+
data = _to_tensor(data, self.transpose_data1d)
|
458 |
+
else:
|
459 |
+
data = tuple(_to_tensor(x, self.transpose_data1d) for x in data)
|
460 |
+
|
461 |
+
if not isinstance(label, tuple):
|
462 |
+
label = _to_tensor(label)
|
463 |
+
else:
|
464 |
+
label = tuple(_to_tensor(x) for x in label)
|
465 |
+
|
466 |
+
return data, label # returning as a tuple (potentially of lists)
|
467 |
+
|
468 |
+
|
469 |
+
class Normalize(object):
|
470 |
+
"""
|
471 |
+
Normalize using given stats.
|
472 |
+
"""
|
473 |
+
|
474 |
+
def __init__(self, stats_mean, stats_std, input=True, channels=None):
|
475 |
+
if channels is None:
|
476 |
+
channels = []
|
477 |
+
self.stats_mean = np.expand_dims(stats_mean.astype(np.float32), axis=0) if stats_mean is not None else None
|
478 |
+
self.stats_std = np.expand_dims(stats_std.astype(np.float32), axis=0) + 1e-8 if stats_std is not None else None
|
479 |
+
self.input = input
|
480 |
+
if len(channels) > 0:
|
481 |
+
for i in range(len(stats_mean)):
|
482 |
+
if not (i in channels):
|
483 |
+
self.stats_mean[:, i] = 0
|
484 |
+
self.stats_std[:, i] = 1
|
485 |
+
|
486 |
+
def __call__(self, sample):
|
487 |
+
if self.input:
|
488 |
+
data = sample['data']
|
489 |
+
else:
|
490 |
+
data = sample['label']
|
491 |
+
|
492 |
+
if self.stats_mean is not None:
|
493 |
+
data = data - self.stats_mean
|
494 |
+
if self.stats_std is not None:
|
495 |
+
data = data / self.stats_std
|
496 |
+
|
497 |
+
if self.input:
|
498 |
+
return {'data': data, 'label': sample['label'], "ID": sample['ID']}
|
499 |
+
else:
|
500 |
+
return {'data': sample['data'], 'label': data, "ID": sample['ID']}
|
501 |
+
|
502 |
+
|
503 |
+
class ButterFilter(object):
|
504 |
+
"""
|
505 |
+
Normalize using given stats.
|
506 |
+
"""
|
507 |
+
|
508 |
+
def __init__(self, lowcut=50, highcut=50, fs=100, order=5, btype='band', forwardbackward=True, input=True):
|
509 |
+
self.filter = butter_filter(lowcut, highcut, fs, order, btype)
|
510 |
+
self.input = input
|
511 |
+
self.forwardbackward = forwardbackward
|
512 |
+
|
513 |
+
def __call__(self, sample):
|
514 |
+
if self.input:
|
515 |
+
data = sample['data']
|
516 |
+
else:
|
517 |
+
data = sample['label']
|
518 |
+
|
519 |
+
# check multiple axis
|
520 |
+
if self.forwardbackward:
|
521 |
+
data = sosfiltfilt(self.filter, data, axis=0)
|
522 |
+
else:
|
523 |
+
data = sosfilt(self.filter, data, axis=0)
|
524 |
+
|
525 |
+
if self.input:
|
526 |
+
return {'data': data, 'label': sample['label'], "ID": sample['ID']}
|
527 |
+
else:
|
528 |
+
return {'data': sample['data'], 'label': data, "ID": sample['ID']}
|
529 |
+
|
530 |
+
|
531 |
+
class ChannelFilter(object):
|
532 |
+
"""
|
533 |
+
Select certain channels.
|
534 |
+
"""
|
535 |
+
|
536 |
+
def __init__(self, channels=None, input=True):
|
537 |
+
if channels is None:
|
538 |
+
channels = [0]
|
539 |
+
self.channels = channels
|
540 |
+
self.input = input
|
541 |
+
|
542 |
+
def __call__(self, sample):
|
543 |
+
if self.input:
|
544 |
+
return {'data': sample['data'][:, self.channels], 'label': sample['label'], "ID": sample['ID']}
|
545 |
+
else:
|
546 |
+
return {'data': sample['data'], 'label': sample['label'][:, self.channels], "ID": sample['ID']}
|
547 |
+
|
548 |
+
|
549 |
+
class Transform(object):
|
550 |
+
"""
|
551 |
+
Transforms data using a given function i.e. data_new = func(data) for input is True else label_new = func(label)
|
552 |
+
"""
|
553 |
+
|
554 |
+
def __init__(self, func, input=False):
|
555 |
+
self.func = func
|
556 |
+
self.input = input
|
557 |
+
|
558 |
+
def __call__(self, sample):
|
559 |
+
if self.input:
|
560 |
+
return {'data': self.func(sample['data']), 'label': sample['label'], "ID": sample['ID']}
|
561 |
+
else:
|
562 |
+
return {'data': sample['data'], 'label': self.func(sample['label']), "ID": sample['ID']}
|
563 |
+
|
564 |
+
|
565 |
+
class TupleTransform(object):
|
566 |
+
"""
|
567 |
+
Transforms data using a given function (operating on both data and label and return a tuple) i.e. data_new, label_new = func(data_old, label_old)
|
568 |
+
"""
|
569 |
+
|
570 |
+
def __init__(self, func, input=False):
|
571 |
+
self.func = func
|
572 |
+
|
573 |
+
def __call__(self, sample):
|
574 |
+
data_new, label_new = self.func(sample['data'], sample['label'])
|
575 |
+
return {'data': data_new, 'label': label_new, "ID": sample['ID']}
|
576 |
+
|
577 |
+
|
578 |
+
# MIL and ensemble models
|
579 |
+
|
580 |
+
def aggregate_predictions(preds, targs=None, idmap=None, aggregate_fn=np.mean, verbose=True):
|
581 |
+
"""
|
582 |
+
aggregates potentially multiple predictions per sample (can also pass targs for convenience)
|
583 |
+
idmap: idmap as returned by TimeSeriesCropsDataset's get_id_mapping
|
584 |
+
preds: ordered predictions as returned by learn.get_preds()
|
585 |
+
aggregate_fn: function that is used to aggregate multiple predictions per sample (most commonly np.amax or np.mean)
|
586 |
+
"""
|
587 |
+
if idmap is not None and len(idmap) != len(np.unique(idmap)):
|
588 |
+
if verbose:
|
589 |
+
print("aggregating predictions...")
|
590 |
+
preds_aggregated = []
|
591 |
+
targs_aggregated = []
|
592 |
+
for i in np.unique(idmap):
|
593 |
+
preds_local = preds[np.where(idmap == i)[0]]
|
594 |
+
preds_aggregated.append(aggregate_fn(preds_local, axis=0))
|
595 |
+
if targs is not None:
|
596 |
+
targs_local = targs[np.where(idmap == i)[0]]
|
597 |
+
assert (np.all(targs_local == targs_local[0])) # all labels have to agree
|
598 |
+
targs_aggregated.append(targs_local[0])
|
599 |
+
if targs is None:
|
600 |
+
return np.array(preds_aggregated)
|
601 |
+
else:
|
602 |
+
return np.array(preds_aggregated), np.array(targs_aggregated)
|
603 |
+
else:
|
604 |
+
if targs is None:
|
605 |
+
return preds
|
606 |
+
else:
|
607 |
+
return preds, targs
|
608 |
+
|
609 |
+
|
610 |
+
class milwrapper(nn.Module):
|
611 |
+
def __init__(self, model, input_size, n, stride=None, softmax=True):
|
612 |
+
super().__init__()
|
613 |
+
self.n = n
|
614 |
+
self.input_size = input_size
|
615 |
+
self.model = model
|
616 |
+
self.softmax = softmax
|
617 |
+
self.stride = input_size if stride is None else stride
|
618 |
+
|
619 |
+
def forward(self, x):
|
620 |
+
# bs,ch,seq
|
621 |
+
for i in range(self.n):
|
622 |
+
pred_single = self.model(x[:, :, i * self.stride:i * self.stride + self.input_size])
|
623 |
+
pred_single = nn.functional.softmax(pred_single, dim=1)
|
624 |
+
if i == 0:
|
625 |
+
pred = pred_single
|
626 |
+
else:
|
627 |
+
pred += pred_single
|
628 |
+
return pred / self.n
|
629 |
+
|
630 |
+
|
631 |
+
class ensemblewrapper(nn.Module):
|
632 |
+
def __init__(self, model, checkpts):
|
633 |
+
super().__init__()
|
634 |
+
self.model = model
|
635 |
+
self.checkpts = checkpts
|
636 |
+
|
637 |
+
def forward(self, x):
|
638 |
+
# bs,ch,seq
|
639 |
+
for i, c in enumerate(self.checkpts):
|
640 |
+
state = torch.load(Path("./models/") / f'{c}.pth', map_location=x.device)
|
641 |
+
self.model.load_state_dict(state['model'], strict=True)
|
642 |
+
|
643 |
+
pred_single = self.model(x)
|
644 |
+
pred_single = nn.functional.softmax(pred_single, dim=1)
|
645 |
+
if (i == 0):
|
646 |
+
pred = pred_single
|
647 |
+
else:
|
648 |
+
pred += pred_single
|
649 |
+
return pred / len(self.checkpts)
|
utilities/utils.py
ADDED
@@ -0,0 +1,509 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import glob
|
3 |
+
import pickle
|
4 |
+
import pandas as pd
|
5 |
+
import numpy as np
|
6 |
+
from tqdm import tqdm
|
7 |
+
import wfdb
|
8 |
+
import ast
|
9 |
+
from sklearn.metrics import roc_auc_score, roc_curve
|
10 |
+
from sklearn.preprocessing import StandardScaler, MultiLabelBinarizer
|
11 |
+
|
12 |
+
|
13 |
+
# EVALUATION STUFF
|
14 |
+
def generate_results(idxs, y_true, y_pred, thresholds):
|
15 |
+
return evaluate_experiment(y_true[idxs], y_pred[idxs], thresholds)
|
16 |
+
|
17 |
+
|
18 |
+
def evaluate_experiment(y_true, y_pred, thresholds=None):
|
19 |
+
results = {}
|
20 |
+
|
21 |
+
if not thresholds is None:
|
22 |
+
# binary predictions
|
23 |
+
y_pred_binary = apply_thresholds(y_pred, thresholds)
|
24 |
+
# PhysioNet/CinC Challenges metrics
|
25 |
+
challenge_scores = challenge_metrics(y_true, y_pred_binary, beta1=2, beta2=2)
|
26 |
+
results['F_beta_macro'] = challenge_scores['F_beta_macro']
|
27 |
+
results['G_beta_macro'] = challenge_scores['G_beta_macro']
|
28 |
+
results['TP'] = challenge_scores['TP']
|
29 |
+
results['TN'] = challenge_scores['TN']
|
30 |
+
results['FP'] = challenge_scores['FP']
|
31 |
+
results['FN'] = challenge_scores['FN']
|
32 |
+
results['Accuracy'] = challenge_scores['Accuracy']
|
33 |
+
results['F1'] = challenge_scores['F1']
|
34 |
+
results['Precision'] = challenge_scores['Precision']
|
35 |
+
results['Recall'] = challenge_scores['Recall']
|
36 |
+
|
37 |
+
# label based metric
|
38 |
+
results['macro_auc'] = roc_auc_score(y_true, y_pred, average='macro')
|
39 |
+
|
40 |
+
df_result = pd.DataFrame(results, index=[0])
|
41 |
+
return df_result
|
42 |
+
|
43 |
+
|
44 |
+
def challenge_metrics(y_true, y_pred, beta1=2, beta2=2, single=False):
|
45 |
+
f_beta = 0
|
46 |
+
g_beta = 0
|
47 |
+
TP, FP, TN, FN = 0., 0., 0., 0.
|
48 |
+
Accuracy = 0
|
49 |
+
Precision = 0
|
50 |
+
Recall = 0
|
51 |
+
F1 = 0
|
52 |
+
|
53 |
+
if single: # if evaluating single class in case of threshold-optimization
|
54 |
+
sample_weights = np.ones(y_true.sum(axis=1).shape)
|
55 |
+
else:
|
56 |
+
sample_weights = y_true.sum(axis=1)
|
57 |
+
for classi in range(y_true.shape[1]):
|
58 |
+
y_truei, y_predi = y_true[:, classi], y_pred[:, classi]
|
59 |
+
TP, FP, TN, FN = 0., 0., 0., 0.
|
60 |
+
for i in range(len(y_predi)):
|
61 |
+
sample_weight = sample_weights[i]
|
62 |
+
if y_truei[i] == y_predi[i] == 1:
|
63 |
+
TP += 1. / sample_weight
|
64 |
+
if (y_predi[i] == 1) and (y_truei[i] != y_predi[i]):
|
65 |
+
FP += 1. / sample_weight
|
66 |
+
if y_truei[i] == y_predi[i] == 0:
|
67 |
+
TN += 1. / sample_weight
|
68 |
+
if (y_predi[i] == 0) and (y_truei[i] != y_predi[i]):
|
69 |
+
FN += 1. / sample_weight
|
70 |
+
f_beta_i = ((1 + beta1 ** 2) * TP) / ((1 + beta1 ** 2) * TP + FP + (beta1 ** 2) * FN)
|
71 |
+
g_beta_i = TP / (TP + FP + beta2 * FN)
|
72 |
+
|
73 |
+
f_beta += f_beta_i
|
74 |
+
g_beta += g_beta_i
|
75 |
+
|
76 |
+
Accuracy = (TP + TN) / (FP + TP + TN + FN)
|
77 |
+
# Precision = TP / (TP + FP)
|
78 |
+
# Recall = TP / (TP + FN)
|
79 |
+
# F1 = 2*(Precision * Recall) / (Precision + Recall)
|
80 |
+
F1 = 2 * TP / 2 * TP + FP + FN
|
81 |
+
|
82 |
+
return {'F_beta_macro': f_beta / y_true.shape[1], 'G_beta_macro': g_beta / y_true.shape[1], 'TP': TP, 'FP': FP,
|
83 |
+
'TN': TN, 'FN': FN, 'Accuracy': Accuracy, 'F1': F1, 'Precision': Precision, 'Recall': Recall}
|
84 |
+
|
85 |
+
|
86 |
+
def get_appropriate_bootstrap_samples(y_true, n_bootstraping_samples):
|
87 |
+
samples = []
|
88 |
+
while True:
|
89 |
+
ridxs = np.random.randint(0, len(y_true), len(y_true))
|
90 |
+
if y_true[ridxs].sum(axis=0).min() != 0:
|
91 |
+
samples.append(ridxs)
|
92 |
+
if len(samples) == n_bootstraping_samples:
|
93 |
+
break
|
94 |
+
return samples
|
95 |
+
|
96 |
+
|
97 |
+
def find_optimal_cutoff_threshold(target, predicted):
|
98 |
+
"""
|
99 |
+
Find the optimal probability cutoff point for a classification model related to event rate
|
100 |
+
"""
|
101 |
+
fpr, tpr, threshold = roc_curve(target, predicted)
|
102 |
+
optimal_idx = np.argmax(tpr - fpr)
|
103 |
+
optimal_threshold = threshold[optimal_idx]
|
104 |
+
return optimal_threshold
|
105 |
+
|
106 |
+
|
107 |
+
def find_optimal_cutoff_thresholds(y_true, y_pred):
|
108 |
+
return [find_optimal_cutoff_threshold(y_true[:, i], y_pred[:, i]) for i in range(y_true.shape[1])]
|
109 |
+
|
110 |
+
|
111 |
+
def find_optimal_cutoff_threshold_for_Gbeta(target, predicted, n_thresholds=100):
|
112 |
+
thresholds = np.linspace(0.00, 1, n_thresholds)
|
113 |
+
scores = [challenge_metrics(target, predicted > t, single=True)['G_beta_macro'] for t in thresholds]
|
114 |
+
optimal_idx = np.argmax(scores)
|
115 |
+
return thresholds[optimal_idx]
|
116 |
+
|
117 |
+
|
118 |
+
def find_optimal_cutoff_thresholds_for_Gbeta(y_true, y_pred):
|
119 |
+
print("optimize thresholds with respect to G_beta")
|
120 |
+
return [
|
121 |
+
find_optimal_cutoff_threshold_for_Gbeta(y_true[:, k][:, np.newaxis], y_pred[:, k][:, np.newaxis])
|
122 |
+
for k in tqdm(range(y_true.shape[1]))]
|
123 |
+
|
124 |
+
|
125 |
+
def apply_thresholds(preds, thresholds):
|
126 |
+
"""
|
127 |
+
apply class-wise thresholds to prediction score in order to get binary format.
|
128 |
+
BUT: if no score is above threshold, pick maximum. This is needed due to metric issues.
|
129 |
+
"""
|
130 |
+
tmp = []
|
131 |
+
for p in preds:
|
132 |
+
tmp_p = (p > thresholds).astype(int)
|
133 |
+
if np.sum(tmp_p) == 0:
|
134 |
+
tmp_p[np.argmax(p)] = 1
|
135 |
+
tmp.append(tmp_p)
|
136 |
+
tmp = np.array(tmp)
|
137 |
+
return tmp
|
138 |
+
|
139 |
+
|
140 |
+
# DATA PROCESSING STUFF
|
141 |
+
def load_dataset(path, sampling_rate, release=False):
|
142 |
+
if path.split('/')[-2] == 'ptbxl':
|
143 |
+
# load and convert annotation data
|
144 |
+
Y = pd.read_csv(path + 'ptbxl_database.csv', index_col='ecg_id')
|
145 |
+
Y.scp_codes = Y.scp_codes.apply(lambda x: ast.literal_eval(x))
|
146 |
+
|
147 |
+
# Load raw signal data
|
148 |
+
X = load_raw_data_ptbxl(Y, sampling_rate, path)
|
149 |
+
|
150 |
+
elif path.split('/')[-2] == 'ICBEB':
|
151 |
+
# load and convert annotation data
|
152 |
+
Y = pd.read_csv(path + 'icbeb_database.csv', index_col='ecg_id')
|
153 |
+
Y.scp_codes = Y.scp_codes.apply(lambda x: ast.literal_eval(x))
|
154 |
+
|
155 |
+
# Load raw signal data
|
156 |
+
X = load_raw_data_icbeb(Y, sampling_rate, path)
|
157 |
+
|
158 |
+
return X, Y
|
159 |
+
|
160 |
+
|
161 |
+
def load_raw_data_icbeb(df, sampling_rate, path):
|
162 |
+
if sampling_rate == 100:
|
163 |
+
if os.path.exists(path + 'raw100.npy'):
|
164 |
+
data = np.load(path + 'raw100.npy', allow_pickle=True)
|
165 |
+
else:
|
166 |
+
data = [wfdb.rdsamp(path + 'records100/' + str(f)) for f in tqdm(df.index)]
|
167 |
+
data = np.array([signal for signal, meta in data])
|
168 |
+
pickle.dump(data, open(path + 'raw100.npy', 'wb'), protocol=4)
|
169 |
+
elif sampling_rate == 500:
|
170 |
+
if os.path.exists(path + 'raw500.npy'):
|
171 |
+
data = np.load(path + 'raw500.npy', allow_pickle=True)
|
172 |
+
else:
|
173 |
+
data = [wfdb.rdsamp(path + 'records500/' + str(f)) for f in tqdm(df.index)]
|
174 |
+
data = np.array([signal for signal, meta in data])
|
175 |
+
pickle.dump(data, open(path + 'raw500.npy', 'wb'), protocol=4)
|
176 |
+
return data
|
177 |
+
|
178 |
+
|
179 |
+
def load_raw_data_ptbxl(df, sampling_rate, path):
|
180 |
+
if sampling_rate == 100:
|
181 |
+
if os.path.exists(path + 'raw100.npy'):
|
182 |
+
data = np.load(path + 'raw100.npy', allow_pickle=True)
|
183 |
+
else:
|
184 |
+
data = [wfdb.rdsamp(path + f) for f in tqdm(df.filename_lr)]
|
185 |
+
data = np.array([signal for signal, meta in data])
|
186 |
+
pickle.dump(data, open(path + 'raw100.npy', 'wb'), protocol=4)
|
187 |
+
elif sampling_rate == 500:
|
188 |
+
if os.path.exists(path + 'raw500.npy'):
|
189 |
+
data = np.load(path + 'raw500.npy', allow_pickle=True)
|
190 |
+
else:
|
191 |
+
data = [wfdb.rdsamp(path + f) for f in tqdm(df.filename_hr)]
|
192 |
+
data = np.array([signal for signal, meta in data])
|
193 |
+
pickle.dump(data, open(path + 'raw500.npy', 'wb'), protocol=4)
|
194 |
+
return data
|
195 |
+
|
196 |
+
|
197 |
+
def compute_label_aggregations(df, folder, ctype):
|
198 |
+
df['scp_codes_len'] = df.scp_codes.apply(lambda x: len(x))
|
199 |
+
|
200 |
+
aggregation_df = pd.read_csv(folder + 'scp_statements.csv', index_col=0)
|
201 |
+
|
202 |
+
if ctype in ['diagnostic', 'subdiagnostic', 'superdiagnostic']:
|
203 |
+
|
204 |
+
def aggregate_all_diagnostic(y_dic):
|
205 |
+
tmp = []
|
206 |
+
for key in y_dic.keys():
|
207 |
+
if key in diag_agg_df.index:
|
208 |
+
tmp.append(key)
|
209 |
+
return list(set(tmp))
|
210 |
+
|
211 |
+
def aggregate_subdiagnostic(y_dic):
|
212 |
+
tmp = []
|
213 |
+
for key in y_dic.keys():
|
214 |
+
if key in diag_agg_df.index:
|
215 |
+
c = diag_agg_df.loc[key].diagnostic_subclass
|
216 |
+
if str(c) != 'nan':
|
217 |
+
tmp.append(c)
|
218 |
+
return list(set(tmp))
|
219 |
+
|
220 |
+
def aggregate_diagnostic(y_dic):
|
221 |
+
tmp = []
|
222 |
+
for key in y_dic.keys():
|
223 |
+
if key in diag_agg_df.index:
|
224 |
+
c = diag_agg_df.loc[key].diagnostic_class
|
225 |
+
if str(c) != 'nan':
|
226 |
+
tmp.append(c)
|
227 |
+
return list(set(tmp))
|
228 |
+
|
229 |
+
diag_agg_df = aggregation_df[aggregation_df.diagnostic == 1.0]
|
230 |
+
if ctype == 'diagnostic':
|
231 |
+
df['diagnostic'] = df.scp_codes.apply(aggregate_all_diagnostic)
|
232 |
+
df['diagnostic_len'] = df.diagnostic.apply(lambda x: len(x))
|
233 |
+
elif ctype == 'subdiagnostic':
|
234 |
+
df['subdiagnostic'] = df.scp_codes.apply(aggregate_subdiagnostic)
|
235 |
+
df['subdiagnostic_len'] = df.subdiagnostic.apply(lambda x: len(x))
|
236 |
+
elif ctype == 'superdiagnostic':
|
237 |
+
df['superdiagnostic'] = df.scp_codes.apply(aggregate_diagnostic)
|
238 |
+
df['superdiagnostic_len'] = df.superdiagnostic.apply(lambda x: len(x))
|
239 |
+
elif ctype == 'form':
|
240 |
+
form_agg_df = aggregation_df[aggregation_df.form == 1.0]
|
241 |
+
|
242 |
+
def aggregate_form(y_dic):
|
243 |
+
tmp = []
|
244 |
+
for key in y_dic.keys():
|
245 |
+
if key in form_agg_df.index:
|
246 |
+
c = key
|
247 |
+
if str(c) != 'nan':
|
248 |
+
tmp.append(c)
|
249 |
+
return list(set(tmp))
|
250 |
+
|
251 |
+
df['form'] = df.scp_codes.apply(aggregate_form)
|
252 |
+
df['form_len'] = df.form.apply(lambda x: len(x))
|
253 |
+
elif ctype == 'rhythm':
|
254 |
+
rhythm_agg_df = aggregation_df[aggregation_df.rhythm == 1.0]
|
255 |
+
|
256 |
+
def aggregate_rhythm(y_dic):
|
257 |
+
tmp = []
|
258 |
+
for key in y_dic.keys():
|
259 |
+
if key in rhythm_agg_df.index:
|
260 |
+
c = key
|
261 |
+
if str(c) != 'nan':
|
262 |
+
tmp.append(c)
|
263 |
+
return list(set(tmp))
|
264 |
+
|
265 |
+
df['rhythm'] = df.scp_codes.apply(aggregate_rhythm)
|
266 |
+
df['rhythm_len'] = df.rhythm.apply(lambda x: len(x))
|
267 |
+
elif ctype == 'all':
|
268 |
+
df['all_scp'] = df.scp_codes.apply(lambda x: list(set(x.keys())))
|
269 |
+
|
270 |
+
return df
|
271 |
+
|
272 |
+
|
273 |
+
def select_data(XX, YY, ctype, min_samples, output_folder):
|
274 |
+
# convert multi_label to multi-hot
|
275 |
+
mlb = MultiLabelBinarizer()
|
276 |
+
|
277 |
+
if ctype == 'diagnostic':
|
278 |
+
X = XX[YY.diagnostic_len > 0]
|
279 |
+
Y = YY[YY.diagnostic_len > 0]
|
280 |
+
mlb.fit(Y.diagnostic.values)
|
281 |
+
y = mlb.transform(Y.diagnostic.values)
|
282 |
+
elif ctype == 'subdiagnostic':
|
283 |
+
counts = pd.Series(np.concatenate(YY.subdiagnostic.values)).value_counts()
|
284 |
+
counts = counts[counts > min_samples]
|
285 |
+
YY.subdiagnostic = YY.subdiagnostic.apply(lambda x: list(set(x).intersection(set(counts.index.values))))
|
286 |
+
YY['subdiagnostic_len'] = YY.subdiagnostic.apply(lambda x: len(x))
|
287 |
+
X = XX[YY.subdiagnostic_len > 0]
|
288 |
+
Y = YY[YY.subdiagnostic_len > 0]
|
289 |
+
mlb.fit(Y.subdiagnostic.values)
|
290 |
+
y = mlb.transform(Y.subdiagnostic.values)
|
291 |
+
elif ctype == 'superdiagnostic':
|
292 |
+
counts = pd.Series(np.concatenate(YY.superdiagnostic.values)).value_counts()
|
293 |
+
counts = counts[counts > min_samples]
|
294 |
+
YY.superdiagnostic = YY.superdiagnostic.apply(lambda x: list(set(x).intersection(set(counts.index.values))))
|
295 |
+
YY['superdiagnostic_len'] = YY.superdiagnostic.apply(lambda x: len(x))
|
296 |
+
X = XX[YY.superdiagnostic_len > 0]
|
297 |
+
Y = YY[YY.superdiagnostic_len > 0]
|
298 |
+
mlb.fit(Y.superdiagnostic.values)
|
299 |
+
y = mlb.transform(Y.superdiagnostic.values)
|
300 |
+
elif ctype == 'form':
|
301 |
+
# filter
|
302 |
+
counts = pd.Series(np.concatenate(YY.form.values)).value_counts()
|
303 |
+
counts = counts[counts > min_samples]
|
304 |
+
YY.form = YY.form.apply(lambda x: list(set(x).intersection(set(counts.index.values))))
|
305 |
+
YY['form_len'] = YY.form.apply(lambda x: len(x))
|
306 |
+
# select
|
307 |
+
X = XX[YY.form_len > 0]
|
308 |
+
Y = YY[YY.form_len > 0]
|
309 |
+
mlb.fit(Y.form.values)
|
310 |
+
y = mlb.transform(Y.form.values)
|
311 |
+
elif ctype == 'rhythm':
|
312 |
+
# filter
|
313 |
+
counts = pd.Series(np.concatenate(YY.rhythm.values)).value_counts()
|
314 |
+
counts = counts[counts > min_samples]
|
315 |
+
YY.rhythm = YY.rhythm.apply(lambda x: list(set(x).intersection(set(counts.index.values))))
|
316 |
+
YY['rhythm_len'] = YY.rhythm.apply(lambda x: len(x))
|
317 |
+
# select
|
318 |
+
X = XX[YY.rhythm_len > 0]
|
319 |
+
Y = YY[YY.rhythm_len > 0]
|
320 |
+
mlb.fit(Y.rhythm.values)
|
321 |
+
y = mlb.transform(Y.rhythm.values)
|
322 |
+
elif ctype == 'all':
|
323 |
+
# filter
|
324 |
+
counts = pd.Series(np.concatenate(YY.all_scp.values)).value_counts()
|
325 |
+
counts = counts[counts > min_samples]
|
326 |
+
YY.all_scp = YY.all_scp.apply(lambda x: list(set(x).intersection(set(counts.index.values))))
|
327 |
+
YY['all_scp_len'] = YY.all_scp.apply(lambda x: len(x))
|
328 |
+
# select
|
329 |
+
X = XX[YY.all_scp_len > 0]
|
330 |
+
Y = YY[YY.all_scp_len > 0]
|
331 |
+
mlb.fit(Y.all_scp.values)
|
332 |
+
y = mlb.transform(Y.all_scp.values)
|
333 |
+
else:
|
334 |
+
pass
|
335 |
+
|
336 |
+
# save Label_Binarizer
|
337 |
+
with open(output_folder + 'mlb.pkl', 'wb') as tokenizer:
|
338 |
+
pickle.dump(mlb, tokenizer)
|
339 |
+
|
340 |
+
return X, Y, y, mlb
|
341 |
+
|
342 |
+
|
343 |
+
def preprocess_signals(X_train, X_validation, X_test, outputfolder):
|
344 |
+
# Standardize data such that mean 0 and variance 1
|
345 |
+
ss = StandardScaler()
|
346 |
+
ss.fit(np.vstack(X_train).flatten()[:, np.newaxis].astype(float))
|
347 |
+
|
348 |
+
# Save Standardize data
|
349 |
+
with open(outputfolder + 'standard_scaler.pkl', 'wb') as ss_file:
|
350 |
+
pickle.dump(ss, ss_file)
|
351 |
+
|
352 |
+
return apply_standardizer(X_train, ss), apply_standardizer(X_validation,
|
353 |
+
ss), apply_standardizer(
|
354 |
+
X_test, ss)
|
355 |
+
|
356 |
+
|
357 |
+
def apply_standardizer(X, ss):
|
358 |
+
X_tmp = []
|
359 |
+
for x in X:
|
360 |
+
x_shape = x.shape
|
361 |
+
X_tmp.append(ss.transform(x.flatten()[:, np.newaxis]).reshape(x_shape))
|
362 |
+
X_tmp = np.array(X_tmp)
|
363 |
+
return X_tmp
|
364 |
+
|
365 |
+
|
366 |
+
# DOCUMENTATION STUFF
|
367 |
+
|
368 |
+
def generate_ptbxl_summary_table(selection=None, folder='/output/'):
|
369 |
+
exps = ['exp0', 'exp1', 'exp1.1', 'exp1.1.1', 'exp2', 'exp3']
|
370 |
+
metrics = ['macro_auc', 'Accuracy', 'TP', 'TN', 'FP', 'FN', 'Precision', 'Recall', 'F1']
|
371 |
+
# 0 1 2 3 4 5 6 7 8
|
372 |
+
|
373 |
+
# get models
|
374 |
+
models = {}
|
375 |
+
for i, exp in enumerate(exps):
|
376 |
+
if selection is None:
|
377 |
+
exp_models = [m.split('/')[-1] for m in glob.glob(folder + str(exp) + '/models/*')]
|
378 |
+
else:
|
379 |
+
exp_models = selection
|
380 |
+
if i == 0:
|
381 |
+
models = set(exp_models)
|
382 |
+
else:
|
383 |
+
models = models.union(set(exp_models))
|
384 |
+
|
385 |
+
results_dic = {'Method': [],
|
386 |
+
'exp0_macro_auc': [],
|
387 |
+
'exp1_macro_auc': [],
|
388 |
+
'exp1.1_macro_auc': [],
|
389 |
+
'exp1.1.1_macro_auc': [],
|
390 |
+
'exp2_macro_auc': [],
|
391 |
+
'exp3_macro_auc': [],
|
392 |
+
'exp0_Accuracy': [],
|
393 |
+
'exp1_Accuracy': [],
|
394 |
+
'exp1.1_Accuracy': [],
|
395 |
+
'exp1.1.1_Accuracy': [],
|
396 |
+
'exp2_Accuracy': [],
|
397 |
+
'exp3_Accuracy': [],
|
398 |
+
'exp0_F1': [],
|
399 |
+
'exp1_F1': [],
|
400 |
+
'exp1.1_F1': [],
|
401 |
+
'exp1.1.1_F1': [],
|
402 |
+
'exp2_F1': [],
|
403 |
+
'exp3_F1': [],
|
404 |
+
'exp0_Precision': [],
|
405 |
+
'exp1_Precision': [],
|
406 |
+
'exp1.1_Precision': [],
|
407 |
+
'exp1.1.1_Precision': [],
|
408 |
+
'exp2_Precision': [],
|
409 |
+
'exp3_Precision': [],
|
410 |
+
'exp0_Recall': [],
|
411 |
+
'exp1_Recall': [],
|
412 |
+
'exp1.1_Recall': [],
|
413 |
+
'exp1.1.1_Recall': [],
|
414 |
+
'exp2_Recall': [],
|
415 |
+
'exp3_Recall': [],
|
416 |
+
'exp0_TP': [],
|
417 |
+
'exp1_TP': [],
|
418 |
+
'exp1.1_TP': [],
|
419 |
+
'exp1.1.1_TP': [],
|
420 |
+
'exp2_TP': [],
|
421 |
+
'exp3_TP': [],
|
422 |
+
'exp0_TN': [],
|
423 |
+
'exp1_TN': [],
|
424 |
+
'exp1.1_TN': [],
|
425 |
+
'exp1.1.1_TN': [],
|
426 |
+
'exp2_TN': [],
|
427 |
+
'exp3_TN': [],
|
428 |
+
'exp0_FP': [],
|
429 |
+
'exp1_FP': [],
|
430 |
+
'exp1.1_FP': [],
|
431 |
+
'exp1.1.1_FP': [],
|
432 |
+
'exp2_FP': [],
|
433 |
+
'exp3_FP': [],
|
434 |
+
'exp0_FN': [],
|
435 |
+
'exp1_FN': [],
|
436 |
+
'exp1.1_FN': [],
|
437 |
+
'exp1.1.1_FN': [],
|
438 |
+
'exp2_FN': [],
|
439 |
+
'exp3_FN': []
|
440 |
+
}
|
441 |
+
|
442 |
+
for m in models:
|
443 |
+
results_dic['Method'].append(m)
|
444 |
+
|
445 |
+
for e in exps:
|
446 |
+
|
447 |
+
try:
|
448 |
+
me_res = pd.read_csv(folder + str(e) + '/models/' + str(m) + '/results/te_results.csv', index_col=0)
|
449 |
+
|
450 |
+
mean1 = me_res.loc['point'][metrics[0]]
|
451 |
+
unc1 = max(me_res.loc['upper'][metrics[0]] - me_res.loc['point'][metrics[0]],
|
452 |
+
me_res.loc['point'][metrics[0]] - me_res.loc['lower'][metrics[0]])
|
453 |
+
|
454 |
+
acc = me_res.loc['point'][metrics[1]]
|
455 |
+
f1 = me_res.loc['point'][metrics[8]]
|
456 |
+
precision = me_res.loc['point'][metrics[6]]
|
457 |
+
recall = me_res.loc['point'][metrics[7]]
|
458 |
+
tp = me_res.loc['point'][metrics[2]]
|
459 |
+
tn = me_res.loc['point'][metrics[3]]
|
460 |
+
fp = me_res.loc['point'][metrics[4]]
|
461 |
+
fn = me_res.loc['point'][metrics[5]]
|
462 |
+
|
463 |
+
results_dic[e + '_macro_auc'].append("%.3f(%.2d)" % (np.round(mean1, 3), int(unc1 * 1000)))
|
464 |
+
results_dic[e + '_Accuracy'].append("%.3f" % acc)
|
465 |
+
results_dic[e + '_F1'].append("%.3f" % f1)
|
466 |
+
results_dic[e + '_Precision'].append("%.3f" % precision)
|
467 |
+
results_dic[e + '_Recall'].append("%.3f" % recall)
|
468 |
+
results_dic[e + '_TP'].append("%.3f" % tp)
|
469 |
+
results_dic[e + '_TN'].append("%.3f" % tn)
|
470 |
+
results_dic[e + '_FP'].append("%.3f" % fp)
|
471 |
+
results_dic[e + '_FN'].append("%.3f" % fn)
|
472 |
+
|
473 |
+
except FileNotFoundError:
|
474 |
+
results_dic[e + '_macro_auc'].append("--")
|
475 |
+
results_dic[e + '_Accuracy'].append("--")
|
476 |
+
results_dic[e + '_F1'].append("--")
|
477 |
+
results_dic[e + '_Precision'].append("--")
|
478 |
+
results_dic[e + '_Recall'].append("--")
|
479 |
+
results_dic[e + '_TP'].append("--")
|
480 |
+
results_dic[e + '_TN'].append("--")
|
481 |
+
results_dic[e + '_FP'].append("--")
|
482 |
+
results_dic[e + '_FN'].append("--")
|
483 |
+
|
484 |
+
df = pd.DataFrame(results_dic)
|
485 |
+
df_index = df[df.Method.isin(['naive', 'ensemble'])]
|
486 |
+
df_rest = df[~df.Method.isin(['naive', 'ensemble'])]
|
487 |
+
df = pd.concat([df_rest, df_index])
|
488 |
+
df.to_csv(folder + 'results_ptbxl.csv')
|
489 |
+
|
490 |
+
titles = [
|
491 |
+
'### 1. PTB-XL: all statements',
|
492 |
+
'### 2. PTB-XL: diagnostic statements',
|
493 |
+
'### 3. PTB-XL: Diagnostic subclasses',
|
494 |
+
'### 4. PTB-XL: Diagnostic superclasses',
|
495 |
+
'### 5. PTB-XL: Form statements',
|
496 |
+
'### 6. PTB-XL: Rhythm statements'
|
497 |
+
]
|
498 |
+
|
499 |
+
# helper output function for markdown tables
|
500 |
+
our_work = 'https://arxiv.org/abs/2004.13701'
|
501 |
+
our_repo = 'https://github.com/helme/ecg_ptbxl_benchmarking/'
|
502 |
+
md_source = ''
|
503 |
+
for i, e in enumerate(exps):
|
504 |
+
md_source += '\n ' + titles[i] + ' \n \n'
|
505 |
+
md_source += '| Model | AUC |\n'
|
506 |
+
|
507 |
+
for row in df_rest[['Method', e + '_AUC']].sort_values(e + '_AUC', ascending=False).values:
|
508 |
+
md_source += '| ' + row[0].replace('fastai_', '') + ' | ' + row[1] + ' |\n'
|
509 |
+
print(md_source)
|