├── .gitignore
├── .pre-commit-config.yaml
├── LICENSE
├── README.md
├── core
├── Conv_AE.py
├── Isolation_Forest.py
├── LSTM_AE.py
├── LSTM_VAE.py
├── MSCRED.py
├── MSET.py
├── Vanilla_AE.py
├── Vanilla_LSTM.py
├── __init.py__
├── metrics.py
├── t2.py
└── utils.py
├── data
├── README.md
├── anomaly-free
│ └── anomaly-free.csv
├── other
│ ├── 1.csv
│ ├── 10.csv
│ ├── 11.csv
│ ├── 12.csv
│ ├── 13.csv
│ ├── 14.csv
│ ├── 2.csv
│ ├── 3.csv
│ ├── 4.csv
│ ├── 5.csv
│ ├── 6.csv
│ ├── 7.csv
│ ├── 8.csv
│ └── 9.csv
├── valve1
│ ├── 0.csv
│ ├── 1.csv
│ ├── 10.csv
│ ├── 11.csv
│ ├── 12.csv
│ ├── 13.csv
│ ├── 14.csv
│ ├── 15.csv
│ ├── 2.csv
│ ├── 3.csv
│ ├── 4.csv
│ ├── 5.csv
│ ├── 6.csv
│ ├── 7.csv
│ ├── 8.csv
│ └── 9.csv
└── valve2
│ ├── 0.csv
│ ├── 1.csv
│ ├── 2.csv
│ └── 3.csv
├── docs
├── contributing.md
└── pictures
│ ├── nab-metric.jpg
│ ├── skab.png
│ └── testbed.png
├── notebooks
├── ArimaFD.ipynb
├── Conv_AE.ipynb
├── LSTM_AE.ipynb
├── MSET.ipynb
├── README.md
├── Vanilla_AE.ipynb
├── Vanilla_LSTM.ipynb
├── isolation_forest.ipynb
├── mscred.ipynb
├── t2_SKAB.ipynb
└── t2_with_q_SKAB.ipynb
├── poetry.lock
├── pyproject.toml
└── results
├── results-Arima_anomaly_detection.pkl
├── results-Conv_AE.pkl
├── results-Isolation_Forest.pkl
├── results-LSTM_AE.pkl
├── results-MSCRED.pkl
├── results-MSET.pkl
├── results-T2-q.pkl
├── results-T2.pkl
├── results-Vanilla_AE.pkl
└── results-Vanilla_LSTM.pkl
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | *.pickle
3 |
4 | # Byte-compiled / optimized / DLL files
5 | __pycache__/
6 | algorithms/__pycache__/
7 | notebooks/__pycache__/
8 | *.py[cod]
9 | *$py.class
10 |
11 | # Distribution / packaging
12 | .Python
13 | build/
14 | develop-eggs/
15 | dist/
16 | downloads/
17 | eggs/
18 | .eggs/
19 | lib/
20 | lib64/
21 | parts/
22 | sdist/
23 | var/
24 | wheels/
25 | pip-wheel-metadata/
26 | share/python-wheels/
27 | *.egg-info/
28 | .installed.cfg
29 | *.egg
30 | MANIFEST
31 |
32 | # PyInstaller
33 | # Usually these files are written by a python script from a template
34 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
35 | *.manifest
36 | *.spec
37 |
38 | # Installer logs
39 | pip-log.txt
40 | pip-delete-this-directory.txt
41 |
42 | # Unit test / coverage reports
43 | htmlcov/
44 | .tox/
45 | .nox/
46 | .coverage
47 | .coverage.*
48 | .cache
49 | nosetests.xml
50 | coverage.xml
51 | *.cover
52 | *.py,cover
53 | .hypothesis/
54 | .pytest_cache/
55 |
56 | # Jupyter Notebook
57 | .ipynb_checkpoints
58 | notebooks/.ipynb_checkpoints
59 | algorithms/.ipynb_checkpoints
60 |
61 | # IPython
62 | profile_default/
63 | ipython_config.py
64 |
65 | # pyenv
66 | .python-version
67 |
68 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
69 | __pypackages__/
70 |
71 | # Environments
72 | .env
73 | .venv
74 | env/
75 | venv/
76 | ENV/
77 | env.bak/
78 | venv.bak/
79 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | # https://pre-commit.com
2 | exclude: 'examples|reports'
3 | repos:
4 | - repo: https://github.com/pre-commit/pre-commit-hooks
5 | rev: v4.5.0
6 | hooks:
7 | - id: debug-statements #Check for debugger imports and breakpoint() in python files
8 | - id: check-ast #Simply check whether files parse as valid python
9 | - id: fix-byte-order-marker #removes UTF-8 byte order marker
10 | - id: check-json
11 | - id: detect-private-key # detect-private-key is not in repo
12 | - id: check-yaml
13 | - id: check-added-large-files
14 | - id: check-shebang-scripts-are-executable
15 | - id: check-case-conflict #Check for files with names that would conflict on a case-insensitive filesystem like MacOS HFS+ or Windows FAT
16 | - id: end-of-file-fixer #Makes sure files end in a newline and only a newline
17 | - id: trailing-whitespace
18 | - id: mixed-line-ending
19 | - repo: https://github.com/astral-sh/ruff-pre-commit
20 | rev: v0.3.4
21 | hooks:
22 | - id: ruff
23 | args: [--fix, --exit-non-zero-on-fix, --line-length=79]
24 | types_or: [python, pyi, jupyter]
25 | - id: ruff-format
26 | args: [--line-length=79]
27 | types_or: [python, pyi, jupyter]
28 | - repo: https://github.com/pycqa/isort
29 | rev: 5.13.2
30 | hooks:
31 | - id: isort #isort is a pre-commit hook that runs to check for issues in imports and docstrings
32 | args: [
33 | "--profile", "black", "--filter-files",
34 | "-l", "79"
35 | ]
36 | - repo: https://github.com/asottile/blacken-docs
37 | rev: 1.16.0
38 | hooks:
39 | - id: blacken-docs #blacken-docs is a pre-commit hook that runs to check for issues in the docs
40 | additional_dependencies: [black]
41 | - repo: https://github.com/asottile/pyupgrade
42 | rev: v3.15.2
43 | hooks:
44 | - id: pyupgrade #pyupgrade is a pre-commit hook that runs to check for issues in the code
45 | args: [--py36-plus]
46 | - repo: local
47 | hooks:
48 | - id: mypy # mypy is a pre-commit hook that runs as a linter to check for type errors
49 | name: mypy
50 | entry: mypy --implicit-optional
51 | language: system
52 | types: [python]
53 | args: [
54 | "--ignore-missing-imports",
55 | "--explicit-package-bases",
56 | "--check-untyped-defs"
57 | ]
58 | stages:
59 | - "pre-push"
60 | - "pre-merge-commit"
61 | - repo: local
62 | hooks:
63 | - id: pytest-check
64 | name: pytest-check
65 | language: python
66 | types: [python]
67 | entry: pytest
68 | pass_filenames: false
69 | always_run: true
70 | args: [
71 | --doctest-modules,
72 | -o, addopts=""
73 | ]
74 | - repo: https://github.com/roy-ht/pre-commit-jupyter
75 | rev: v1.2.1
76 | hooks:
77 | - id: jupyter-notebook-cleanup
78 | args:
79 | - --remove-kernel-metadata
80 | - --pin-patterns
81 | - "[pin];[donotremove]"
82 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
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 |
635 | Copyright (C)
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 .
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 | Copyright (C)
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 | .
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 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 
2 |
3 | 🛠🛠🛠**The testbed is under repair right now. Unfortunately, we can't tell exactly when it will be ready and we be able to continue data collection. Information about it will be in the repository. Sorry for the delay.**
4 |
5 | ❗️❗️❗️The current version of SKAB (v0.9) contains 34 datasets with collective anomalies. But the update to v1.0 will contain 300+ additional files with point and collective anomalies. It will make SKAB one of the largest changepoint-containing benchmarks, especially in the technical field.
6 |
7 | ## About SKAB [](https://github.com/waico/SKAB/graphs/commit-activity) [](https://doi.org/10.34740/KAGGLE/DSV/1693952) [](https://www.gnu.org/licenses/gpl-3.0.html)
8 |
9 | We propose the [Skoltech](https://www.skoltech.ru/en) Anomaly Benchmark (SKAB) designed for evaluating the anomaly detection core. SKAB allows working with two main problems (there are two markups for anomalies):
10 |
11 | 1. Outlier detection (anomalies considered and marked up as single-point anomalies)
12 | 2. Changepoint detection (anomalies considered and marked up as collective anomalies)
13 |
14 | SKAB consists of the following artifacts:
15 |
16 | 1. [Datasets](#datasets)
17 | 2. [Proposed Leaderboard](#proposed-leaderboard) for outlier detection and changepoint detection problems
18 | 3. Python modules for algorithms’ evaluation (now evaluation modules are being imported from [TSAD](https://github.com/waico/tsad) framework, while the details regarding the evaluation process are presented [here](https://github.com/waico/tsad/blob/main/examples/Evaluating.ipynb))
19 | 4. Python [core](core/) with algorithms’ implementation
20 | 5. Python [notebooks](#notebooks) with anomaly detection pipeline implementation for various algorithms
21 |
22 | All the details about SKAB are presented in the following artifacts:
23 |
24 | - Position paper (*currently submitted for publication*)
25 | - Talk about the project: [English](https://youtu.be/hjzuKeNYUho) version and [Russian](https://www.youtube.com/watch?v=VLmmYGc4v2c) version
26 | - Slides about the project: [English](https://drive.google.com/open?id=1dHUevwPp6ftQCEKnRgB4KMp9oLBMSiDM) version and [Russian](https://drive.google.com/file/d/1gThPCNbEaIxhENLm-WTFGO_9PU1Wdwjq/view?usp=share_link) version
27 |
28 | ## Datasets
29 |
30 | The SKAB v0.9 corpus contains 35 individual data files in .csv format (datasets). The [data](data/) folder contains datasets from the benchmark. The structure of the data folder is presented in the [structure](./data/README.md) file. Each dataset represents a single experiment and contains a single anomaly. The datasets represent a multivariate time series collected from the sensors installed on the testbed. Columns in each data file are following:
31 |
32 | - `datetime` - Represents dates and times of the moment when the value is written to the database (YYYY-MM-DD hh:mm:ss)
33 | - `Accelerometer1RMS` - Shows a vibration acceleration (Amount of g units)
34 | - `Accelerometer2RMS` - Shows a vibration acceleration (Amount of g units)
35 | - `Current` - Shows the amperage on the electric motor (Ampere)
36 | - `Pressure` - Represents the pressure in the loop after the water pump (Bar)
37 | - `Temperature` - Shows the temperature of the engine body (The degree Celsius)
38 | - `Thermocouple` - Represents the temperature of the fluid in the circulation loop (The degree Celsius)
39 | - `Voltage` - Shows the voltage on the electric motor (Volt)
40 | - `RateRMS` - Represents the circulation flow rate of the fluid inside the loop (Liter per minute)
41 | - `anomaly` - Shows if the point is anomalous (0 or 1)
42 | - `changepoint` - Shows if the point is a changepoint for collective anomalies (0 or 1)
43 |
44 | Exploratory Data Analysis (EDA) for SKAB is presented [here (tbd)]. Russian version of EDA is available on [kaggle](https://www.kaggle.com/newintown/eda-example).
45 |
46 | ℹ️We have also made a *SKAB teaser* that is a small dataset collected separately but from the same testbed. SKAB teaser is made just for learning/teaching purposes and contains only 4 collective anomalies. All the information is available on [kaggle](https://www.kaggle.com/datasets/yuriykatser/skoltech-anomaly-benchmark-skab-teaser).
47 |
48 | ## Proposed Leaderboard
49 |
50 | This leaderboard shows performance of algorithms on test set, unlike leaderboard for SKAB v0.9 which evaluates both training and testing data all together. Moreover, the evaluated window of change points is to the right side of actual change point occurence which is in accordance with fact, that it should be impossible to capture event before it occurs. Lastly, the window size for the NAB detection algorithm is set to 60 seconds to reflect the dynamics of the transition as presented in the slides to enable detection of the start of the transition phase which is also marked as change-point.
51 |
52 | You can present and evaluate your algorithm using SKAB on [kaggle](https://www.kaggle.com/yuriykatser/skoltech-anomaly-benchmark-skab). Leaderboards are also available at paperswithcode.com: [CPD problem](https://paperswithcode.com/sota/change-point-detection-on-skab).
53 |
54 | Information about the metrics for anomaly detection and intuition behind the metrics selection can be found in [this](https://medium.com/@katser/a-review-of-anomaly-detection-metrics-with-a-lot-of-related-information-736d88774712) medium article.
55 |
56 | ### Outlier detection problem
57 |
58 | *Sorted by F1; for F1 bigger is better; both for FAR (False Alarm Rate) and MAR (Missing Alarm Rate) less is better*
59 | *Evaluated as binary classification problem.*
60 |
61 | | Algorithm | F1 | FAR, % | MAR, %
62 | |---|---|---|---
63 | |Perfect detector | 1 | 0 | 0
64 | |Conv-AE |0.78 | 13.55 | 28.02
65 | |MSET |0.78 | 39.73 | 14.13
66 | |T-squared+Q (PCA-based) | 0.76 | 26.62 | 24.92
67 | |LSTM-AE |0.74 | 29.96 | 25.92
68 | |T-squared | 0.66 | 19.21 | 42.6
69 | |LSTM-VAE | 0.56 | 9.13 | 55.03
70 | |Vanilla LSTM | 0.54 | 12.54 | 59.53
71 | |MSCRED | 0.36 | 49.94 | 69.88
72 | |Vanilla AE | 0.39 | 2.59 | 75.15
73 | |Isolation forest | 0.29 | 2.56 | 82.89
74 | |Null detector | 0 | 0 | 100
75 |
76 | ### Changepoint detection problem
77 |
78 | *Sorted by NAB (standard); for NAB (standard), NAB (LowFP), NAB (LowFN) bigger is better, for Number of Missed CPs, Number of FPs lower is better*
79 | *The current leaderboard is obtained with the window size for the NAB detection algorithm equal to 60 sec and to the right side of true change point.*
80 |
81 | | Algorithm | NAB (standard) | NAB (LowFP) | NAB (LowFN) | Number of Missed CPs | Number of FPs
82 | |---|---|---|---|---|---
83 | |Perfect detector | 100 | 100 | 100 | 0 | 0
84 | |MSCRED | 32.42 | 16.53 | 40.28 | 55 | 342
85 | |Isolation forest | 26.16 | 19.5 | 30.82 | 76 | 135
86 | |T-squared+Q (PCA-based) | 25.35 | 14.51 | 31.33 | 72 | 232
87 | |Conv-AE | 23.61 | 21.54 | 27.55 | 82 | 23
88 | |LSTM-AE | 23.51 | 20.11 | 25.91 | 88 | 69
89 | |T-squared | 19.54 | 10.2 | 24.31 | 70 | 106
90 | |MSET | 13.84 | 10.22 | 17.37 | 96 | 66
91 | |Vanilla AE | 11.41 | 6.53 | 13.91 | 103 | 106
92 | |Vanilla LSTM | 11.31 | -3.8 | 17.25 | 90 | 342
93 | |ArimaFD | -0.09 | -0.17 | -0.06 | 127 | 2
94 | |Null detector | 0 | 0 | 0 | - | -
95 |
96 | ## Notebooks
97 |
98 | The [notebooks](notebooks/) folder contains jupyter notebooks with the code for the proposed leaderboard results reproducing. We have calculated the results for following commonly known anomaly detection algorithms:
99 |
100 | - Isolation forest - *Outlier detection algorithm based on Random forest concept*
101 | - Vanilla LSTM - *NN with LSTM layer*
102 | - Vanilla AE - *Feed-Forward Autoencoder*
103 | - LSTM-AE - *LSTM Autoencoder*
104 | - LSTM-VAE - *LSTM Variational Autoencoder*
105 | - Conv-AE - *Convolutional Autoencoder*
106 | - MSCRED - *Multi-Scale Convolutional Recurrent Encoder-Decoder*
107 | - MSET - *Multivariate State Estimation Technique*
108 |
109 | Additionally on the leaderboard were shown the externally calculated results of the following algorithms:
110 |
111 | - [ArimaFD](https://github.com/waico/arimafd) - *ARIMA-based fault detection algorithm*
112 | - [T-squared](http://github.com/YKatser/ControlCharts/tree/main/examples) - *Hotelling's T-squared statistics*
113 | - [T-squared+Q (PCA-based)](http://github.com/YKatser/ControlCharts/tree/main/examples) - *Hotelling's T-squared statistics + Q statistics based on PCA*
114 | - [ruptures](https://github.com/deepcharles/ruptures) - *Changepoint detection (CPD) algorithms from ruptures package*
115 | - [CPDE](https://github.com/YKatser/CPDE) - *Ruptures-based changepoint detection ensemble (CPDE) algorithms*
116 |
117 | Details regarding the algorithms, including short description, references to scientific papers and code of the initial implementation is available in [this readme](https://github.com/waico/SKAB/tree/master/notebooks#anomaly-detection-algorithms).
118 |
119 | ## Installation
120 |
121 | 1. install Python 3.10+ (tested on 3.10.13)
122 |
123 | 1. install [poetry](https://python-poetry.org/docs/) package manager
124 | - `brew install poetry`
125 | > Poetry installs dependencies and locks versions for deterministic installs. Poetry uses [Python's built-in `venv` module](https://docs.python.org/3/library/venv.html) to create virtual environments. It also uses PEP [517](https://peps.python.org/pep-0517) & [518](https://peps.python.org/pep-0518) specifications to build packages without requiring `setup.py` or `requirements.txt` files.
126 |
127 | 1. LightGBM base install
128 | - `brew install lightgbm`
129 |
130 | 1. install SKAB dependencies, see [pyproject.toml](pyproject.toml) for details
131 | - `poetry install`
132 |
133 | 1. confirm installation
134 | - `poetry show --tree` - shows all dependencies installed
135 | - `poetry env info` - displays information about the current environment (Python version, path, etc)
136 | - `poetry list` - lists all cli commands
137 |
138 | ## Citation
139 |
140 | Please cite our project in your publications if it helps your research.
141 |
142 | ```bibtex
143 | @misc{skab,
144 | author = {Katser, Iurii D. and Kozitsin, Vyacheslav O.},
145 | title = {Skoltech Anomaly Benchmark (SKAB)},
146 | year = {2020},
147 | publisher = {Kaggle},
148 | howpublished = {\url{https://www.kaggle.com/dsv/1693952}},
149 | DOI = {10.34740/KAGGLE/DSV/1693952}
150 | }
151 | ```
152 |
153 | ## Notable mentions
154 |
155 | SKAB is acknowledged by some ML resources.
156 |
157 | - [Anomaly Detection Learning Resources](https://github.com/yzhao062/anomaly-detection-resources#34-datasets)
158 | - [awesome-TS-anomaly-detection](https://github.com/rob-med/awesome-TS-anomaly-detection#benchmark-datasets)
159 | - [List of datasets for machine-learning research](https://en.wikipedia.org/wiki/List_of_datasets_for_machine-learning_research#Anomaly_data)
160 | - [paperswithcode.com](https://paperswithcode.com/dataset/skab)
161 | - [Google datasets](https://datasetsearch.research.google.com/search?query=skoltech%20anomaly%20benchmark&docid=IIIE4VWbqUKszygyAAAAAA%3D%3D)
162 | - [Industrial ML Datasets](https://github.com/nicolasj92/industrial-ml-datasets)
163 | - etc.
164 |
--------------------------------------------------------------------------------
/core/Conv_AE.py:
--------------------------------------------------------------------------------
1 | from tensorflow.keras.callbacks import EarlyStopping
2 | from tensorflow.keras.layers import Conv1D, Conv1DTranspose, Dropout, Input
3 | from tensorflow.keras.models import Sequential
4 | from tensorflow.keras.optimizers import Adam
5 |
6 |
7 | class Conv_AE:
8 | """
9 | A reconstruction convolutional autoencoder model to detect anomalies in timeseries data using reconstruction error as an anomaly score.
10 |
11 | Parameters
12 | ----------
13 | No parameters are required for initializing the class.
14 |
15 | Attributes
16 | ----------
17 | model : Sequential
18 | The trained convolutional autoencoder model.
19 |
20 | Examples
21 | --------
22 | >>> from Conv_AE import Conv_AE
23 | >>> CAutoencoder = Conv_AE()
24 | >>> CAutoencoder.fit(train_data)
25 | >>> prediction = CAutoencoder.predict(test_data)
26 | """
27 |
28 | def __init__(self):
29 | self._Random(0)
30 |
31 | def _Random(self, seed_value):
32 | import os
33 |
34 | os.environ["PYTHONHASHSEED"] = str(seed_value)
35 |
36 | import random
37 |
38 | random.seed(seed_value)
39 |
40 | import numpy as np
41 |
42 | np.random.seed(seed_value)
43 |
44 | import tensorflow as tf
45 |
46 | tf.random.set_seed(seed_value)
47 |
48 | def _build_model(self):
49 | model = Sequential(
50 | [
51 | Input(shape=(self.shape[1], self.shape[2])),
52 | Conv1D(
53 | filters=32,
54 | kernel_size=7,
55 | padding="same",
56 | strides=2,
57 | activation="relu",
58 | ),
59 | Dropout(rate=0.2),
60 | Conv1D(
61 | filters=16,
62 | kernel_size=7,
63 | padding="same",
64 | strides=2,
65 | activation="relu",
66 | ),
67 | Conv1DTranspose(
68 | filters=16,
69 | kernel_size=7,
70 | padding="same",
71 | strides=2,
72 | activation="relu",
73 | ),
74 | Dropout(rate=0.2),
75 | Conv1DTranspose(
76 | filters=32,
77 | kernel_size=7,
78 | padding="same",
79 | strides=2,
80 | activation="relu",
81 | ),
82 | Conv1DTranspose(filters=1, kernel_size=7, padding="same"),
83 | ]
84 | )
85 | model.compile(optimizer=Adam(learning_rate=0.001), loss="mse")
86 |
87 | return model
88 |
89 | def fit(self, data):
90 | """
91 | Train the convolutional autoencoder model on the provided data.
92 |
93 | Parameters
94 | ----------
95 | data : numpy.ndarray
96 | Input data for training the autoencoder model.
97 | """
98 |
99 | self.shape = data.shape
100 | self.model = self._build_model()
101 |
102 | self.model.fit(
103 | data,
104 | data,
105 | epochs=100,
106 | batch_size=32,
107 | validation_split=0.1,
108 | verbose=0,
109 | callbacks=[
110 | EarlyStopping(
111 | monitor="val_loss", patience=5, mode="min", verbose=0
112 | )
113 | ],
114 | )
115 |
116 | def predict(self, data):
117 | """
118 | Generate predictions using the trained convolutional autoencoder model.
119 |
120 | Parameters
121 | ----------
122 | data : numpy.ndarray
123 | Input data for generating predictions.
124 |
125 | Returns
126 | -------
127 | numpy.ndarray
128 | Predicted output data.
129 | """
130 |
131 | return self.model.predict(data)
132 |
--------------------------------------------------------------------------------
/core/Isolation_Forest.py:
--------------------------------------------------------------------------------
1 | from sklearn.ensemble import IsolationForest
2 |
3 |
4 | class Isolation_Forest:
5 | """
6 | Isolation Forest or iForest builds an ensemble of iTrees for a given data set, then anomalies are those instances which have short average path lengths on the iTrees.
7 |
8 | Parameters
9 | ----------
10 | params : list
11 | A list containing three parameters: random_state, n_jobs, and contamination.
12 |
13 | Attributes
14 | ----------
15 | random_state : int
16 | The random seed used for reproducibility.
17 | n_jobs : int
18 | The number of CPU cores to use for parallelism.
19 | contamination : float
20 | The expected proportion of anomalies in the dataset.
21 |
22 | Examples
23 | --------
24 | >>> from Isolation_Forest import Isolation_Forest
25 | >>> PARAMS = [random_state, n_jobs, contamination]
26 | >>> model = Isolation_Forest(PARAMS)
27 | >>> model.fit(X_train)
28 | >>> predictions = model.predict(test_data)
29 | """
30 |
31 | def __init__(self, params):
32 | self.params = params
33 | self.random_state = self.params[0]
34 | self.n_jobs = self.params[1]
35 | self.contamination = self.params[2]
36 |
37 | def _Random(self, seed_value):
38 | import os
39 |
40 | os.environ["PYTHONHASHSEED"] = str(seed_value)
41 |
42 | import random
43 |
44 | random.seed(seed_value)
45 |
46 | import numpy as np
47 |
48 | np.random.seed(seed_value)
49 |
50 | import tensorflow as tf
51 |
52 | tf.random.set_seed(seed_value)
53 |
54 | def _build_model(self):
55 | self._Random(0)
56 |
57 | model = IsolationForest(
58 | random_state=self.random_state,
59 | n_jobs=self.n_jobs,
60 | contamination=self.contamination,
61 | )
62 | return model
63 |
64 | def fit(self, X):
65 | """
66 | Train the Isolation Forest model on the provided data.
67 |
68 | Parameters
69 | ----------
70 | X : numpy.ndarray
71 | Input data for training the model.
72 | """
73 |
74 | self.model = self._build_model()
75 |
76 | self.model.fit(X)
77 |
78 | def predict(self, data):
79 | """
80 | Generate predictions using the trained Isolation Forest model.
81 |
82 | Parameters
83 | ----------
84 | data : numpy.ndarray
85 | Input data for generating predictions.
86 |
87 | Returns
88 | -------
89 | numpy.ndarray
90 | Predicted output data.
91 | """
92 |
93 | return self.model.predict(data)
94 |
--------------------------------------------------------------------------------
/core/LSTM_AE.py:
--------------------------------------------------------------------------------
1 | from tensorflow.keras import Model
2 | from tensorflow.keras.callbacks import EarlyStopping
3 | from tensorflow.keras.layers import (
4 | LSTM,
5 | Dense,
6 | Input,
7 | RepeatVector,
8 | TimeDistributed,
9 | )
10 |
11 |
12 | class LSTM_AE:
13 | """
14 | A reconstruction sequence-to-sequence (LSTM-based) autoencoder model to detect anomalies in timeseries data using reconstruction error as an anomaly score.
15 |
16 | Parameters
17 | ----------
18 | params : list
19 | A list of hyperparameters for the model, containing the following elements:
20 | - EPOCHS : int
21 | The number of training epochs.
22 | - BATCH_SIZE : int
23 | The batch size for training.
24 | - VAL_SPLIT : float
25 | The validation split ratio during training.
26 |
27 | Attributes
28 | ----------
29 | params : list
30 | The hyperparameters for the model.
31 |
32 | Examples
33 | --------
34 | >>> from LSTM_AE import LSTM_AE
35 | >>> PARAMS = [EPOCHS, BATCH_SIZE, VAL_SPLIT]
36 | >>> model = LSTM_AE(PARAMS)
37 | >>> model.fit(train_data)
38 | >>> predictions = model.predict(test_data)
39 | """
40 |
41 | def __init__(self, params):
42 | self.params = params
43 |
44 | def _Random(self, seed_value):
45 | import os
46 |
47 | os.environ["PYTHONHASHSEED"] = str(seed_value)
48 |
49 | import random
50 |
51 | random.seed(seed_value)
52 |
53 | import numpy as np
54 |
55 | np.random.seed(seed_value)
56 |
57 | import tensorflow as tf
58 |
59 | tf.random.set_seed(seed_value)
60 |
61 | def _build_model(self):
62 | self._Random(0)
63 |
64 | inputs = Input(shape=(self.shape[1], self.shape[2]))
65 | encoded = LSTM(100, activation="relu")(inputs)
66 |
67 | decoded = RepeatVector(self.shape[1])(encoded)
68 | decoded = LSTM(100, activation="relu", return_sequences=True)(decoded)
69 | decoded = TimeDistributed(Dense(self.shape[2]))(decoded)
70 |
71 | model = Model(inputs, decoded)
72 | _ = Model(inputs, encoded)
73 |
74 | model.compile(optimizer="adam", loss="mae", metrics=["mse"])
75 |
76 | return model
77 |
78 | def fit(self, X):
79 | """
80 | Train the sequence-to-sequence (LSTM-based) autoencoder model on the provided data.
81 |
82 | Parameters
83 | ----------
84 | X : numpy.ndarray
85 | Input data for training the model.
86 | """
87 |
88 | self.shape = X.shape
89 | self.model = self._build_model()
90 |
91 | early_stopping = EarlyStopping(patience=5, verbose=0)
92 |
93 | self.model.fit(
94 | X,
95 | X,
96 | validation_split=self.params[2],
97 | epochs=self.params[0],
98 | batch_size=self.params[1],
99 | verbose=0,
100 | shuffle=False,
101 | callbacks=[early_stopping],
102 | )
103 |
104 | def predict(self, data):
105 | """
106 | Generate predictions using the trained sequence-to-sequence (LSTM-based) autoencoder model.
107 |
108 | Parameters
109 | ----------
110 | data : numpy.ndarray
111 | Input data for generating predictions.
112 |
113 | Returns
114 | -------
115 | numpy.ndarray
116 | Predicted output data.
117 | """
118 |
119 | return self.model.predict(data)
120 |
--------------------------------------------------------------------------------
/core/LSTM_VAE.py:
--------------------------------------------------------------------------------
1 | from tensorflow.keras import backend as K
2 | from tensorflow.keras import losses
3 | from tensorflow.keras.callbacks import EarlyStopping
4 | from tensorflow.keras.layers import LSTM, Dense, Input, Layer, RepeatVector
5 | from tensorflow.keras.models import Model
6 |
7 |
8 | class KLDivergenceLayer(Layer):
9 | def __init__(self, **kwargs):
10 | super().__init__(**kwargs)
11 |
12 | def call(self, inputs):
13 | z_mean, z_log_sigma = inputs
14 | kl_loss = -0.5 * K.mean(
15 | 1 + z_log_sigma - K.square(z_mean) - K.exp(z_log_sigma), axis=-1
16 | )
17 | self.add_loss(kl_loss)
18 | return kl_loss # Return KL loss value
19 |
20 |
21 | class Sampling(Layer):
22 | def __init__(self, latent_dim, epsilon_std=1.0, **kwargs):
23 | super().__init__(**kwargs)
24 | self.latent_dim = latent_dim
25 | self.epsilon_std = epsilon_std
26 |
27 | def call(self, inputs):
28 | z_mean, z_log_sigma = inputs
29 | batch = K.shape(z_mean)[0]
30 | dim = K.shape(z_mean)[1]
31 | epsilon = K.random_normal(
32 | shape=(batch, dim), mean=0.0, stddev=self.epsilon_std
33 | )
34 | return z_mean + z_log_sigma * epsilon
35 |
36 | def compute_output_shape(self, input_shape):
37 | return input_shape[0] # Same shape as z_mean and z_log_sigma
38 |
39 |
40 | class LSTM_VAE:
41 | """
42 | A reconstruction LSTM variational autoencoder model to detect anomalies in timeseries data using reconstruction error as an anomaly score.
43 |
44 | Parameters
45 | ----------
46 | TenserFlow_backend : bool, optional
47 | Flag to specify whether to use TensorFlow backend (default is False).
48 |
49 | Attributes
50 | ----------
51 | None
52 |
53 | Examples
54 | -------
55 | >>> from LSTM_VAE import LSTM_VAE
56 | >>> model = LSTM_VAE()
57 | >>> model.fit(train_data)
58 | >>> predictions = model.predict(test_data)
59 | """
60 |
61 | def __init__(self, params):
62 | self.params = params
63 |
64 | def _build_model(self, input_dim, timesteps, intermediate_dim, latent_dim):
65 | self._Random(0)
66 |
67 | x = Input(
68 | shape=(
69 | timesteps,
70 | input_dim,
71 | )
72 | )
73 |
74 | h = LSTM(intermediate_dim)(x)
75 |
76 | self.z_mean = Dense(latent_dim)(h)
77 | self.z_log_sigma = Dense(latent_dim)(h)
78 |
79 | z = Sampling(latent_dim)([self.z_mean, self.z_log_sigma])
80 |
81 | h_decoded = RepeatVector(timesteps)(z)
82 | decoder_h = LSTM(intermediate_dim, return_sequences=True)(h_decoded)
83 | decoder_mean = LSTM(input_dim, return_sequences=True)(decoder_h)
84 |
85 | vae = Model(x, decoder_mean)
86 |
87 | _ = Model(x, self.z_mean)
88 |
89 | decoder_input = Input(shape=(latent_dim,))
90 |
91 | _h_decoded = RepeatVector(timesteps)(decoder_input)
92 | _h_decoded = LSTM(intermediate_dim, return_sequences=True)(_h_decoded)
93 |
94 | _x_decoded_mean = LSTM(input_dim, return_sequences=True)(_h_decoded)
95 | _ = Model(decoder_input, _x_decoded_mean)
96 |
97 | vae.compile(optimizer="rmsprop", loss=self.vae_loss)
98 |
99 | return vae
100 |
101 | def _Random(self, seed_value):
102 | import os
103 |
104 | os.environ["PYTHONHASHSEED"] = str(seed_value)
105 |
106 | import random
107 |
108 | random.seed(seed_value)
109 |
110 | import numpy as np
111 |
112 | np.random.seed(seed_value)
113 |
114 | import tensorflow as tf
115 |
116 | tf.random.set_seed(seed_value)
117 |
118 | def vae_loss(self, x, x_decoded_mean):
119 | """
120 | Calculate the VAE loss.
121 |
122 | Parameters
123 | ----------
124 | x : tensorflow.Tensor
125 | Input data.
126 | x_decoded_mean : tensorflow.Tensor
127 | Decoded output data.
128 |
129 | Returns
130 | -------
131 | loss : tensorflow.Tensor
132 | VAE loss value.
133 | """
134 | mse = losses.MeanSquaredError()
135 | xent_loss = mse(x, x_decoded_mean)
136 | kl_loss = KLDivergenceLayer()([self.z_mean, self.z_log_sigma])
137 | loss = xent_loss + kl_loss
138 | return loss
139 |
140 | def fit(self, X):
141 | """
142 | Train the LSTM variational autoencoder model on the provided data.
143 |
144 | Parameters
145 | ----------
146 | data : numpy.ndarray
147 | Input data for training.
148 | epochs : int, optional
149 | Number of training epochs (default is 20).
150 | validation_split : float, optional
151 | Fraction of the training data to be used as validation data (default is 0.1).
152 | BATCH_SIZE : int, optional
153 | Batch size for training (default is 1).
154 | early_stopping : bool, optional
155 | Whether to use early stopping during training (default is True).
156 | """
157 |
158 | self.shape = X.shape
159 | self.input_dim = self.shape[-1]
160 | self.timesteps = self.shape[1]
161 | self.latent_dim = 100
162 | self.epsilon_std = 1.0
163 | self.intermediate_dim = 32
164 |
165 | self.model = self._build_model(
166 | self.input_dim,
167 | timesteps=self.timesteps,
168 | intermediate_dim=self.intermediate_dim,
169 | latent_dim=self.latent_dim,
170 | )
171 |
172 | early_stopping = EarlyStopping(patience=5, verbose=0)
173 |
174 | self.model.fit(
175 | X,
176 | X,
177 | validation_split=self.params[2],
178 | epochs=self.params[0],
179 | batch_size=self.params[1],
180 | verbose=0,
181 | shuffle=False,
182 | callbacks=[early_stopping],
183 | )
184 |
185 | def predict(self, data):
186 | """
187 | Generate predictions using the trained LSTM variational autoencoder model.
188 |
189 | Parameters
190 | ----------
191 | data : numpy.ndarray
192 | Input data for making predictions.
193 |
194 | Returns
195 | -------
196 | predictions : numpy.ndarray
197 | The reconstructed output predictions.
198 | """
199 |
200 | return self.model.predict(data)
201 |
--------------------------------------------------------------------------------
/core/MSCRED.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | import tensorflow as tf
4 | from tensorflow.keras import Model
5 | from tensorflow.keras.callbacks import ReduceLROnPlateau
6 | from tensorflow.keras.layers import (
7 | Conv2D,
8 | Conv2DTranspose,
9 | ConvLSTM2D,
10 | Input,
11 | Layer,
12 | TimeDistributed,
13 | )
14 | from tensorflow.keras.optimizers import Adam
15 |
16 |
17 | class MSCRED:
18 | """
19 | MSCRED - Multi-Scale Convolutional Recurrent Encoder-Decoder first constructs multi-scale (resolution) signature matrices to characterize multiple levels of the system statuses across different time steps. In particular, different levels of the system statuses are used to indicate the severity of different abnormal incidents. Subsequently, given the signature matrices, a convolutional encoder is employed to encode the inter-sensor (time series) correlations patterns and an attention based Convolutional Long-Short Term Memory (ConvLSTM) network is developed to capture the temporal patterns. Finally, with the feature maps which encode the inter-sensor correlations and temporal information, a convolutional decoder is used to reconstruct the signature matrices and the residual signature matrices are further utilized to detect and diagnose anomalies. The intuition is that MSCRED may not reconstruct the signature matrices well if it never observes similar system statuses before.
20 |
21 | Parameters
22 | ----------
23 | params : list
24 | A list containing configuration parameters for the MSCRED model.
25 |
26 | Attributes
27 | ----------
28 | model : Model
29 | The trained MSCRED model.
30 |
31 | Examples
32 | --------
33 | >>> from MSCRED import MSCRED
34 | >>> PARAMS = [sensor_n, scale_n, step_max]
35 | >>> model = MSCRED(PARAMS)
36 | >>> model.fit(X_train, Y_train, X_test, Y_test)
37 | >>> prediction = model.predict(test_data)
38 | """
39 |
40 | def __init__(self, params):
41 | self.params = params
42 |
43 | def _build_model(self):
44 | self._Random(0)
45 |
46 | class MyPadLayer(Layer):
47 | def __init__(self, paddings, **kwargs):
48 | super().__init__(**kwargs)
49 | self.paddings = paddings
50 |
51 | def call(self, inputs):
52 | return tf.pad(inputs, self.paddings)
53 |
54 | class MyAttentionLayer(Layer):
55 | def __init__(self, attention_fun, **kwargs):
56 | super().__init__(**kwargs)
57 | self.attention = attention_fun
58 |
59 | def call(self, inputs, **kwargs):
60 | # Your attention mechanism implementation here
61 | return self.attention(inputs, **kwargs)
62 |
63 | class MyConcatLayer(Layer):
64 | def __init__(self, axis, **kwargs):
65 | super().__init__(**kwargs)
66 | self.axis = axis
67 |
68 | def call(self, inputs):
69 | return tf.concat(inputs, axis=self.axis)
70 |
71 | input_size = (
72 | self.params[2],
73 | self.params[0],
74 | self.params[0],
75 | self.params[1],
76 | )
77 | inputs = Input(input_size)
78 |
79 | if self.params[0] % 8 != 0:
80 | self.sensor_n_pad = (self.params[0] // 8) * 8 + 8
81 | else:
82 | self.sensor_n_pad = self.params[0]
83 |
84 | paddings = tf.constant(
85 | [
86 | [0, 0],
87 | [0, 0],
88 | [0, self.sensor_n_pad - self.params[0]],
89 | [0, self.sensor_n_pad - self.params[0]],
90 | [0, 0],
91 | ]
92 | )
93 |
94 | inputs_pad = MyPadLayer(paddings)(inputs)
95 |
96 | conv1 = TimeDistributed(
97 | Conv2D(
98 | filters=32,
99 | kernel_size=3,
100 | strides=1,
101 | kernel_initializer="glorot_uniform",
102 | padding="same",
103 | activation="selu",
104 | name="conv1",
105 | )
106 | )(inputs_pad)
107 |
108 | conv2 = TimeDistributed(
109 | Conv2D(
110 | filters=64,
111 | kernel_size=3,
112 | strides=2,
113 | kernel_initializer="glorot_uniform",
114 | padding="same",
115 | activation="selu",
116 | name="conv2",
117 | )
118 | )(conv1)
119 |
120 | conv3 = TimeDistributed(
121 | Conv2D(
122 | filters=128,
123 | kernel_size=2,
124 | strides=2,
125 | kernel_initializer="glorot_uniform",
126 | padding="same",
127 | activation="selu",
128 | name="conv3",
129 | )
130 | )(conv2)
131 |
132 | conv4 = TimeDistributed(
133 | Conv2D(
134 | filters=256,
135 | kernel_size=2,
136 | strides=2,
137 | kernel_initializer="glorot_uniform",
138 | padding="same",
139 | activation="selu",
140 | name="conv4",
141 | )
142 | )(conv3)
143 |
144 | convLSTM1 = ConvLSTM2D(
145 | filters=32,
146 | kernel_size=2,
147 | padding="same",
148 | return_sequences=True,
149 | name="convLSTM1",
150 | )(conv1)
151 | convLSTM1_out = MyAttentionLayer(self.attention)(
152 | convLSTM1, **{"koef": 1}
153 | )
154 |
155 | convLSTM2 = ConvLSTM2D(
156 | filters=64,
157 | kernel_size=2,
158 | padding="same",
159 | return_sequences=True,
160 | name="convLSTM2",
161 | )(conv2)
162 | convLSTM2_out = MyAttentionLayer(self.attention)(
163 | convLSTM2, **{"koef": 2}
164 | )
165 |
166 | convLSTM3 = ConvLSTM2D(
167 | filters=128,
168 | kernel_size=2,
169 | padding="same",
170 | return_sequences=True,
171 | name="convLSTM3",
172 | )(conv3)
173 | convLSTM3_out = MyAttentionLayer(self.attention)(
174 | convLSTM3, **{"koef": 4}
175 | )
176 |
177 | convLSTM4 = ConvLSTM2D(
178 | filters=256,
179 | kernel_size=2,
180 | padding="same",
181 | return_sequences=True,
182 | name="convLSTM4",
183 | )(conv4)
184 | convLSTM4_out = MyAttentionLayer(self.attention)(
185 | convLSTM4, **{"koef": 8}
186 | )
187 |
188 | deconv4 = Conv2DTranspose(
189 | filters=128,
190 | kernel_size=2,
191 | strides=2,
192 | kernel_initializer="glorot_uniform",
193 | padding="same",
194 | activation="selu",
195 | name="deconv4",
196 | )(convLSTM4_out)
197 | deconv4_out = MyConcatLayer(axis=3)([deconv4, convLSTM3_out])
198 |
199 | deconv3 = Conv2DTranspose(
200 | filters=64,
201 | kernel_size=2,
202 | strides=2,
203 | kernel_initializer="glorot_uniform",
204 | padding="same",
205 | activation="selu",
206 | name="deconv3",
207 | )(deconv4_out)
208 | deconv3_out = MyConcatLayer(axis=3)([deconv3, convLSTM2_out])
209 |
210 | deconv2 = Conv2DTranspose(
211 | filters=32,
212 | kernel_size=3,
213 | strides=2,
214 | kernel_initializer="glorot_uniform",
215 | padding="same",
216 | activation="selu",
217 | name="deconv2",
218 | )(deconv3_out)
219 | deconv2_out = MyConcatLayer(axis=3)([deconv2, convLSTM1_out])
220 |
221 | deconv1 = Conv2DTranspose(
222 | filters=self.params[1],
223 | kernel_size=3,
224 | strides=1,
225 | kernel_initializer="glorot_uniform",
226 | padding="same",
227 | activation="selu",
228 | name="deconv1",
229 | )(deconv2_out)
230 |
231 | model = Model(
232 | inputs=inputs,
233 | outputs=deconv1[:, : self.params[0], : self.params[0], :],
234 | )
235 |
236 | return model
237 |
238 | def attention(self, outputs, koef):
239 | """
240 | Attention mechanism to weigh the importance of each step in the sequence.
241 |
242 | Parameters
243 | ----------
244 | outputs : tf.Tensor
245 | The output tensor from ConvLSTM layers.
246 | koef : int
247 | A coefficient to scale the attention mechanism.
248 |
249 | Returns
250 | -------
251 | tf.Tensor
252 | Weighted output tensor.
253 | """
254 |
255 | attention_w = []
256 | for k in range(self.params[2]):
257 | attention_w.append(
258 | tf.reduce_sum(
259 | tf.multiply(outputs[:, k], outputs[:, -1]), axis=(1, 2, 3)
260 | )
261 | / self.params[2]
262 | )
263 | attention_w = tf.reshape(
264 | tf.nn.softmax(tf.stack(attention_w, axis=1)),
265 | [-1, 1, self.params[2]],
266 | )
267 | outputs = tf.reshape(
268 | outputs,
269 | [-1, self.params[2], tf.reduce_prod(outputs.shape.as_list()[2:])],
270 | )
271 | outputs = tf.matmul(attention_w, outputs)
272 | outputs = tf.reshape(
273 | outputs,
274 | [
275 | -1,
276 | math.ceil(self.sensor_n_pad / koef),
277 | math.ceil(self.sensor_n_pad / koef),
278 | 32 * koef,
279 | ],
280 | )
281 | return outputs
282 |
283 | def _Random(self, seed_value):
284 | import os
285 |
286 | os.environ["PYTHONHASHSEED"] = str(seed_value)
287 |
288 | import random
289 |
290 | random.seed(seed_value)
291 |
292 | import numpy as np
293 |
294 | np.random.seed(seed_value)
295 |
296 | import tensorflow as tf
297 |
298 | tf.random.set_seed(seed_value)
299 |
300 | def _loss_fn(self, y_true, y_pred):
301 | return tf.reduce_mean(tf.square(y_true - y_pred))
302 |
303 | def fit(self, X_train, Y_train, batch_size=200, epochs=25):
304 | """
305 | Train the MSCRED model on the provided data.
306 |
307 | Parameters
308 | ----------
309 | X_train : numpy.ndarray
310 | The training input data.
311 | Y_train : numpy.ndarray
312 | The training target data.
313 | X_test : numpy.ndarray
314 | The testing input data.
315 | Y_test : numpy.ndarray
316 | The testing target data.
317 | batch_size : int, optional
318 | The batch size for training, by default 200.
319 | epochs : int, optional
320 | The number of training epochs, by default 25.
321 | """
322 |
323 | self.model = self._build_model()
324 |
325 | self.model.compile(
326 | optimizer=Adam(learning_rate=1e-3),
327 | loss=self._loss_fn,
328 | )
329 | reduce_lr = ReduceLROnPlateau(
330 | monitor="loss", factor=0.8, patience=6, min_lr=0.000001, verbose=1
331 | )
332 | self.model.fit(
333 | X_train,
334 | Y_train,
335 | batch_size=batch_size,
336 | epochs=epochs,
337 | # validation_data=(X_test, Y_test),
338 | callbacks=reduce_lr,
339 | )
340 |
341 | def predict(self, data):
342 | """
343 | Generate predictions using the trained MSCRED model.
344 |
345 | Parameters
346 | ----------
347 | data : numpy.ndarray
348 | Input data for generating predictions.
349 |
350 | Returns
351 | -------
352 | numpy.ndarray
353 | Predicted output data.
354 | """
355 |
356 | return self.model.predict(data)
357 |
--------------------------------------------------------------------------------
/core/MSET.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import pandas as pd
3 | from scipy import linalg as spla
4 | from sklearn.preprocessing import StandardScaler
5 |
6 |
7 | class MSET:
8 | """
9 | MSET - multivariate state estimation technique is a non-parametric and statistical modeling method, which calculates the estimated values based on the weighted average of historical data. In terms of procedure, MSET is similar to some nonparametric regression methods, such as, auto-associative kernel regression.
10 |
11 | Parameters
12 | ----------
13 | None
14 |
15 | Attributes
16 | ----------
17 | None
18 |
19 | Examples
20 | --------
21 | >>> from MSET import MSET
22 | >>> model = MSET()
23 | >>> model.fit(data)
24 | >>> prediction = model.predict(test_data)
25 | """
26 |
27 | def __init__(self):
28 | self._Random(0)
29 |
30 | def _build_model(self):
31 | self.SS = StandardScaler()
32 |
33 | def _Random(self, seed_value):
34 | import os
35 |
36 | os.environ["PYTHONHASHSEED"] = str(seed_value)
37 |
38 | import random
39 |
40 | random.seed(seed_value)
41 |
42 | import numpy as np
43 |
44 | np.random.seed(seed_value)
45 |
46 | import tensorflow as tf
47 |
48 | tf.random.set_seed(seed_value)
49 |
50 | def calc_W(self, X_obs):
51 | """
52 | Calculate the weight matrix W.
53 |
54 | Parameters
55 | ----------
56 | X_obs : numpy.ndarray
57 | Observations for which to calculate the weight matrix.
58 |
59 | Returns
60 | -------
61 | numpy.ndarray
62 | Weight matrix W.
63 | """
64 |
65 | DxX_obs = self.otimes(self.D, X_obs)
66 | # try:
67 | W = spla.lu_solve(self.LU_factors, DxX_obs)
68 | # except:
69 | # W = np.linalg.solve(self.DxD, DxX_obs)
70 |
71 | return W
72 |
73 | def otimes(self, X, Y):
74 | """
75 | Compute the outer product of two matrices X and Y.
76 |
77 | Parameters
78 | ----------
79 | X : numpy.ndarray
80 | First matrix.
81 | Y : numpy.ndarray
82 | Second matrix.
83 |
84 | Returns
85 | -------
86 | numpy.ndarray
87 | Outer product of X and Y.
88 | """
89 |
90 | m1, n = np.shape(X)
91 | m2, p = np.shape(Y)
92 |
93 | if m1 != m2:
94 | raise Exception("dimensionality mismatch between X and Y.")
95 |
96 | Z = np.zeros((n, p))
97 |
98 | if n != p:
99 | for i in range(n):
100 | for j in range(p):
101 | Z[i, j] = self.kernel(X[:, i], Y[:, j])
102 | else:
103 | for i in range(n):
104 | for j in range(i, p):
105 | Z[i, j] = self.kernel(X[:, i], Y[:, j])
106 | Z[j, i] = Z[i, j]
107 |
108 | return Z
109 |
110 | def kernel(self, x, y):
111 | """
112 | Compute the kernel function value.
113 |
114 | Parameters
115 | ----------
116 | x : numpy.ndarray
117 | First vector.
118 | y : numpy.ndarray
119 | Second vector.
120 |
121 | Returns
122 | -------
123 | float
124 | Kernel function s(x,y) = 1 - ||x-y||/(||x|| + ||y||) value.
125 | """
126 |
127 | if all(x == y):
128 | return 1.0
129 | else:
130 | return 1.0 - np.linalg.norm(x - y) / (
131 | np.linalg.norm(x) + np.linalg.norm(y)
132 | )
133 |
134 | def fit(self, df, train_start=None, train_stop=None):
135 | """
136 | Train the MSET model on the provided data.
137 |
138 | Parameters
139 | ----------
140 | df : pandas.DataFrame
141 | Input data for training the model.
142 | train_start : int, optional
143 | Index to start training, by default None.
144 | train_stop : int, optional
145 | Index to stop training, by default None.
146 |
147 | Returns
148 | -------
149 | None
150 | """
151 |
152 | self.model = self._build_model()
153 |
154 | self.D = df[train_start:train_stop].values.T.copy()
155 | self.D = self.SS.fit_transform(self.D.T).T
156 |
157 | self.DxD = self.otimes(self.D, self.D)
158 | self.LU_factors = spla.lu_factor(self.DxD)
159 |
160 | def predict(self, data):
161 | """
162 | Generate predictions using the trained MSET model.
163 |
164 | Parameters
165 | ----------
166 | data : pandas.DataFrame
167 | Input data for generating predictions.
168 |
169 | Returns
170 | -------
171 | pandas.DataFrame
172 | Predicted output data.
173 | """
174 |
175 | X_obs = data.values.T.copy()
176 | X_obs = self.SS.transform(X_obs.T).T
177 |
178 | pred = np.zeros(X_obs.T.shape)
179 |
180 | for i in range(X_obs.shape[1]):
181 | pred[[i], :] = (
182 | self.D @ self.calc_W(X_obs[:, i].reshape([-1, 1]))
183 | ).T
184 |
185 | return pd.DataFrame(
186 | self.SS.inverse_transform(pred),
187 | index=data.index,
188 | columns=data.columns,
189 | )
190 |
--------------------------------------------------------------------------------
/core/Vanilla_AE.py:
--------------------------------------------------------------------------------
1 | from tensorflow.keras.callbacks import EarlyStopping
2 | from tensorflow.keras.layers import (
3 | Activation,
4 | BatchNormalization,
5 | Dense,
6 | Input,
7 | )
8 | from tensorflow.keras.models import Model
9 | from tensorflow.keras.optimizers import Adam
10 |
11 |
12 | class Vanilla_AE:
13 | """
14 | Feed-forward neural network with autoencoder architecture for anomaly detection using reconstruction error as an anomaly score.
15 |
16 | Parameters
17 | ----------
18 | params : list
19 | List containing the following hyperparameters in order:
20 | - Number of neurons in the first encoder layer
21 | - Number of neurons in the bottleneck layer (latent representation)
22 | - Number of neurons in the first decoder layer
23 | - Learning rate for the optimizer
24 | - Batch size for training
25 |
26 | Attributes
27 | ----------
28 | model : tensorflow.keras.models.Model
29 | The autoencoder model.
30 |
31 | Examples
32 | -------
33 | >>> from Vanilla_AE import AutoEncoder
34 | >>> autoencoder = AutoEncoder(param=[5, 4, 2, 0.005, 32])
35 | >>> autoencoder.fit(train_data)
36 | >>> predictions = autoencoder.predict(test_data)
37 | """
38 |
39 | def __init__(self, params):
40 | self.param = params
41 |
42 | def _build_model(self):
43 | self._Random(0)
44 |
45 | input_dots = Input(shape=(self.shape,))
46 | x = Dense(self.param[0])(input_dots)
47 | x = BatchNormalization()(x)
48 | x = Activation("relu")(x)
49 |
50 | x = Dense(self.param[1])(x)
51 | x = BatchNormalization()(x)
52 | x = Activation("relu")(x)
53 |
54 | bottleneck = Dense(self.param[2], activation="linear")(x)
55 |
56 | x = Dense(self.param[1])(bottleneck)
57 | x = BatchNormalization()(x)
58 | x = Activation("relu")(x)
59 |
60 | x = Dense(self.param[0])(x)
61 | x = BatchNormalization()(x)
62 | x = Activation("relu")(x)
63 |
64 | out = Dense(self.shape, activation="linear")(x)
65 |
66 | model = Model(input_dots, out)
67 | model.compile(
68 | optimizer=Adam(self.param[3]), loss="mae", metrics=["mse"]
69 | )
70 | self.model = model
71 |
72 | return model
73 |
74 | def _Random(self, seed_value):
75 | import os
76 |
77 | os.environ["PYTHONHASHSEED"] = str(seed_value)
78 |
79 | import random
80 |
81 | random.seed(seed_value)
82 |
83 | import numpy as np
84 |
85 | np.random.seed(seed_value)
86 |
87 | import tensorflow as tf
88 |
89 | tf.random.set_seed(seed_value)
90 |
91 | def fit(
92 | self,
93 | data,
94 | early_stopping=True,
95 | validation_split=0.2,
96 | epochs=40,
97 | verbose=0,
98 | shuffle=True,
99 | ):
100 | """
101 | Train the autoencoder model on the provided data.
102 |
103 | Parameters
104 | ----------
105 | data : numpy.ndarray
106 | Input data for training.
107 | early_stopping : bool, optional
108 | Whether to use early stopping during training.
109 | validation_split : float, optional
110 | Fraction of the training data to be used as validation data.
111 | epochs : int, optional
112 | Number of training epochs.
113 | verbose : int, optional
114 | Verbosity mode (0 = silent, 1 = progress bar, 2 = current epoch and losses, 3 = each training iteration).
115 | shuffle : bool, optional
116 | Whether to shuffle the training data before each epoch.
117 | """
118 |
119 | self.shape = data.shape[1]
120 | self.model = self._build_model()
121 | callbacks = []
122 | if early_stopping:
123 | callbacks.append(EarlyStopping(patience=3, verbose=0))
124 | self.model.fit(
125 | data,
126 | data,
127 | validation_split=validation_split,
128 | epochs=epochs,
129 | batch_size=self.param[4],
130 | verbose=verbose,
131 | shuffle=shuffle,
132 | callbacks=callbacks,
133 | )
134 |
135 | def predict(self, data):
136 | """
137 | Generate predictions using the trained autoencoder model.
138 |
139 | Parameters
140 | ----------
141 | data : numpy.ndarray
142 | Input data for making predictions.
143 |
144 | Returns
145 | -------
146 | numpy.ndarray
147 | The reconstructed output predictions.
148 | """
149 |
150 | return self.model.predict(data)
151 |
--------------------------------------------------------------------------------
/core/Vanilla_LSTM.py:
--------------------------------------------------------------------------------
1 | from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
2 | from tensorflow.keras.layers import LSTM, Dense
3 | from tensorflow.keras.models import Sequential
4 |
5 |
6 | class Vanilla_LSTM:
7 | """
8 | LSTM-based neural network for anomaly detection using reconstruction error as an anomaly score.
9 |
10 | Parameters
11 | ----------
12 | params : list
13 | A list containing various parameters for configuring the LSTM model.
14 |
15 | Attributes
16 | ----------
17 | model : Sequential
18 | The trained LSTM model.
19 |
20 | Examples
21 | --------
22 | >>> from Vanilla_LSTM import Vanilla_LSTM
23 | >>> PARAMS = [N_STEPS, EPOCHS, BATCH_SIZE, VAL_SPLIT]
24 | >>> lstm_model = Vanilla_LSTM(PARAMS)
25 | >>> lstm_model.fit(train_data, train_labels)
26 | >>> predictions = lstm_model.predict(test_data)
27 | """
28 |
29 | def __init__(self, params):
30 | self.params = params
31 |
32 | def _Random(self, seed_value):
33 | import os
34 |
35 | os.environ["PYTHONHASHSEED"] = str(seed_value)
36 |
37 | import random
38 |
39 | random.seed(seed_value)
40 |
41 | import numpy as np
42 |
43 | np.random.seed(seed_value)
44 |
45 | import tensorflow as tf
46 |
47 | tf.random.set_seed(seed_value)
48 |
49 | def _build_model(self):
50 | self._Random(0)
51 |
52 | model = Sequential()
53 | model.add(
54 | LSTM(
55 | 100,
56 | activation="relu",
57 | return_sequences=True,
58 | input_shape=(self.params[0], self.n_features),
59 | )
60 | )
61 | model.add(LSTM(100, activation="relu"))
62 | model.add(Dense(self.n_features))
63 | model.compile(optimizer="adam", loss="mae", metrics=["mse"])
64 | return model
65 |
66 | def fit(self, X, y):
67 | """
68 | Train the LSTM model on the provided data.
69 |
70 | Parameters
71 | ----------
72 | X : numpy.ndarray
73 | Input data for training the model.
74 | y : numpy.ndarray
75 | Target data for training the model.
76 | """
77 | self.n_features = X.shape[2]
78 | self.model = self._build_model()
79 |
80 | early_stopping = EarlyStopping(patience=10, verbose=0)
81 |
82 | reduce_lr = ReduceLROnPlateau(
83 | factor=0.1, patience=5, min_lr=0.0001, verbose=0
84 | )
85 |
86 | self.model.fit(
87 | X,
88 | y,
89 | validation_split=self.params[3],
90 | epochs=self.params[1],
91 | batch_size=self.params[2],
92 | verbose=0,
93 | shuffle=False,
94 | callbacks=[early_stopping, reduce_lr],
95 | )
96 |
97 | def predict(self, data):
98 | """
99 | Generate predictions using the trained LSTM model.
100 |
101 | Parameters
102 | ----------
103 | data : numpy.ndarray
104 | Input data for generating predictions.
105 |
106 | Returns
107 | -------
108 | numpy.ndarray
109 | Predicted output data.
110 | """
111 |
112 | return self.model.predict(data)
113 |
--------------------------------------------------------------------------------
/core/__init.py__:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/waico/SKAB/b2c0d46c2971dcbfe71e26087b6d231998bb91c2/core/__init.py__
--------------------------------------------------------------------------------
/core/metrics.py:
--------------------------------------------------------------------------------
1 | """
2 | This module is part of library (tsad)[https://github.com/waico/tsad]
3 | """
4 |
5 | import matplotlib.gridspec as gridspec
6 | import matplotlib.pyplot as plt
7 | import numpy as np
8 | import pandas as pd
9 |
10 |
11 | def filter_detecting_boundaries(detecting_boundaries):
12 | """
13 | [[t1,t2],[],[t1,t2]] -> [[t1,t2],[t1,t2]]
14 | [[],[]] -> []
15 | """
16 | _detecting_boundaries = []
17 | for couple in detecting_boundaries.copy():
18 | if len(couple) != 0:
19 | _detecting_boundaries.append(couple)
20 | detecting_boundaries = _detecting_boundaries
21 | return detecting_boundaries
22 |
23 |
24 | def single_detecting_boundaries(
25 | true_series,
26 | true_list_ts,
27 | prediction,
28 | portion,
29 | window_width,
30 | anomaly_window_destination,
31 | intersection_mode,
32 | ):
33 | """
34 | Extract detecting_boundaries from series or list of timestamps
35 | """
36 |
37 | if (true_series is not None) and (true_list_ts is not None):
38 | raise Exception("Choose the ONE type")
39 | elif true_series is not None:
40 | true_timestamps = true_series[true_series == 1].index
41 | elif true_list_ts is not None:
42 | if len(true_list_ts) == 0:
43 | return [[]]
44 | else:
45 | true_timestamps = true_list_ts
46 | else:
47 | raise Exception("Choose the type")
48 | #
49 | detecting_boundaries = []
50 | td = (
51 | pd.Timedelta(window_width)
52 | if window_width is not None
53 | else pd.Timedelta(
54 | (prediction.index[-1] - prediction.index[0])
55 | / (len(true_timestamps) + 1)
56 | * portion
57 | )
58 | )
59 | for val in true_timestamps:
60 | if anomaly_window_destination == "lefter":
61 | detecting_boundaries.append([val - td, val])
62 | elif anomaly_window_destination == "righter":
63 | detecting_boundaries.append([val, val + td])
64 | elif anomaly_window_destination == "center":
65 | detecting_boundaries.append([val - td / 2, val + td / 2])
66 | else:
67 | raise RuntimeError("choose anomaly_window_destination")
68 |
69 | # block for resolving intersection problem:
70 | # important to watch right boundary to be never included to avoid windows intersection
71 | if len(detecting_boundaries) == 0:
72 | return detecting_boundaries
73 |
74 | new_detecting_boundaries = detecting_boundaries.copy()
75 | intersection_count = 0
76 | for i in range(len(new_detecting_boundaries) - 1):
77 | if (
78 | new_detecting_boundaries[i][1]
79 | >= new_detecting_boundaries[i + 1][0]
80 | ):
81 | # transform print to list of intersections
82 | # print(f'Intersection of scoring windows {new_detecting_boundaries[i][1], new_detecting_boundaries[i+1][0]}')
83 | intersection_count += 1
84 | if intersection_mode == "cut left window":
85 | new_detecting_boundaries[i][1] = new_detecting_boundaries[
86 | i + 1
87 | ][0]
88 | elif intersection_mode == "cut right window":
89 | new_detecting_boundaries[i + 1][0] = new_detecting_boundaries[
90 | i
91 | ][1]
92 | elif intersection_mode == "cut both":
93 | _a = new_detecting_boundaries[i][1]
94 | new_detecting_boundaries[i][1] = new_detecting_boundaries[
95 | i + 1
96 | ][0]
97 | new_detecting_boundaries[i + 1][0] = _a
98 | else:
99 | raise Exception("choose the intersection_mode")
100 | # print(f'There are {intersection_count} intersections of scoring windows')
101 | detecting_boundaries = new_detecting_boundaries.copy()
102 | return detecting_boundaries
103 |
104 |
105 | def check_errors(my_list):
106 | """
107 | Check format of input true data
108 |
109 | Parameters
110 | ----------
111 | my_list - uniform format of true (See evaluate.evaluate)
112 |
113 | Returns
114 | ----------
115 | mx : depth of list, or variant of processing
116 | """
117 | assert isinstance(my_list, list)
118 | mx = 1
119 | # ravel = []
120 | level_list = {}
121 |
122 | def check_error(my_list):
123 | return not (
124 | (all(isinstance(my_el, list) for my_el in my_list))
125 | or (all(isinstance(my_el, pd.Series) for my_el in my_list))
126 | or (all(isinstance(my_el, pd.Timestamp) for my_el in my_list))
127 | )
128 |
129 | def recurse(my_list, level=1):
130 | nonlocal mx
131 | nonlocal level_list
132 |
133 | if check_error(my_list):
134 | raise Exception(
135 | f"Non uniform data format in level {level}: {my_list}"
136 | )
137 |
138 | if level not in level_list.keys():
139 | level_list[level] = [] # for checking format
140 |
141 | for my_el in my_list:
142 | level_list[level].append(my_el)
143 | if isinstance(my_el, list):
144 | mx = max([mx, level + 1])
145 | recurse(my_el, level + 1)
146 |
147 | recurse(my_list)
148 | for level in level_list:
149 | if check_error(level_list[level]):
150 | raise Exception(
151 | f"Non uniform data format in level {level}: {my_list}"
152 | )
153 |
154 | if 3 in level_list:
155 | for el in level_list[2]:
156 | if not ((len(el) == 2) or (len(el) == 0)):
157 | raise Exception(
158 | f"Non uniform data format in level {2}: {my_list}"
159 | )
160 | return mx
161 |
162 |
163 | def extract_cp_confusion_matrix(
164 | detecting_boundaries, prediction, point=0, binary=False
165 | ):
166 | """
167 | prediction: pd.Series
168 |
169 | point=None for binary case
170 | Returns
171 | ----------
172 | dict: TPs: dict of numer window of [t1,t_cp,t2]
173 | FPs: list of timestamps
174 | FNs: list of numer window
175 | """
176 | _detecting_boundaries = []
177 | for couple in detecting_boundaries.copy():
178 | if len(couple) != 0:
179 | _detecting_boundaries.append(couple)
180 | detecting_boundaries = _detecting_boundaries
181 |
182 | times_pred = prediction[prediction.dropna() == 1].sort_index().index
183 |
184 | my_dict = {}
185 | my_dict["TPs"] = {}
186 | my_dict["FPs"] = []
187 | my_dict["FNs"] = []
188 |
189 | if len(detecting_boundaries) != 0:
190 | my_dict["FPs"].append(
191 | times_pred[times_pred < detecting_boundaries[0][0]]
192 | ) # left
193 | for i in range(len(detecting_boundaries)):
194 | times_pred_window = times_pred[
195 | (times_pred >= detecting_boundaries[i][0])
196 | & (times_pred <= detecting_boundaries[i][1])
197 | ]
198 | times_prediction_in_window = prediction[
199 | detecting_boundaries[i][0] : detecting_boundaries[i][1]
200 | ].index
201 | if len(times_pred_window) == 0:
202 | if not binary:
203 | my_dict["FNs"].append(i)
204 | else:
205 | my_dict["FNs"].append(times_prediction_in_window)
206 | else:
207 | my_dict["TPs"][i] = [
208 | detecting_boundaries[i][0],
209 | times_pred_window[point]
210 | if not binary
211 | else times_pred_window, # attention
212 | detecting_boundaries[i][1],
213 | ]
214 | if binary:
215 | my_dict["FNs"].append(
216 | times_prediction_in_window[
217 | ~times_prediction_in_window.isin(times_pred_window)
218 | ]
219 | )
220 | if len(detecting_boundaries) > i + 1:
221 | my_dict["FPs"].append(
222 | times_pred[
223 | (times_pred > detecting_boundaries[i][1])
224 | & (times_pred < detecting_boundaries[i + 1][0])
225 | ]
226 | )
227 |
228 | my_dict["FPs"].append(
229 | times_pred[times_pred > detecting_boundaries[i][1]]
230 | ) # right
231 | else:
232 | my_dict["FPs"].append(times_pred)
233 |
234 | if len(my_dict["FPs"]) > 1:
235 | my_dict["FPs"] = np.concatenate(my_dict["FPs"])
236 | elif len(my_dict["FPs"]) == 1:
237 | my_dict["FPs"] = my_dict["FPs"][0]
238 | if len(my_dict["FPs"]) == 0: # not elif on purpose
239 | my_dict["FPs"] = []
240 |
241 | if binary:
242 | if len(my_dict["FNs"]) > 1:
243 | my_dict["FNs"] = np.concatenate(my_dict["FNs"])
244 | elif len(my_dict["FNs"]) == 1:
245 | my_dict["FNs"] = my_dict["FNs"][0]
246 | if len(my_dict["FNs"]) == 0: # not elif on purpose
247 | my_dict["FNs"] = []
248 | return my_dict
249 |
250 |
251 | def confusion_matrix(true, prediction):
252 | true_ = true == 1
253 | prediction_ = prediction == 1
254 | TP = (true_ & prediction_).sum()
255 | TN = (~true_ & ~prediction_).sum()
256 | FP = (~true_ & prediction_).sum()
257 | FN = (true_ & ~prediction_).sum()
258 | return TP, TN, FP, FN
259 |
260 |
261 | def single_average_delay(
262 | detecting_boundaries,
263 | prediction,
264 | anomaly_window_destination,
265 | clear_anomalies_mode,
266 | ):
267 | """
268 | anomaly_window_destination: 'lefter', 'righter', 'center'. Default='right'
269 | """
270 | detecting_boundaries = filter_detecting_boundaries(detecting_boundaries)
271 | point = 0 if clear_anomalies_mode else -1
272 | dict_cp_confusion = extract_cp_confusion_matrix(
273 | detecting_boundaries, prediction, point=point
274 | )
275 |
276 | missing = 0
277 | detectHistory = []
278 | all_true_anom = 0
279 | FP = 0
280 |
281 | FP += len(dict_cp_confusion["FPs"])
282 | missing += len(dict_cp_confusion["FNs"])
283 | all_true_anom += len(dict_cp_confusion["TPs"]) + len(
284 | dict_cp_confusion["FNs"]
285 | )
286 |
287 | if anomaly_window_destination == "lefter":
288 |
289 | def average_time(output_cp_cm_tp):
290 | return output_cp_cm_tp[2] - output_cp_cm_tp[1]
291 | elif anomaly_window_destination == "righter":
292 |
293 | def average_time(output_cp_cm_tp):
294 | return output_cp_cm_tp[1] - output_cp_cm_tp[0]
295 | elif anomaly_window_destination == "center":
296 |
297 | def average_time(output_cp_cm_tp):
298 | return output_cp_cm_tp[1] - (
299 | output_cp_cm_tp[0]
300 | + (output_cp_cm_tp[2] - output_cp_cm_tp[0]) / 2
301 | )
302 | else:
303 | raise Exception("Choose anomaly_window_destination")
304 |
305 | for fp_case_window in dict_cp_confusion["TPs"]:
306 | detectHistory.append(
307 | average_time(dict_cp_confusion["TPs"][fp_case_window])
308 | )
309 | return missing, detectHistory, FP, all_true_anom
310 |
311 |
312 | def my_scale(
313 | fp_case_window=None,
314 | A_tp=1,
315 | A_fp=0,
316 | koef=1,
317 | detalization=1000,
318 | clear_anomalies_mode=True,
319 | plot_figure=False,
320 | ):
321 | """
322 | ts - segment on which the window is applied
323 | """
324 | x = np.linspace(-np.pi / 2, np.pi / 2, detalization)
325 | x = x if clear_anomalies_mode else x[::-1]
326 | y = (
327 | (A_tp - A_fp)
328 | / 2
329 | * -1
330 | * np.tanh(koef * x)
331 | / (np.tanh(np.pi * koef / 2))
332 | + (A_tp - A_fp) / 2
333 | + A_fp
334 | )
335 | if not plot_figure and fp_case_window is not None:
336 | event = int(
337 | (fp_case_window[1] - fp_case_window[0])
338 | / (fp_case_window[-1] - fp_case_window[0])
339 | * detalization
340 | )
341 | if event >= len(x):
342 | event = len(x) - 1
343 | score = y[event]
344 | return score
345 | else:
346 | return y
347 |
348 |
349 | def single_evaluate_nab(
350 | detecting_boundaries,
351 | prediction,
352 | table_of_coef=None,
353 | clear_anomalies_mode=True,
354 | scale_func="improved",
355 | scale_koef=1,
356 | ):
357 | """
358 |
359 | detecting_boundaries: list of list of two float values
360 | The list of lists of left and right boundary indices
361 | for scoring results of labeling if empty. Can be [[]], or [[],[t1,t2],[]]
362 | table_of_coef: pandas array (3x4) of float values
363 | Table of coefficients for NAB score function
364 | indices: 'Standard','LowFP','LowFN'
365 | columns:'A_tp','A_fp','A_tn','A_fn'
366 |
367 | scale_func {default}, improved
368 | недостатки scale_func default -
369 | 1 - зависит от относительного шага, а это значит, что если
370 | слишком много точек в scoring window то перепад будет слишком
371 | жестким в середение.
372 | 2- то самая левая точка не равно Atp, а права не равна Afp
373 | (особенно если пррименять расплывающую множитель)
374 |
375 | clear_anomalies_mode тогда слева от границы Atp срправа Afp,
376 | иначе fault mode, когда слева от границы Afp срправа Atp
377 | """
378 | if scale_func == "improved":
379 | scale_func = my_scale
380 | else:
381 | raise Exception("choose the scale_func")
382 |
383 | # filter
384 | detecting_boundaries = filter_detecting_boundaries(detecting_boundaries)
385 |
386 | if table_of_coef is None:
387 | table_of_coef = pd.DataFrame(
388 | [
389 | [1.0, -0.11, 1.0, -1.0],
390 | [1.0, -0.22, 1.0, -1.0],
391 | [1.0, -0.11, 1.0, -2.0],
392 | ]
393 | )
394 | table_of_coef.index = pd.Index(["Standard", "LowFP", "LowFN"])
395 | table_of_coef.index.name = "Metric"
396 | table_of_coef.columns = ["A_tp", "A_fp", "A_tn", "A_fn"]
397 |
398 | # GO
399 | point = 0 if clear_anomalies_mode else -1
400 | dict_cp_confusion = extract_cp_confusion_matrix(
401 | detecting_boundaries, prediction, point=point
402 | )
403 |
404 | Scores, Scores_perfect, Scores_null = [], [], []
405 | for profile in ["Standard", "LowFP", "LowFN"]:
406 | A_tp = table_of_coef["A_tp"][profile]
407 | A_fp = table_of_coef["A_fp"][profile]
408 | A_fn = table_of_coef["A_fn"][profile]
409 |
410 | score = 0
411 | score += A_fp * len(dict_cp_confusion["FPs"])
412 | score += A_fn * len(dict_cp_confusion["FNs"])
413 | for fp_case_window in dict_cp_confusion["TPs"]:
414 | set_times = dict_cp_confusion["TPs"][fp_case_window]
415 | score += scale_func(set_times, A_tp, A_fp, koef=scale_koef)
416 |
417 | Scores.append(score)
418 | Scores_perfect.append(len(detecting_boundaries) * A_tp)
419 | Scores_null.append(len(detecting_boundaries) * A_fn)
420 |
421 | return np.array(
422 | [np.array(Scores), np.array(Scores_null), np.array(Scores_perfect)]
423 | )
424 |
425 |
426 | def chp_score(
427 | true,
428 | prediction,
429 | metric="nab",
430 | window_width=None,
431 | portion=0.1,
432 | anomaly_window_destination="lefter",
433 | clear_anomalies_mode=True,
434 | intersection_mode="cut right window",
435 | table_of_coef=None,
436 | scale_func="improved",
437 | scale_koef=1,
438 | plot_figure=False,
439 | verbose=True,
440 | ):
441 | """
442 | Parameters
443 | ----------
444 | true: variants:
445 | or: if one dataset : pd.Series with binary int labels (1 is
446 | anomaly, 0 is not anomaly);
447 |
448 | or: if one dataset : list of pd.Timestamp of true labels, or []
449 | if haven't labels ;
450 |
451 | or: if one dataset : list of list of t1,t2: left and right
452 | detection, boundaries of pd.Timestamp or [[]] if haven't labels
453 |
454 | or: if many datasets: list (len of number of datasets) of pd.Series
455 | with binary int labels;
456 |
457 | or: if many datasets: list of list of pd.Timestamp of true labels, or
458 | true = [ts,[]] if haven't labels for specific dataset;
459 |
460 | or: if many datasets: list of list of list of t1,t2: left and right
461 | detection boundaries of pd.Timestamp;
462 | If we haven't true labels for specific dataset then we must insert
463 | empty list of labels: true = [[[]],[[t1,t2],[t1,t2]]].
464 |
465 | __True labels of anomalies or changepoints.
466 | It is important to have appropriate labels (CP or
467 | anomaly) for corresponding metric (See later "metric")
468 |
469 | prediction: variants:
470 | or: if one dataset : pd.Series with binary int labels
471 | (1 is anomaly, 0 is not anomaly);
472 |
473 | or: if many datasets: list (len of number of datasets)
474 | of pd.Series with binary int labels.
475 |
476 | __Predicted labels of anomalies or changepoints.
477 | It is important to have appropriate labels (CP or
478 | anomaly) for corresponding metric (See later "metric")
479 |
480 | metric: {'nab', 'binary', 'average_time', 'confusion_matrix'}.
481 | Default='nab'
482 | Affects to output (see later: Returns)
483 | Changepoint problem: {'nab', 'average_time'}.
484 | Standard AD problem: {'binary', 'confusion_matrix'}.
485 | 'nab' is Numenta Anomaly Benchmark metric
486 |
487 | 'average_time' is both average delay or time to failure
488 | depend on situation.
489 |
490 | 'binary': FAR, MAR, F1.
491 |
492 | 'confusion_matrix' standard confusion_matrix for any point.
493 |
494 | window_width: 'str' for pd.Timedelta
495 | Width of detection window. Default=None.
496 |
497 | portion : float, default=0.1
498 | The portion is needed if window_width = None.
499 | The width of the detection window in this case is equal
500 | to a portion of the width of the length of prediction divided
501 | by the number of real CPs in this dataset. Default=0.1.
502 |
503 | anomaly_window_destination: {'lefter', 'righter', 'center'}. Default='right'
504 | The parameter of the location of the detection window relative to the anomaly.
505 | 'lefter' : the detection window will be on the left side of the anomaly
506 | 'righter' : the detection window will be on the right side of the anomaly
507 | 'center' : the scoring window will be positioned relative to the center of anom.
508 |
509 | clear_anomalies_mode : boolean, default=True.
510 | True : then the `left value of a Scoring function is Atp and the
511 | `right is Afp. Only the `first value inside the detection window is taken.
512 | False: then the `right value of a Scoring function is Atp and the
513 | `left is Afp. Only the `last value inside the detection window is taken.
514 |
515 | intersection_mode: {'cut left window', 'cut right window', 'both'}.
516 | Default='cut right window'
517 | The parameter will be used if the detection windows overlap for
518 | true changepoints, which is generally undesirable and requires a
519 | different approach than simply cropping the scoring window using
520 | this parameter.
521 | 'cut left window' : will cut the overlapping part of the left window
522 | 'cut right window': will cut the intersecting part of the right window
523 | 'both' : will crop the intersecting portion of both the left
524 | and right windows
525 |
526 | verbose: boolean, default=True.
527 | If True, then output useful information
528 |
529 | plot_figure : boolean, default=False.
530 | If True, then drawing the score fuctions, detection windows and predictions
531 | It is used for example, for calibration the scale_koef.
532 |
533 | table_of_coef (metric='nab'): pd.DataFrame of specific form. See bellow.
534 | Application profiles of NAB metric.If Default is None:
535 | table_of_coef = pd.DataFrame([[1.0,-0.11,1.0,-1.0],
536 | [1.0,-0.22,1.0,-1.0],
537 | [1.0,-0.11,1.0,-2.0]])
538 | table_of_coef.index = ['Standard','LowFP','LowFN']
539 | table_of_coef.index.name = "Metric"
540 | table_of_coef.columns = ['A_tp','A_fp','A_tn','A_fn']
541 |
542 | scale_func (metric='nab'): "default" of "improved". Default="improved".
543 | Scoring function in NAB metric.
544 | 'default' : standard NAB scoring function
545 | 'improved' : Our function for resolving disadvantages
546 | of standard NAB scoring function
547 |
548 | scale_koef : float > 0. Default=1.0.
549 | Smoothing factor. The smaller it is,
550 | the smoother the scoring function is.
551 |
552 | Returns
553 | ----------
554 | metrics : value of metrics, depend on metric
555 | 'nab': tuple
556 | - Standard profile, float
557 | - Low FP profile, float
558 | - Low FN profile
559 | 'average_time': tuple
560 | - Average time (average delay, or time to failure)
561 | - Missing changepoints, int
562 | - FPs, int
563 | - Number of true changepoints, int
564 | 'binary': tuple
565 | - F1 metric, float
566 | - False alarm rate, %, float
567 | - Missing Alarm Rate, %, float
568 | 'binary': tuple
569 | - TPs, int
570 | - TNs, int
571 | - FPs, int
572 | - FNS, int
573 |
574 | """
575 |
576 | assert isinstance(true, pd.Series) or isinstance(true, list)
577 | # checking prediction
578 | if isinstance(prediction, pd.Series):
579 | true = [true]
580 | prediction = [prediction]
581 | elif isinstance(prediction, list):
582 | if not all(isinstance(my_el, pd.Series) for my_el in prediction):
583 | raise Exception("Incorrect format for prediction")
584 | else:
585 | raise Exception("Incorrect format for prediction")
586 |
587 | # checking dataset length: Number of dataset unequal
588 | assert len(true) == len(prediction)
589 |
590 | # final check
591 | input_variant = check_errors(true)
592 |
593 | def check_sort(my_list, input_variant):
594 | for dataset in my_list:
595 | if input_variant == 2:
596 | assert all(np.sort(dataset) == np.array(dataset))
597 | elif input_variant == 3:
598 | assert all(
599 | np.sort(np.concatenate(dataset)) == np.concatenate(dataset)
600 | )
601 | elif input_variant == 1:
602 | assert all(
603 | dataset.index.values == dataset.sort_index().index.values
604 | )
605 |
606 | check_sort(true, input_variant)
607 | check_sort(prediction, 1)
608 |
609 | # part 2. To detected boundaries
610 | if (
611 | ((metric == "nab") or (metric == "average_time"))
612 | and (window_width is None)
613 | and (input_variant != 3)
614 | ):
615 | print(
616 | f"Since you didn't choose window_width and portion, portion will be default ({portion})"
617 | )
618 |
619 | if input_variant == 1:
620 | detecting_boundaries = [
621 | single_detecting_boundaries(
622 | true_series=true[i],
623 | true_list_ts=None,
624 | prediction=prediction[i],
625 | window_width=window_width,
626 | portion=portion,
627 | anomaly_window_destination=anomaly_window_destination,
628 | intersection_mode=intersection_mode,
629 | )
630 | for i in range(len(true))
631 | ]
632 |
633 | elif input_variant == 2:
634 | detecting_boundaries = [
635 | single_detecting_boundaries(
636 | true_series=None,
637 | true_list_ts=true[i],
638 | prediction=prediction[i],
639 | window_width=window_width,
640 | portion=portion,
641 | anomaly_window_destination=anomaly_window_destination,
642 | intersection_mode=intersection_mode,
643 | )
644 | for i in range(len(true))
645 | ]
646 |
647 | elif input_variant == 3:
648 | detecting_boundaries = true.copy()
649 | # Next anti fool system [[[t1,t2]],[]] -> [[[t1,t2]],[[]]]
650 | for i in range(len(detecting_boundaries)):
651 | if len(detecting_boundaries[i]) == 0:
652 | detecting_boundaries[i] = [[]]
653 | else:
654 | raise Exception("Unknown format for true data")
655 |
656 | # part 3. To compute metric
657 | if plot_figure:
658 | num_datasets = len(true)
659 | if ((metric == "binary") or (metric == "confusion_matrix")) and (
660 | input_variant == 1
661 | ):
662 | f = plt.figure(figsize=(16, 5 * num_datasets))
663 | grid = gridspec.GridSpec(num_datasets, 1)
664 | for i in range(num_datasets):
665 | globals()["ax" + str(i)] = f.add_subplot(grid[i])
666 | prediction[i].plot(
667 | ax=globals()["ax" + str(i)], label="pred", marker="o"
668 | )
669 | true[i].plot( # type: ignore
670 | ax=globals()["ax" + str(i)], label="true", marker="o"
671 | )
672 | globals()["ax" + str(i)].legend()
673 | plt.show()
674 | else:
675 | f = plt.figure(figsize=(16, 5 * num_datasets))
676 | grid = gridspec.GridSpec(num_datasets, 1)
677 | detalization = 100
678 | for i in range(num_datasets):
679 | globals()["ax" + str(i)] = f.add_subplot(grid[i])
680 | print_legend_boundary = True
681 |
682 | def plot_cp(couple, anomaly_window_destination, ax, label):
683 | if anomaly_window_destination == "lefter":
684 | ax.axvline(couple[1], c="r", label=label)
685 | elif anomaly_window_destination == "righter":
686 | ax.axvline(couple[0], c="r", label=label)
687 | elif anomaly_window_destination == "center":
688 | ax.axvline(
689 | couple[0] + ((couple[1] - couple[0]) / 2),
690 | c="r",
691 | label=label,
692 | )
693 |
694 | for couple in detecting_boundaries[i]:
695 | if len(couple) > 0:
696 | globals()["ax" + str(i)].axvspan(
697 | couple[0],
698 | couple[1],
699 | alpha=0.5,
700 | color="green",
701 | label="detection \nboundary"
702 | if print_legend_boundary
703 | else None,
704 | )
705 | nab = pd.Series(
706 | my_scale(
707 | plot_figure=True, detalization=detalization
708 | ),
709 | index=pd.date_range(
710 | couple[0], couple[1], periods=detalization
711 | ),
712 | )
713 | nab.plot(
714 | ax=globals()["ax" + str(i)],
715 | linewidth=0.4,
716 | color="brown",
717 | label="nab scoring func"
718 | if print_legend_boundary
719 | else None,
720 | )
721 | plot_cp(
722 | couple,
723 | anomaly_window_destination,
724 | globals()["ax" + str(i)],
725 | label="Changepoint"
726 | if print_legend_boundary
727 | else None,
728 | )
729 | print_legend_boundary = False
730 | else:
731 | pass
732 | prediction[i].plot(
733 | ax=globals()["ax" + str(i)], label="pred", marker="o"
734 | )
735 | globals()["ax" + str(i)].legend()
736 | plt.show()
737 |
738 | if metric == "nab":
739 | matrix = np.zeros((3, 3))
740 | for i in range(len(prediction)):
741 | matrix_ = single_evaluate_nab(
742 | detecting_boundaries[i],
743 | prediction[i],
744 | table_of_coef=table_of_coef,
745 | clear_anomalies_mode=clear_anomalies_mode,
746 | scale_func=scale_func,
747 | scale_koef=scale_koef,
748 | # plot_figure=plot_figure,
749 | )
750 | matrix = matrix + matrix_
751 |
752 | results = {}
753 | desc = ["Standard", "LowFP", "LowFN"]
754 | for t, profile_name in enumerate(desc):
755 | results[profile_name] = round(
756 | 100
757 | * (matrix[0, t] - matrix[1, t])
758 | / (matrix[2, t] - matrix[1, t]),
759 | 2,
760 | )
761 | if verbose:
762 | print(profile_name, " - ", results[profile_name])
763 | return results
764 |
765 | elif metric == "average_time":
766 | missing, detectHistory, FP, all_true_anom = 0, [], 0, 0
767 | for i in range(len(prediction)):
768 | missing_, detectHistory_, FP_, all_true_anom_ = (
769 | single_average_delay(
770 | detecting_boundaries[i],
771 | prediction[i],
772 | anomaly_window_destination=anomaly_window_destination,
773 | clear_anomalies_mode=clear_anomalies_mode,
774 | )
775 | )
776 | missing, detectHistory, FP, all_true_anom = (
777 | missing + missing_,
778 | detectHistory + detectHistory_,
779 | FP + FP_,
780 | all_true_anom + all_true_anom_,
781 | )
782 | add = np.mean(detectHistory)
783 | if verbose:
784 | print("Amount of true anomalies", all_true_anom)
785 | print(f"A number of missed CPs = {missing}")
786 | print(f"A number of FPs = {int(FP)}")
787 | print("Average time", add)
788 | return add, missing, int(FP), all_true_anom
789 |
790 | elif (metric == "binary") or (metric == "confusion_matrix"):
791 | if all(isinstance(my_el, pd.Series) for my_el in true):
792 | TP, TN, FP, FN = 0, 0, 0, 0
793 | for i in range(len(prediction)):
794 | TP_, TN_, FP_, FN_ = confusion_matrix(true[i], prediction[i])
795 | TP, TN, FP, FN = TP + TP_, TN + TN_, FP + FP_, FN + FN_
796 | else:
797 | print(
798 | "For this metric it is better if you use pd.Series format for true \nwith common index of true and prediction"
799 | )
800 | TP, TN, FP, FN = 0, 0, 0, 0
801 | for i in range(len(prediction)):
802 | dict_cp_confusion = extract_cp_confusion_matrix(
803 | detecting_boundaries[i], prediction[i], binary=True
804 | )
805 | TP += np.sum(
806 | [
807 | len(dict_cp_confusion["TPs"][window][1])
808 | for window in dict_cp_confusion["TPs"]
809 | ]
810 | )
811 | FP += len(dict_cp_confusion["FPs"])
812 | FN += len(dict_cp_confusion["FNs"])
813 | TN += len(prediction[i]) - TP - FP - FN
814 |
815 | if metric == "binary":
816 | f1 = round(TP / (TP + (FN + FP) / 2), 2)
817 | far = round(FP / (FP + TN) * 100, 2)
818 | mar = round(FN / (FN + TP) * 100, 2)
819 | if verbose:
820 | print(f"False Alarm Rate {far} %")
821 | print(f"Missing Alarm Rate {mar} %")
822 | print(f"F1 metric {f1}")
823 | return f1, far, mar
824 |
825 | elif metric == "confusion_matrix":
826 | if verbose:
827 | print("TP", TP)
828 | print("TN", TN)
829 | print("FP", FP)
830 | print("FN", FN)
831 | return TP, TN, FP, FN
832 | else:
833 | raise Exception("Choose the performance metric")
834 |
--------------------------------------------------------------------------------
/core/t2.py:
--------------------------------------------------------------------------------
1 | # Author: Iurii Katser
2 |
3 | import os
4 | from math import sqrt
5 |
6 | import numpy as np
7 | import scipy.stats as SS
8 | from matplotlib import pyplot as plt
9 | from numpy import linalg as LA
10 | from pandas import DataFrame
11 | from sklearn.decomposition import PCA
12 | from sklearn.preprocessing import StandardScaler
13 |
14 |
15 | class T2:
16 | """Calculation of the Hotelling's 1-dimensional T-squared
17 | statistic or T-squared statistic+Q-statistic based on PCA for
18 | anomaly detection in multivariate data.
19 |
20 | Based on the following papers:
21 | [1] - Q-statistic and T2-statistic PCA-based measures for damage
22 | assessment in structures / LE Mujica, J. Rodellar, A. Ferna ́ndez,
23 | A. Gu ̈emes // Structural Health Monitoring: An International
24 | Journal. — 2010. — nov. — Vol. 10, no. 5. — Pp. 539–553.
25 | [2] - Zhao Chunhui, Gao Furong. Online fault prognosis with
26 | relative deviation analysis and vector autoregressive modeling //
27 | Chemical Engineering Science. — 2015. — dec. — Vol. 138. — Pp.
28 | 531–543.
29 | [3] - Li Wei, Peng Minjun, Wang Qingzhong. False alarm reducing in
30 | PCA method for sensor fault detection in a nuclear power plant //
31 | Annals of Nuclear Energy. — 2018. — aug. — Vol. 118. — Pp. 131–139.
32 |
33 | Parameters
34 | ----------
35 | scaling : boolean, default = False
36 | If True StandartScaler is used in the pipeline.
37 | If False no scaling procedures are used.
38 |
39 | using_pca : boolean, default = True
40 | If True T2+Q based on PCA is used as anomaly detection method.
41 | If False T2 without PCA is used as anomaly detection method.
42 |
43 | explained_variance : object, default = 0.85
44 | Proportion of the explained variance for principal components
45 | selection. Relevant only if using_pca=True.
46 |
47 | p_value : object, default = 0.999
48 | P value for upper control limits selection. Shows the proportion
49 | of the number of points in train set perceived as normal.
50 |
51 | Examples
52 | --------
53 | T2+Q based on PCA:
54 |
55 | from ControlCharts import T2
56 | import pandas as pd
57 | import numpy as np
58 | df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
59 | t2 = T2()
60 | t2.fit(df.iloc[:20])
61 | t2.predict(df)
62 |
63 | T2 without PCA:
64 |
65 | from ControlCharts import T2
66 | import pandas as pd
67 | import numpy as np
68 | df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
69 | t2 = T2(using_pca=False)
70 | t2.fit(df.iloc[:20])
71 | t2.predict(df)
72 |
73 | More examples at:
74 | https://github.com/YKatser/control-charts/tree/main/examples
75 | """
76 |
77 | def __init__(
78 | self,
79 | scaling=False,
80 | using_pca=True,
81 | explained_variance=0.85,
82 | p_value=0.999,
83 | ):
84 | self.scaling = scaling
85 | self.using_pca = using_pca
86 | self.explained_variance = explained_variance
87 | self.p_value = p_value
88 |
89 | # T2 and Q statistics calculations
90 | def _t2_calculation(self, x):
91 | t2 = []
92 | for i in range(len(x)):
93 | t2.append(x[i] @ self.inv_cov @ x[i].T)
94 | return t2
95 |
96 | def _q_calculation(self, x):
97 | q = []
98 | for i in range(len(x)):
99 | q.append(x[i] @ self.transform_rc @ x[i].T)
100 | return q
101 |
102 | # CALCULATING UPPER CONTROL LIMITS
103 | def _t2_ucl(self, x):
104 | if self.using_pca:
105 | m = self.n_components
106 | else:
107 | m = x.shape[1]
108 |
109 | n = len(x)
110 | linspace = np.linspace(0, 15, 10000)
111 | c_alpha = linspace[SS.f.cdf(linspace, m, n - m) < self.p_value][-1]
112 | # koef = m * (n-1) / (n-m)
113 | koef = m * (n - 1) * (n + 1) / (n * (n - m))
114 |
115 | self.t2_ucl = koef * c_alpha
116 |
117 | def _q_ucl(self, x):
118 | w, v = LA.eig(np.cov(x.T))
119 | sum_ = 0
120 | for i in range(self.n_components, len(w)):
121 | sum_ += w[i]
122 |
123 | tetta = []
124 | for i in [1, 2, 3]:
125 | tetta.append(sum_**i)
126 | h0 = 1 - 2 * tetta[0] * tetta[2] / (3 * tetta[1] ** 2)
127 | linspace = np.linspace(0, 15, 10000)
128 | c_alpha = linspace[SS.norm.cdf(linspace) < self.p_value][-1]
129 |
130 | self.q_ucl = tetta[0] * (
131 | 1
132 | + (c_alpha * h0 * sqrt(2 * tetta[1]) / tetta[0])
133 | + tetta[1] * h0 * (h0 - 1) / tetta[0] ** 2
134 | ) ** (1 / h0)
135 |
136 | # applying pca
137 | def _pca_applying(self, x):
138 | self.pca = PCA(n_components=self.explained_variance).fit(x)
139 | self.n_components = self.pca.n_components_
140 | self._EV = self.pca.components_.T
141 | return self.pca.transform(x)
142 |
143 | # PLOTTING AND SAVING RESULTS
144 | def plot_t2(self, t2=None, t2_ucl=None, save_fig=False, fig_name="T2"):
145 | """Plotting results of T2-statistic calculation with matplotlib
146 |
147 | Parameters
148 | ----------
149 | t2 : pandas.DataFrame(), default = None
150 | Results of T2-statistic calculation.
151 |
152 | t2_ucl : float or int, default = None
153 | Upper control limit for T2.
154 |
155 | save_fig : boolean, default = False
156 | If True there will be saved T2 chart as .png to the
157 | current folder.
158 |
159 | fig_name : str, default = 'T2'
160 | Name of the saved figure.
161 |
162 | Returns
163 | -------
164 | self : object.
165 | """
166 |
167 | if t2 is None:
168 | t2 = self.t2
169 | if t2_ucl is None:
170 | t2_ucl = self.t2_ucl
171 | plt.figure(figsize=(12, 4))
172 | plt.plot(t2, label="$T^2$-statistic")
173 | # for i in self.final_list:
174 | # plt.axvspan(i[0], i[1], facecolor='green', alpha=0.2, zorder=0,
175 | # label='Train set')
176 | plt.grid(True)
177 | plt.axhline(t2_ucl, zorder=10, color="r", label="UCL")
178 | plt.ylim(0, 3 * max(t2.min().values, t2_ucl))
179 | plt.xlim(t2.index.values[0], t2.index.values[-1])
180 | plt.title("$T^2$-statistic chart")
181 | plt.xlabel("Time")
182 | plt.ylabel("$T^2$-statistic value")
183 | plt.legend(["$T^2$-statistic", "UCL", "Train set"])
184 | plt.tight_layout()
185 | if save_fig:
186 | self._save(name=fig_name)
187 |
188 | def plot_q(self, q=None, q_ucl=None, save_fig=False, fig_name="Q"):
189 | """Plotting results of Q-statistic calculation with matplotlib
190 |
191 | Parameters
192 | ----------
193 | q : pandas.DataFrame(), default = None
194 | Results of Q-statistic calculation.
195 |
196 | q_ucl : float or int, default = None
197 | Upper control limit for Q.
198 |
199 | save_fig : boolean, default = False
200 | If True there will be saved Q chart as .png to the
201 | current folder.
202 |
203 | fig_name : str, default = 'Q'
204 | Name of the saved figure.
205 |
206 | Returns
207 | -------
208 | self : object.
209 | """
210 |
211 | if q is None:
212 | q = self.q
213 | if q_ucl is None:
214 | q_ucl = self.q_ucl
215 | plt.figure(figsize=(12, 4))
216 | plt.plot(q, label="$Q$-statistic")
217 | # for i in self.final_list:
218 | # plt.axvspan(i[0], i[1], facecolor='green', alpha=0.2, zorder=0,
219 | # label='Train set')
220 | plt.grid(True)
221 | plt.axhline(q_ucl, zorder=10, color="r", label="UCL")
222 | plt.ylim(0, 3 * max(q.min().values, q_ucl))
223 | plt.xlim(q.index.values[0], q.index.values[-1])
224 | plt.title("$Q$-statistic chart")
225 | plt.xlabel("Time")
226 | plt.ylabel("$Q$-statistic value")
227 | plt.legend(["$Q$-statistic", "UCL", "Train set"])
228 | plt.tight_layout()
229 | if save_fig:
230 | self._save(name=fig_name)
231 |
232 | @staticmethod
233 | def _save(name="", fmt="png"):
234 | pwd = os.getcwd()
235 | iPath = pwd + "/pictures/"
236 | if not os.path.exists(iPath):
237 | os.mkdir(iPath)
238 | os.chdir(iPath)
239 | plt.savefig(f"{name}.{fmt}", fmt="png", dpi=150, bbox_inches="tight")
240 | os.chdir(pwd)
241 |
242 | def fit(self, x):
243 | """Computation of the inversed covariance matrix, matrix of
244 | transformation to the residual space (in case of
245 | using_pca=True) and standart scaler fitting (in case of using
246 | scaling=True).
247 |
248 | Parameters
249 | ----------
250 | x : pandas.DataFrame()
251 | Training set.
252 |
253 | Returns
254 | -------
255 | self : object.
256 | """
257 |
258 | x = x.copy()
259 |
260 | # removing constant columns
261 | initial_cols_number = len(x.columns)
262 | x = x.loc[:, (x != x.iloc[0]).any()]
263 | self._feature_names_in = x.columns
264 | if initial_cols_number > len(x.columns):
265 | print("Constant columns removed")
266 |
267 | if self.scaling:
268 | # fitting PCA and calculation of scaler, EV
269 | self.scaler = StandardScaler()
270 | self.scaler.fit(x)
271 | x_ = self.scaler.transform(x)
272 | else:
273 | x_ = x.values
274 |
275 | if self.using_pca:
276 | x_pc = self._pca_applying(x_)
277 | else:
278 | self.n_components = x.shape[1]
279 |
280 | if self.n_components == x.shape[1]:
281 | # preparing inv_cov for T2
282 | self.inv_cov = LA.inv(np.cov(x_.T))
283 |
284 | # calculating T2_ucl
285 | self._t2_ucl(x_)
286 | if self.using_pca:
287 | print("""Number of principal components is equal to dataset \
288 | shape. Q-statistics is unavailable.""")
289 | else:
290 | # preparing inv_cov for T2 (principal space)
291 | self.inv_cov = LA.inv(np.cov(x_pc.T))
292 |
293 | # preparing transform matrix for Q (to residual space)
294 | self.transform_rc = np.eye(len(self._EV)) - np.dot(
295 | self._EV, self._EV.T
296 | )
297 |
298 | # calculating t2_ucl and q_ucl
299 | self._t2_ucl(x_)
300 | self._q_ucl(x_)
301 |
302 | # calculating train indices
303 | # indices = x.index.tolist()
304 | # diff = x.index.to_series().diff()
305 | # list_of_ind = diff[diff > diff.mean() + 3 * diff.std()].index.tolist()
306 |
307 | def predict(
308 | self,
309 | x,
310 | plot_fig=True,
311 | save_fig=False,
312 | fig_name=["T2", "Q"],
313 | window_size=1,
314 | ):
315 | """Computation of T2-statistic or T2-statistic+Q-statistic for
316 | the test dataset.
317 |
318 | Parameters
319 | ----------
320 | x : pandas.DataFrame()
321 | Testing dataset.
322 |
323 | plot_fig : boolean, default = True
324 | If True there will be plotted T2-statistics or
325 | T2-statistics+Q-statistics chart.
326 |
327 | save_fig : boolean, default = False
328 | If True there will be saved T2 and Q charts as .png to the
329 | current folder.
330 |
331 | fig_name : list of one or two str, default = ['T2','Q']
332 | Names of the saved figures.
333 |
334 | window_size : int, default = 1
335 | Size of the window for median filter as a postprocessing.
336 |
337 | Returns
338 | -------
339 | self : object
340 | Plotting and saving T2 or T2+Q charts. To get DataFrames
341 | with T2 or Q values call self.t2 or self.q.
342 | """
343 |
344 | x = x.copy()
345 | x = x.loc[:, self._feature_names_in]
346 | if self.scaling:
347 | x_ = self.scaler.transform(x)
348 | else:
349 | x_ = x.values
350 |
351 | if self.n_components != x.shape[1]:
352 | # calculating T2
353 | self.t2 = (
354 | DataFrame(
355 | self._t2_calculation(self.pca.transform(x_)),
356 | index=x.index,
357 | columns=["T2"],
358 | )
359 | .rolling(window_size)
360 | .median()
361 | )
362 |
363 | # calculating Q
364 | self.q = (
365 | DataFrame(
366 | self._q_calculation(x_), index=x.index, columns=["Q"]
367 | )
368 | .rolling(window_size)
369 | .median()
370 | )
371 |
372 | # plotting
373 | if plot_fig:
374 | self.plot_t2(
375 | t2=self.t2,
376 | t2_ucl=self.t2_ucl,
377 | save_fig=save_fig,
378 | fig_name=fig_name[0],
379 | )
380 | self.plot_q(
381 | q=self.q,
382 | q_ucl=self.q_ucl,
383 | save_fig=save_fig,
384 | fig_name=fig_name[1],
385 | )
386 |
387 | else:
388 | # calculating T2
389 | self.t2 = (
390 | DataFrame(
391 | self._t2_calculation(x_), index=x.index, columns=["T2"]
392 | )
393 | .rolling(window_size)
394 | .median()
395 | )
396 |
397 | # plotting
398 | if plot_fig:
399 | self.plot_t2(self.t2)
400 | if save_fig:
401 | self._save(name=fig_name[0])
402 |
--------------------------------------------------------------------------------
/core/utils.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import matplotlib.pyplot as plt
4 | import numpy as np
5 | import pandas as pd
6 | from sklearn.model_selection import train_test_split
7 |
8 | from .metrics import chp_score
9 |
10 |
11 | def load_skab():
12 | path_to_data = "../data/"
13 | # benchmark files checking
14 | all_files = []
15 |
16 | for root, dirs, files in os.walk(path_to_data):
17 | for file in files:
18 | if file.endswith(".csv"):
19 | all_files.append(os.path.join(root, file))
20 |
21 | # datasets with anomalies loading
22 | list_of_df = [
23 | pd.read_csv(file, sep=";", index_col="datetime", parse_dates=True)
24 | for file in all_files
25 | if "anomaly-free" not in file
26 | ]
27 | # anomaly-free df loading
28 | anomaly_free_df = pd.read_csv(
29 | [file for file in all_files if "anomaly-free" in file][0],
30 | sep=";",
31 | index_col="datetime",
32 | parse_dates=True,
33 | )
34 |
35 | return list_of_df, anomaly_free_df
36 |
37 |
38 | def preprocess_skab(list_of_df):
39 | Xy_traintest_list: list[list] = []
40 | for df in list_of_df:
41 | Xy_traintest_list.append(
42 | train_test_split(
43 | df.drop(["anomaly", "changepoint"], axis=1),
44 | df[["anomaly", "changepoint"]],
45 | train_size=400,
46 | shuffle=False,
47 | random_state=0,
48 | )
49 | )
50 | return Xy_traintest_list
51 |
52 |
53 | def load_preprocess_skab():
54 | list_of_df, _ = load_skab()
55 | Xy_traintest_list = preprocess_skab(list_of_df)
56 | return Xy_traintest_list
57 |
58 |
59 | # Generated training sequences for use in the model.
60 | def create_sequences(values, time_steps):
61 | output = []
62 | for i in range(len(values) - time_steps + 1):
63 | output.append(values[i : (i + time_steps)])
64 | return np.stack(output)
65 |
66 |
67 | def plot_results(*true_pred_pairs: tuple[pd.Series, pd.Series]):
68 | n = len(true_pred_pairs)
69 | fig, axs = plt.subplots(n, 1, figsize=(12, 3 * n), sharex=True)
70 | if not isinstance(axs, (list | np.ndarray)):
71 | axs = [axs]
72 | for ax, (true, pred) in zip(axs, true_pred_pairs):
73 | ax.plot(true, label="True", marker="o", markersize=5)
74 | ax.plot(pred, label="Predicted", marker="x", markersize=5)
75 | ax.set_title(f"{true.name} detection")
76 | ax.legend()
77 | fig.show()
78 |
79 |
80 | def print_results(
81 | y_true,
82 | y_pred,
83 | score_kwargs: list[dict],
84 | ):
85 | for kwargs in score_kwargs:
86 | print(kwargs)
87 | chp_score(y_true, y_pred, **kwargs)
88 | print()
89 |
--------------------------------------------------------------------------------
/data/README.md:
--------------------------------------------------------------------------------
1 | ```
2 | └── data # Data files and processing Jupyter Notebook
3 | ├── Load data.ipynb # Jupyter Notebook to load all data
4 | ├── anomaly-free
5 | │ └── anomaly-free.csv # Data obtained from the experiments with normal mode
6 | ├── valve2 # Data obtained from the experiments with closing the valve at the outlet of the flow from the pump.
7 | │ ├── 1.csv
8 | │ ├── 2.csv
9 | │ ├── 3.csv
10 | │ └── 4.csv
11 | ├── valve1 # Data obtained from the experiments with closing the valve at the flow inlet to the pump.
12 | │ ├── 1.csv
13 | │ ├── 2.csv
14 | │ ├── 3.csv
15 | │ ├── 4.csv
16 | │ ├── 5.csv
17 | │ ├── 6.csv
18 | │ ├── 7.csv
19 | │ ├── 8.csv
20 | │ ├── 9.csv
21 | │ ├── 10.csv
22 | │ ├── 11.csv
23 | │ ├── 12.csv
24 | │ ├── 12.csv
25 | │ ├── 13.csv
26 | │ ├── 14.csv
27 | │ ├── 15.csv
28 | │ └── 16.csv
29 | └── other # Data obtained from the other experiments
30 | ├── 1.csv # Simulation of fluid leaks and fluid additions
31 | ├── 2.csv # Simulation of fluid leaks and fluid additions
32 | ├── 3.csv # Simulation of fluid leaks and fluid additions
33 | ├── 4.csv # Simulation of fluid leaks and fluid additions
34 | ├── 5.csv # Sharply behavior of rotor imbalance
35 | ├── 6.csv # Linear behavior of rotor imbalance
36 | ├── 7.csv # Step behavior of rotor imbalance
37 | ├── 8.csv # Dirac delta function behavior of rotor imbalance
38 | ├── 9.csv # Exponential behavior of rotor imbalance
39 | ├── 10.csv # The slow increase in the amount of water in the circuit
40 | ├── 11.csv # The sudden increase in the amount of water in the circuit
41 | ├── 12.csv # Draining water from the tank until cavitation
42 | ├── 13.csv # Two-phase flow supply to the pump inlet (cavitation)
43 | └── 14.csv # Water supply of increased temperature
44 | ```
45 |
--------------------------------------------------------------------------------
/docs/contributing.md:
--------------------------------------------------------------------------------
1 | # Contributing to SKAB repository
2 |
3 | We are glad you are reading this because work on the SKAB benchmark is still in progress, and contribution is welcome.
4 |
5 | ## How to Contribute
6 |
7 | 1. Make sure you have a GitHub account.
8 | 2. Fork the repository for the relevant book.
9 | 3. Create a new branch on which to make your change, e.g.
10 | `git checkout -b my_contribution`
11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted.
12 | 5. Submit a [pull request](https://github.com/waico/skab/compare?expand=1).
13 |
14 | Thank you for your contribution!
15 |
--------------------------------------------------------------------------------
/docs/pictures/nab-metric.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/waico/SKAB/b2c0d46c2971dcbfe71e26087b6d231998bb91c2/docs/pictures/nab-metric.jpg
--------------------------------------------------------------------------------
/docs/pictures/skab.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/waico/SKAB/b2c0d46c2971dcbfe71e26087b6d231998bb91c2/docs/pictures/skab.png
--------------------------------------------------------------------------------
/docs/pictures/testbed.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/waico/SKAB/b2c0d46c2971dcbfe71e26087b6d231998bb91c2/docs/pictures/testbed.png
--------------------------------------------------------------------------------
/notebooks/ArimaFD.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Pipeline for the anomaly detection on the SKAB using ARIMA fault detection algorithm"
8 | ]
9 | },
10 | {
11 | "cell_type": "markdown",
12 | "metadata": {},
13 | "source": [
14 | "Details regarding the SKAB one can find in the [SKAB repository](https://github.com/waico/SKAB)."
15 | ]
16 | },
17 | {
18 | "cell_type": "markdown",
19 | "metadata": {},
20 | "source": [
21 | "The idea behind this algorithm is to use ARIMA weights as features for the anomaly detection algorithm. Using discrete differences of weight coefficients for different heuristic methods for obtaining function, which characterized the state (anomaly, not anomaly) using a threshold. \n",
22 | "\n",
23 | "Links at [PyPi](https://pypi.org/project/arimafd/), [GitHub](https://github.com/waico/arimafd) and [paper](https://waico.ru)"
24 | ]
25 | },
26 | {
27 | "cell_type": "code",
28 | "execution_count": null,
29 | "metadata": {},
30 | "outputs": [],
31 | "source": [
32 | "# libraries importing\n",
33 | "import sys\n",
34 | "import warnings\n",
35 | "\n",
36 | "import pandas as pd\n",
37 | "from arimafd import Arima_anomaly_detection\n",
38 | "\n",
39 | "sys.path.append(\"..\")\n",
40 | "from core.metrics import chp_score\n",
41 | "from core.utils import load_preprocess_skab, plot_results\n",
42 | "\n",
43 | "warnings.filterwarnings(\"ignore\", category=UserWarning)"
44 | ]
45 | },
46 | {
47 | "cell_type": "markdown",
48 | "metadata": {},
49 | "source": [
50 | "## Data"
51 | ]
52 | },
53 | {
54 | "cell_type": "code",
55 | "execution_count": null,
56 | "metadata": {},
57 | "outputs": [],
58 | "source": [
59 | "Xy_traintest_list = load_preprocess_skab()"
60 | ]
61 | },
62 | {
63 | "cell_type": "markdown",
64 | "metadata": {},
65 | "source": [
66 | "## Method"
67 | ]
68 | },
69 | {
70 | "cell_type": "code",
71 | "execution_count": null,
72 | "metadata": {},
73 | "outputs": [],
74 | "source": [
75 | "predicted_outlier, predicted_cp = [], []\n",
76 | "true_outlier, true_cp = [], []\n",
77 | "for X_train, X_test, y_train, y_test in Xy_traintest_list:\n",
78 | " model = Arima_anomaly_detection()\n",
79 | " model.fit(X_train)\n",
80 | " prediction = pd.Series(\n",
81 | " model.predict(X_test),\n",
82 | " index=X_test.index,\n",
83 | " )\n",
84 | "\n",
85 | " # predicted outliers saving\n",
86 | " predicted_outlier.append(prediction)\n",
87 | "\n",
88 | " # predicted CPs saving\n",
89 | " prediction_cp = prediction.rolling(30).max().fillna(0).diff().abs()\n",
90 | " prediction_cp[0] = prediction[0]\n",
91 | " predicted_cp.append(prediction_cp)\n",
92 | "\n",
93 | " true_outlier.append(y_test[\"anomaly\"])\n",
94 | " true_cp.append(y_test[\"changepoint\"])"
95 | ]
96 | },
97 | {
98 | "cell_type": "markdown",
99 | "metadata": {},
100 | "source": [
101 | "### Results visualization"
102 | ]
103 | },
104 | {
105 | "cell_type": "code",
106 | "execution_count": null,
107 | "metadata": {},
108 | "outputs": [
109 | {
110 | "data": {
111 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAA+MAAAEpCAYAAAD4aPMrAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8fJSN1AAAACXBIWXMAAA9hAAAPYQGoP6dpAABJw0lEQVR4nO3de3wU1f3/8fdurtxCEELCJRDAC+AFKkjEVgFF0frFKrXwBS0Xb1VBkehXQJGA/jTeG7UoolWwyldUKlrhi5dAtCJKgdJaFcodFAhQTQIBEtid3x9hl53dBLIhk0lyXs/HI5KdzOycOSZnzmfPZ87xWJZlCQAAAAAA1Bqv2wUAAAAAAMA0BOMAAAAAANQygnEAAAAAAGoZwTgAAAAAALWMYBwAAAAAgFpGMA4AAAAAQC0jGAcAAAAAoJYRjAMAAAAAUMsIxgEAAAAAqGUE4wCAOmf27NnyeDxauXKl20Wps/r376/+/fu7WgaPx6Np06a5Wobqqgv1BwAwG8E4AACGmTt3rnJzc107/44dOzRt2jStWbPG0fN8++23mjZtmrZs2eLoeQAAqA6CcQAA6qGPPvpIH330UbWOrQvB+PTp02slGJ8+fXqFwfjJ1B8AADUh1u0CAACA6MXHx7tdhHqN+gMAuI2RcQBArfvhhx904403qm3btkpISFCnTp102223qayszLZfaWmpsrKylJKSoiZNmuiaa67Rnj17bPu89957uvLKK4Pv1aVLFz300EPy+Xy2/fr376+zzjpL3377rQYMGKDGjRurXbt2evzxxyPKt3XrVl111VVq0qSJWrdurQkTJujDDz+Ux+NRfn6+bd+vvvpKl19+uZo3b67GjRurX79+WrZsmW2fadOmyePxaO3atRo6dKiSkpLUsmVLjR8/XocOHbLte+TIET300EPq0qWLEhISlJGRofvuu0+lpaUR1xP6zHN+fr48Ho/eeustPfzww2rfvr0SExN1ySWXaMOGDbbjFi5cqK1bt8rj8cjj8SgjI6PC/0+h/x8mTJiglJQUNWvWTFdddZW+//77Cvf94YcfdMMNNyg1NVUJCQk688wz9corr9jKed5550mSxowZEyzD7Nmzo6rTwLkq+z2aPXu2fvOb30iSBgwYEDxP4P9fRc+M7969WzfeeKNSU1OVmJioHj16aM6cObZ9tmzZIo/HoyeffFKzZs0K/n8677zz9Le//e249QgAQChGxgEAtWrHjh3q06ePCgsLdcstt6hr16764Ycf9M477+jAgQO2Ecs77rhDLVq0UHZ2trZs2aLc3FyNGzdO8+bNC+4ze/ZsNW3aVFlZWWratKmWLFmiqVOnqri4WE888YTt3D/99JMuv/xyDRkyREOHDtU777yjiRMn6uyzz9YVV1whSSopKdHFF1+snTt3avz48UpLS9PcuXO1dOnSiGtZsmSJrrjiCvXq1UvZ2dnyer169dVXdfHFF+uvf/2r+vTpY9t/6NChysjIUE5Ojr788ks9++yz+umnn/Taa68F97nppps0Z84cXXvttbr77rv11VdfKScnR999953efffdE9bvo48+Kq/Xq3vuuUdFRUV6/PHHdd111+mrr76SJN1///0qKirS999/r9///veSpKZNmx73PW+66Sa9/vrrGjFihC644AItWbJEV155ZcR+BQUFOv/88+XxeDRu3DilpKTo//7v/3TjjTequLhYd911l7p166YHH3xQU6dO1S233KILL7xQknTBBRdEVacn+j266KKLdOedd+rZZ5/Vfffdp27duklS8N9wBw8eVP/+/bVhwwaNGzdOnTp10ttvv63Ro0ersLBQ48ePt+0/d+5c7du3T7/73e/k8Xj0+OOPa8iQIdq0aZPi4uJO+P8JAABZAADUopEjR1per9f629/+FvEzv99vWZZlvfrqq5Yka+DAgcFtlmVZEyZMsGJiYqzCwsLgtgMHDkS8z+9+9zurcePG1qFDh4Lb+vXrZ0myXnvtteC20tJSKy0tzfr1r38d3PbUU09ZkqwFCxYEtx08eNDq2rWrJclaunRpsKynnX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Af119/faXB9DnnnFOl9zhRnf7444/VL2gNcaueAQANB8E4AKDWpKSkKCkpSf/6179q5P3y8/P1n//8R3/+85910UUXBbdv3ry52u/ZsWNHffvtt7IsyxYUh85ILik4UpyUlKSBAwdW6b3Xr1+vTp062d7T7/cHZzPv2LGj/H6/1q9fb5torKCgQIWFherYsWN1L8smmmA/UKaNGzfaRsPXrVtn2y8w07rP5zthfVR2/qrWaVV/j6K9zn/+85/y+/220fHAow41VfcAAATwzDgAoNZ4vV5dffXV+stf/qKVK1dG/DzaUcXA6GTocWVlZXr++eerXcZBgwbphx9+0Pvvvx/cdujQIb300ku2/Xr16qUuXbroySef1P79+yPeJ3wJNkmaMWOG7fVzzz0nScGZ3H/5y19KknJzc237Pf3005JU4Qzm1dGkSZOIFP7KBMr27LPP2raHlzEmJka//vWvNX/+/AqD5ND6aNKkiaTyzIZQVa3Tqv4eVXaeivzyl7/Url27bDP1HzlyRM8995yaNm2qfv36nfA9AACIBiPjAIBa9cgjj+ijjz5Sv379dMstt6hbt27auXOn3n77bX3++edKTk6u8ntdcMEFatGihUaNGqU777xTHo9Hf/rTn04qVfh3v/ud/vCHP2j48OEaP3682rRpozfeeEOJiYmSjo22er1evfzyy7riiit05plnasyYMWrXrp1++OEHLV26VElJSfrLX/5ie+/Nmzfrqquu0uWXX67ly5cHlwvr0aOHJKlHjx4aNWqUZs2aFUzBX7FihebMmaOrr75aAwYMqPZ1herVq5fmzZunrKwsnXfeeWratKkGDx5c4b49e/bU8OHD9fzzz6uoqEgXXHCB8vLyIjIFpPJl1ZYuXarMzEzdfPPN6t69u3788UetXr1an3zySTC9vEuXLkpOTtbMmTPVrFkzNWnSRJmZmerUqVOV67Qqv0c9e/ZUTEyMHnvsMRUVFSkhIUEXX3yxWrduHVH2W265RS+++KJGjx6tVatWKSMjQ++8846WLVum3NxcNWvWrEbqHgCAIJdmcQcAGGzr1q3WyJEjrZSUFCshIcHq3LmzNXbs2OCSXIGlzcKXrQos3xW6VNWyZcus888/32r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ZL/V/7a8kX5Pif3y9SoUSOVlZVJkvLy8rRu3Tp9/PHH+uCDD3T48GENGjRIzZo101//+lctW7ZMTZs21eWXXx485qmnntLs2bP1yiuv6PPPP9ePP/6od99997jnHDlypP73f/9Xzz77rL777ju9+OKLatq0qdLT0zV//nxJ0rp167Rz504988wzkqScnBy99tprmjlzpr755htNmDBB119/vT799FNJ5R8aDBkyRIMHD9aaNWt00003adKkSSdVN04jTR2A447Npu5yQVxikZoJAKwscRRp6g3U4QPSI22rd+xnT5R/Vfb6RO7bIcU3ifq0lmUpLy9PH374oe644w7t2bNHTZo00csvvxxMT3/99dfl9/v18ssvy+PxSJJeffVVJScnKz8/X5dddplyc3M1efJkDRkyRJI0c+ZMffjhh5We99///rfeeustffzxxxo4cKAkqXPnzsGfB1LaW7dureTkZEnlI+mPPPKIPvnkE/Xt2zd4zOeff64XX3xR/fr10wsvvKAuXbroqaeekiSdccYZ+vrrr/XYY49FXTe1hWAcgOOMn8DNT2omANhjT3NbQ9LU4bYPPvhATZs21eHDh+X3+zVixAhNmzZNY8eO1dlnn217Tvwf//iHNmzYoGbNmtne49ChQ9q4caOKioq0c+dOZWZmBn8WGxur3r17V5oBs2bNGsXExKhfv35VLvOGDRt04MABXXrppbbtZWVl+tnPfiZJ+u6772zlkBQM3OsqgnEAjgt2PAwdBfCTpg4AYWnqrhXDfYbPo9JgxTUuH6GO1ue/Lx8Fj4mXfGXSRf8j/WJC9OeOwoABA/TCCy8oPj5ebdu2VWzssZCwSRP7CPv+/fvVq1cvvfHGGxHvk5KSEl05j2rUqFHUx+zfv1+StHDhQrVr1872s4SEhGqVoy4gGAfgONM7HP7QfEzD6wKAufxkCUlinfEGy+OJPlX808fLA/EB90v97j06edvD5YF5v3udKafKA+5TTz21Svuee+65mjdvnlq3bq2kpKQK92nTpo2++uorXXTRRZKkI0eOaNWqVTr33HMr3P/ss8+W3+/Xp59+GkxTDxUYmff5fMFt3bt3V0JCgrZt21bpiHq3bt30/vvv27Z9+eWXJ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dbHk434mPC93X6fumk+dz6u+hLv0tVOdnlmXpwGG/7RxNE2KPza1Rx343nTpf6RGf/lNyOLg9LkZKjIut9L2r+vvUonG8fn5qK918UWd1atXkhOVp6ML75Sfzu3uinx2PE/doJ8tZm33P+vI763QcGnUwnpmZqfPOO09/+MMfJEl+v1/p6em64447NGnSpIj9hw0bppKSEn3wwQfBbeeff7569uypmTNnVumcdT0Y/+aNSSpemx8MOJb7z1Rf7zc607tFRVYT2yzKzT0lKraaBL+vTOC4pJB9KjoufL8iq4l2qJXaam9wv5o8X/j+lhQ8LrB/YHtNni9wzPdWitI9e4LHFVtNtN1KUXvPnho/38mc82TOV516rW/nS/KURPW3URPnC7yuyt8H56va+STpG3+GJOlM75ZK36smz1dsNdE2q7U6eHZX+n41fb4Tve+JysP5TnxcdduGunY+p/4e6tLfgqRq/aw+/W668bdwMr9P31sptvM179pfZ173aKXlaejC++WS1N5T/mG4m7/XNXGPdrKctdkXrE+/s3UqGC8rK1Pjxo31zjvv6Oqrrw5uHzVqlAoLC/Xee+9FHNOhQwdlZWXprrvuCm7Lzs7WggUL9I9//KNK563LwfjmvSV69/d3KivuHbeLElTob6xk7wG3iwHUSbX999HQzwcAqFuePXy10q+6X6lJiW4XpdYVFB3S9r88rDvjFrhdlApxj67Y00eu1ZC7nlVGHRwhdzoOjY1m571798rn8yk1NdW2PTU1VWvXrq3wmF27dlW4/65duyo9T2lpqUpLS4Ovi4uLoylmrXpr5XbN9A1RrI7UmT98/siBytX230dDPx8AoG65M26B9H8L3C6Ge+LcLkDluEdHeurwtfqDb4gOr9yuiZd3dbs4ta5Ozqaek5Oj5s2bB7/S09PdLlKlvv/poCxJL/iucrsoAAAAAFAvlFmxes43RJbKYyoTRTUy3qpVK8XExKigoMC2vaCgQGlpaRUek5aWFtX+kjR58mRlZWUFXxcXF9fZgLx9i0bySLopxuwZ4v2WR15PVNMPoApqu175/wgAQP317OGrNdN3lW66sLOyLj3d7eLUuqc//rde/usm3Rrzfp3JWK1varMv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MOAAAAAAAtYxgHAAAAACAWkYwDgAAAABALSMYBwAAAACglhGMAwAAAABQywjGAQAAAACoZQTjAAAAAADUMoJxAAAAAABqGcE4AAAAAAC1jGAcAAAAAIBaRjAOAAAAAEAtIxgHAAAAAKCW/X/77AbOjCbLogAAAABJRU5ErkJggg==",
112 | "text/plain": [
113 | ""
114 | ]
115 | },
116 | "metadata": {},
117 | "output_type": "display_data"
118 | }
119 | ],
120 | "source": [
121 | "# [donotremove]\n",
122 | "plot_results(\n",
123 | " (true_cp[1], predicted_cp[1]),\n",
124 | ")"
125 | ]
126 | },
127 | {
128 | "cell_type": "markdown",
129 | "metadata": {},
130 | "source": [
131 | "## Evaluation (metrics calculation)"
132 | ]
133 | },
134 | {
135 | "cell_type": "code",
136 | "execution_count": null,
137 | "metadata": {},
138 | "outputs": [],
139 | "source": [
140 | "import pickle\n",
141 | "\n",
142 | "pickle.dump(\n",
143 | " predicted_outlier,\n",
144 | " open(f\"../results/results-{model.__class__.__name__}.pkl\", \"wb\"),\n",
145 | ")"
146 | ]
147 | },
148 | {
149 | "cell_type": "markdown",
150 | "metadata": {},
151 | "source": [
152 | "### Binary classification (outlier detection) metrics"
153 | ]
154 | },
155 | {
156 | "cell_type": "code",
157 | "execution_count": null,
158 | "metadata": {},
159 | "outputs": [
160 | {
161 | "name": "stdout",
162 | "output_type": "stream",
163 | "text": [
164 | "False Alarm Rate 0.01 %\n",
165 | "Missing Alarm Rate 100.0 %\n",
166 | "F1 metric 0.0\n"
167 | ]
168 | }
169 | ],
170 | "source": [
171 | "# [donotremove]\n",
172 | "# binary classification metrics calculation\n",
173 | "binary = chp_score(true_outlier, predicted_outlier, metric=\"binary\")"
174 | ]
175 | },
176 | {
177 | "cell_type": "markdown",
178 | "metadata": {},
179 | "source": [
180 | "not implemented"
181 | ]
182 | },
183 | {
184 | "cell_type": "markdown",
185 | "metadata": {},
186 | "source": [
187 | "### Changepoint detection metrics"
188 | ]
189 | },
190 | {
191 | "cell_type": "code",
192 | "execution_count": null,
193 | "metadata": {},
194 | "outputs": [
195 | {
196 | "name": "stdout",
197 | "output_type": "stream",
198 | "text": [
199 | "Amount of true anomalies 127\n",
200 | "A number of missed CPs = 127\n",
201 | "A number of FPs = 2\n",
202 | "Average time nan\n"
203 | ]
204 | },
205 | {
206 | "name": "stderr",
207 | "output_type": "stream",
208 | "text": [
209 | "/Users/mw/pyprojects/SKAB/.venv/lib/python3.10/site-packages/numpy/core/fromnumeric.py:3504: RuntimeWarning: Mean of empty slice.\n",
210 | " return _methods._mean(a, axis=axis, dtype=dtype,\n",
211 | "/Users/mw/pyprojects/SKAB/.venv/lib/python3.10/site-packages/numpy/core/_methods.py:129: RuntimeWarning: invalid value encountered in scalar divide\n",
212 | " ret = ret.dtype.type(ret / rcount)\n"
213 | ]
214 | }
215 | ],
216 | "source": [
217 | "# [donotremove]\n",
218 | "# average detection delay metric calculation\n",
219 | "add = chp_score(\n",
220 | " true_cp,\n",
221 | " predicted_cp,\n",
222 | " metric=\"average_time\",\n",
223 | " window_width=\"60s\",\n",
224 | " anomaly_window_destination=\"righter\",\n",
225 | ")"
226 | ]
227 | },
228 | {
229 | "cell_type": "code",
230 | "execution_count": null,
231 | "metadata": {},
232 | "outputs": [
233 | {
234 | "name": "stdout",
235 | "output_type": "stream",
236 | "text": [
237 | "Standard - -0.09\n",
238 | "LowFP - -0.17\n",
239 | "LowFN - -0.06\n"
240 | ]
241 | }
242 | ],
243 | "source": [
244 | "# [donotremove]\n",
245 | "# nab metric calculation\n",
246 | "nab = chp_score(\n",
247 | " true_cp,\n",
248 | " predicted_cp,\n",
249 | " metric=\"nab\",\n",
250 | " window_width=\"60s\",\n",
251 | " anomaly_window_destination=\"righter\",\n",
252 | ")"
253 | ]
254 | }
255 | ],
256 | "metadata": {
257 | "kernelspec": {
258 | "display_name": "",
259 | "language": "python",
260 | "name": ""
261 | },
262 | "language_info": {
263 | "codemirror_mode": {
264 | "name": "ipython",
265 | "version": 3
266 | },
267 | "file_extension": ".py",
268 | "mimetype": "text/x-python",
269 | "name": "python",
270 | "nbconvert_exporter": "python",
271 | "pygments_lexer": "ipython3",
272 | "version": "3.10.14"
273 | },
274 | "toc": {
275 | "base_numbering": 1,
276 | "nav_menu": {
277 | "height": "282.997px",
278 | "width": "471.989px"
279 | },
280 | "number_sections": true,
281 | "sideBar": true,
282 | "skip_h1_title": false,
283 | "title_cell": "Table of Contents",
284 | "title_sidebar": "Contents",
285 | "toc_cell": false,
286 | "toc_position": {},
287 | "toc_section_display": true,
288 | "toc_window_display": false
289 | }
290 | },
291 | "nbformat": 4,
292 | "nbformat_minor": 4
293 | }
294 |
--------------------------------------------------------------------------------
/notebooks/README.md:
--------------------------------------------------------------------------------
1 | # Anomaly Detection Algorithms
2 |
3 | ### Hotelling's T-squared statistic
4 | Hotelling's statistic is one of the most popular statistical process control techniques. It is based on the Mahalanobis distance.
5 | Generally, it measures the distance between the new vector of values and the previously defined vector of normal values additionally using variances.
6 |
7 | [[notebook]](https://github.com/YKatser/ControlCharts/blob/main/examples/t2_SKAB.ipynb) [[paper]](https://www.semanticscholar.org/paper/Multivariate-Quality-Control-illustrated-by-the-air-Hotelling/529ba6c1a80b684d2f704a7565da305bb84f14e8)
8 |
9 | ### Hotelling's T-squared statistic + Q statistic (SPE index) based on PCA
10 | The combined index is based on PCA.
11 | Hotelling’s T-squared statistic measures variations in the principal component subspace.
12 | Q statistic measures the projection of the sample vector on the residual subspace.
13 | To avoid using two separated indicators (Hotelling's T-squared and Q statistics) for the process monitoring, we use a combined one based on logical or.
14 |
15 | [[notebook]](https://github.com/YKatser/ControlCharts/blob/main/examples/t2_with_q_SKAB.ipynb) [[paper]](https://analyticalsciencejournals.onlinelibrary.wiley.com/doi/abs/10.1002/cem.800)
16 |
17 | ### Isolation Forest
18 | Isolation Forest or iForest builds an ensemble of iTrees for a given data set, then anomalies are those instances which have short average path lengths on the iTrees.
19 |
20 | [[notebook]](https://github.com/waico/SKAB/blob/master/notebooks/isolation_forest.ipynb) [[paper]](https://ieeexplore.ieee.org/abstract/document/4781136?casa_token=kiHmrqDyGL4AAAAA:O4yM7O2WCXdQH2sQbpKUXAHiepBxUhc5odzbydmgTiz5f7ZEDYgkXltodCahlgIzArxUldce5LB9mg)
21 |
22 | ### LSTM-based NN (LSTM)
23 | LSTM-based neural network for anomaly detection using reconstruction error as an anomaly score.
24 |
25 | [[notebook]](https://github.com/waico/SKAB/blob/master/notebooks/LSTM.ipynb) [[paper]](https://arxiv.org/abs/1612.06676)
26 |
27 | ### Feed-Forward Autoencoder
28 | Feed-forward neural network with autoencoder architecture for anomaly detection using reconstruction error as an anomaly score.
29 |
30 | [[notebook]](https://github.com/waico/SKAB/blob/master/notebooks/autoencoder.ipynb) [[paper]](https://epubs.siam.org/doi/abs/10.1137/1.9781611974973.11)
31 |
32 | ### Convolutional Autoencoder (Conv-AE)
33 | A reconstruction convolutional autoencoder model to detect anomalies in timeseries data using reconstruction error as an anomaly score.
34 |
35 | [[notebook]](https://github.com/waico/SKAB/blob/master/notebooks/CAE.ipynb) [[paper]](https://keras.io/examples/timeseries/timeseries_anomaly_detection/)
36 |
37 | ### LSTM Autoencoder (LSTM-AE)
38 | If you inputs are sequences, rather than vectors or 2D images, then you may want to use as encoder and decoder a type of model that can capture temporal structure, such as a LSTM. To build a LSTM-based autoencoder, first use a LSTM encoder to turn your input sequences into a single vector that contains information about the entire sequence, then repeat this vector n times (where n is the number of timesteps in the output sequence), and run a LSTM decoder to turn this constant sequence into the target sequence.
39 |
40 | A reconstruction sequence-to-sequence (LSTM-based) autoencoder model to detect anomalies in timeseries data using reconstruction error as an anomaly score.
41 |
42 | [[notebook]](https://github.com/waico/SKAB/blob/master/notebooks/LSTM-AE.ipynb) [[paper]](https://machinelearningmastery.com/lstm-autoencoders/) [[paper]](https://blog.keras.io/building-autoencoders-in-keras.html)
43 |
44 | ### LSTM Variational Autoencoder (LSTM-VAE)
45 | A reconstruction LSTM variational autoencoder model to detect anomalies in timeseries data using reconstruction error as an anomaly score.
46 |
47 | [[notebook]](https://github.com/waico/SKAB/blob/master/notebooks/LSTM-VAE.ipynb) [[paper]](https://arxiv.org/pdf/1511.06349.pdf) [[code]](https://github.com/twairball/keras_lstm_vae)
48 |
49 | ### Variational Autoencoder (VAE)
50 | A reconstruction variational autoencoder (VAE) model to detect anomalies in timeseries data using reconstruction error as an anomaly score. VAE is an autoencoder that learns a latent variable model for its input data. So instead of letting your neural network learn an arbitrary function, you are learning the parameters of a probability distribution modeling your data. If you sample points from this distribution, you can generate new input data samples: a VAE is a "generative model".
51 |
52 | [[notebook]](https://github.com/waico/SKAB/blob/master/notebooks/VAE.ipynb) [[paper1]](https://arxiv.org/pdf/1312.6114.pdf) [[paper2]](https://dl.acm.org/doi/pdf/10.1145/3178876.3185996?casa_token=HVY_9X3NxToAAAAA%3AZzZNSpmDdI9bEbTCqC1R3fPLiP4SDHyH9l9VyHxZ9zsL_3UXblc7Fe-ZdMPI7gkyVN9orRYQ5j9C) [[code]](https://blog.keras.io/building-autoencoders-in-keras.html)
53 |
54 |
55 | ### MSCRED
56 | MSCRED - Multi-Scale Convolutional Recurrent Encoder-Decoder first constructs multi-scale (resolution) signature matrices to characterize multiple levels of the system statuses across different time steps.
57 | In particular, different levels of the system statuses are used to indicate the severity of different abnormal incidents.
58 | Subsequently, given the signature matrices, a convolutional encoder is employed to encode the inter-sensor (time series) correlations patterns and an attention based Convolutional Long-Short Term Memory (ConvLSTM) network is developed to capture the temporal patterns.
59 | Finally, with the feature maps which encode the inter-sensor correlations and temporal information, a convolutional decoder is used to reconstruct the signature matrices and the residual signature matrices are further utilized to detect and diagnose anomalies.
60 | The intuition is that MSCRED may not reconstruct the signature matrices well if it never observes similar system statuses before.
61 |
62 | [[notebook]](https://github.com/waico/SKAB/blob/master/notebooks/MSCRED.ipynb) [[paper]](https://ojs.aaai.org/index.php/AAAI/article/view/3942)
63 |
64 | ### MSET
65 | MSET - multivariate state estimation technique is a non-parametric and statistical modeling method, which calculates the estimated values based on the weighted average of historical data. In terms of procedure, MSET is similar to some nonparametric regression methods, such as, auto-associative kernel regression.
66 |
67 | [[notebook]](https://github.com/waico/SKAB/blob/master/notebooks/MSET.ipynb) [[paper]](https://inis.iaea.org/collection/NCLCollectionStore/_Public/32/025/32025817.pdf)
68 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.poetry]
2 | name = "notebooks"
3 | version = "0.1.0"
4 | description = ""
5 | authors = ["Your Name "]
6 | readme = "README.md"
7 |
8 | [tool.poetry.dependencies]
9 | python = ">=3.10,<3.11"
10 | arimafd = {git = "https://github.com/InSuperposition/arimafd.git", branch = "master"}
11 | tensorflow = "^2.15.0"
12 | sympy = "^1.12"
13 | lightgbm = "^4.3.0"
14 | matplotlib = "^3.8.4"
15 | ipykernel = "^6.29.4"
16 | ipython = "^8.24.0"
17 |
18 | [tool.poetry.group.dev.dependencies]
19 | pre-commit = "^3.7.0"
20 | ruff = "^0.4.2"
21 | ipykernel = "^6.29.4"
22 | pytest = "^8.2.0"
23 |
24 | [build-system]
25 | requires = ["poetry-core"]
26 | build-backend = "poetry.core.masonry.api"
27 |
--------------------------------------------------------------------------------
/results/results-Arima_anomaly_detection.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/waico/SKAB/b2c0d46c2971dcbfe71e26087b6d231998bb91c2/results/results-Arima_anomaly_detection.pkl
--------------------------------------------------------------------------------
/results/results-Conv_AE.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/waico/SKAB/b2c0d46c2971dcbfe71e26087b6d231998bb91c2/results/results-Conv_AE.pkl
--------------------------------------------------------------------------------
/results/results-Isolation_Forest.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/waico/SKAB/b2c0d46c2971dcbfe71e26087b6d231998bb91c2/results/results-Isolation_Forest.pkl
--------------------------------------------------------------------------------
/results/results-LSTM_AE.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/waico/SKAB/b2c0d46c2971dcbfe71e26087b6d231998bb91c2/results/results-LSTM_AE.pkl
--------------------------------------------------------------------------------
/results/results-MSCRED.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/waico/SKAB/b2c0d46c2971dcbfe71e26087b6d231998bb91c2/results/results-MSCRED.pkl
--------------------------------------------------------------------------------
/results/results-MSET.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/waico/SKAB/b2c0d46c2971dcbfe71e26087b6d231998bb91c2/results/results-MSET.pkl
--------------------------------------------------------------------------------
/results/results-T2-q.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/waico/SKAB/b2c0d46c2971dcbfe71e26087b6d231998bb91c2/results/results-T2-q.pkl
--------------------------------------------------------------------------------
/results/results-T2.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/waico/SKAB/b2c0d46c2971dcbfe71e26087b6d231998bb91c2/results/results-T2.pkl
--------------------------------------------------------------------------------
/results/results-Vanilla_AE.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/waico/SKAB/b2c0d46c2971dcbfe71e26087b6d231998bb91c2/results/results-Vanilla_AE.pkl
--------------------------------------------------------------------------------
/results/results-Vanilla_LSTM.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/waico/SKAB/b2c0d46c2971dcbfe71e26087b6d231998bb91c2/results/results-Vanilla_LSTM.pkl
--------------------------------------------------------------------------------