├── .DS_Store
├── .gitattributes
├── .gitignore
├── HoeffdingTree
├── LICENSE
├── README.md
├── __init__.py
├── core
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-36.pyc
│ │ ├── attribute.cpython-36.pyc
│ │ ├── dataset.cpython-36.pyc
│ │ ├── instance.cpython-36.pyc
│ │ ├── univariatenormalestimator.cpython-36.pyc
│ │ └── utils.cpython-36.pyc
│ ├── attribute.py
│ ├── dataset.py
│ ├── instance.py
│ ├── univariatenormalestimator.py
│ └── utils.py
├── hoeffdingtree.py
├── ht
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-36.pyc
│ │ ├── activehnode.cpython-36.pyc
│ │ ├── conditionalsufficientstats.cpython-36.pyc
│ │ ├── gaussianconditionalsufficientstats.cpython-36.pyc
│ │ ├── ginisplitmetric.cpython-36.pyc
│ │ ├── hnode.cpython-36.pyc
│ │ ├── inactivehnode.cpython-36.pyc
│ │ ├── infogainsplitmetric.cpython-36.pyc
│ │ ├── leafnode.cpython-36.pyc
│ │ ├── nominalconditionalsufficientstats.cpython-36.pyc
│ │ ├── split.cpython-36.pyc
│ │ ├── splitcandidate.cpython-36.pyc
│ │ ├── splitmetric.cpython-36.pyc
│ │ ├── splitnode.cpython-36.pyc
│ │ ├── univariatenominalmultiwaysplit.cpython-36.pyc
│ │ ├── univariatenumericbinarysplit.cpython-36.pyc
│ │ └── weightmass.cpython-36.pyc
│ ├── activehnode.py
│ ├── conditionalsufficientstats.py
│ ├── gaussianconditionalsufficientstats.py
│ ├── ginisplitmetric.py
│ ├── hnode.py
│ ├── inactivehnode.py
│ ├── infogainsplitmetric.py
│ ├── leafnode.py
│ ├── nominalconditionalsufficientstats.py
│ ├── split.py
│ ├── splitcandidate.py
│ ├── splitmetric.py
│ ├── splitnode.py
│ ├── univariatenominalmultiwaysplit.py
│ ├── univariatenumericbinarysplit.py
│ └── weightmass.py
└── main.py
├── README.assets
├── .DS_Store
├── image-20190830143305580.png
└── image-20190830143415142.png
├── README.md
├── check_measure.py
├── chunk_based_methods.py
├── chunk_size_select.py
├── data
├── .DS_Store
├── drifting_gaussian_abrupt.npz
├── drifting_gaussian_gradual.npz
├── elec2_abrupt.npz
├── elec2_gradual.npz
├── hyperP_abrupt.npz
├── hyperP_gradual.npz
├── moving_gaussian_abrupt.npz
├── moving_gaussian_gradual.npz
├── noaa_abrupt.npz
├── noaa_gradual.npz
├── rotcb_abrupt.npz
├── rotcb_gradual.npz
├── rotsp_abrupt.npz
├── rotsp_gradual.npz
├── sea_abrupt.npz
└── sea_gradual.npz
├── dwmil.py
├── main.py
├── main_compare.py
├── online_methods.py
├── requirments.txt
├── subunderbagging.py
└── underbagging.py
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/.DS_Store
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | .DS_Store
3 | .idea/ACDWM.iml
4 | .idea/modules.xml
5 | .idea/vcs.xml
6 | .idea/workspace.xml
7 | HoeffdingTree/.DS_Store
8 | .DS_Store
9 |
--------------------------------------------------------------------------------
/HoeffdingTree/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 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
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 | {project} Copyright (C) {year} {fullname}
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 |
--------------------------------------------------------------------------------
/HoeffdingTree/README.md:
--------------------------------------------------------------------------------
1 | # HoeffdingTree
2 | A Python implementation of the Hoeffding Tree algorithm, also known as Very Fast Decision Tree (VFDT).
3 |
4 | The Hoeffding Tree is a decision tree for classification tasks in data streams.
5 |
6 | ```
7 | Pedro Domingos and Geoff Hulten. 2000.
8 | Mining high-speed data streams.
9 | In Proceedings of the sixth ACM SIGKDD international conference on
10 | Knowledge discovery and data mining (KDD '00).
11 | ACM, New York, NY, USA, 71-80.
12 | ```
13 |
14 | This implementation was initially based on [Weka](http://www.cs.waikato.ac.nz/ml/weka/)'s Hoeffding Tree and the original work by Geoff Hulten and Pedro Domingos, [VFML](http://www.cs.washington.edu/dm/vfml/). Although it is based on these I cannot guarantee that the algorithm will work exactly, or even produce the same output, as any of these implementations. Most of the class and variable names, for example, follow Weka's implementation in order to ease the use of the algorithm for some of my peers who are used to Weka when performing data mining tasks, but there may be significant changes in the code behind it.
15 |
16 | If you use this in your paper, please cite:
17 |
18 | ```
19 | Vitor da Silva and Ana Trindade Winck. 2017.
20 | Video popularity prediction in data streams based on context-independent features.
21 | In Proceedings of the Symposium on Applied Computing (SAC '17).
22 | ACM, New York, NY, USA, 95-100.
23 | DOI: https://doi.org/10.1145/3019612.3019638
24 | ```
25 |
--------------------------------------------------------------------------------
/HoeffdingTree/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/__init__.py
--------------------------------------------------------------------------------
/HoeffdingTree/core/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/core/__init__.py
--------------------------------------------------------------------------------
/HoeffdingTree/core/__pycache__/__init__.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/core/__pycache__/__init__.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/core/__pycache__/attribute.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/core/__pycache__/attribute.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/core/__pycache__/dataset.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/core/__pycache__/dataset.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/core/__pycache__/instance.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/core/__pycache__/instance.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/core/__pycache__/univariatenormalestimator.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/core/__pycache__/univariatenormalestimator.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/core/__pycache__/utils.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/core/__pycache__/utils.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/core/attribute.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | class Attribute(object):
4 | """A class for handling an attribute.
5 | Attribute can be either numeric or nominal and should never be changed after creation.
6 |
7 | Note:
8 | This class is based on the Weka implementation (weka.core.Attribute) to make porting existing
9 | Java algorithms an easier task.
10 |
11 | Args:
12 | name (str): The name of the attribute.
13 | values (list[str]): A list of possible attribute values. (default None)
14 | att_type (str): The type of the attribute. Should be 'Numeric' or 'Nominal'. (default None)
15 | index (int): The index of the attribute in the attribute set.
16 | If the attribute is not yet part of a set, its index is -1. (default -1)
17 |
18 | Raises:
19 | ValueError: If att_type is not 'Numeric' or 'Nominal'.
20 |
21 | """
22 |
23 | # TODO: Make constructor identify the attribute type by using the args received.
24 | def __init__(self, name, values=None, att_type=None, index=-1):
25 | # The name of the attribute
26 | self.__name = name
27 | # The possible values of the attribute, if Nominal
28 | self.__values = values
29 | # The type of the attribute
30 | if att_type not in ['Numeric', 'Nominal']:
31 | raise ValueError('Attribute type should be \'Numeric\' or \'Nominal\'. {0} is not a supported attribute type.'.format(att_type))
32 | self.__att_type = att_type
33 | # The index of the attribute
34 | self.__index = index
35 | # The bounds of the attribute, if Numeric
36 | self.__lower_bound = None
37 | self.__upper_bound = None
38 |
39 | def __str__(self):
40 | return 'Attribute \'{0}\' ({1})\n Index: {2}\n Values: {3}'.format(
41 | self.__name, self.__att_type, self.__index, self.__values)
42 |
43 | def index(self):
44 | """Return the index of the attribute.
45 |
46 | Returns:
47 | int: The index of the attribute.
48 | """
49 | return self.__index
50 |
51 | def index_of_value(self, value):
52 | """Return the index of the first occurence of an attribute value.
53 |
54 | Note:
55 | Since no values are stored in the Attribute class for Numeric attributes,
56 | a valid index is only returned for Nominal attributes.
57 |
58 | Args:
59 | value (str): The value for which the index should be returned.
60 |
61 | Returns:
62 | int: The index of a given attribute value if attribute is Nominal.
63 | int: -1 if attribute is Numeric.
64 | """
65 | if self.__att_type is 'Nominal':
66 | if value not in self.__values :
67 | self.add_value(value)
68 | return self.__values.index(value)
69 | else:
70 | return -1
71 |
72 | def is_numeric(self):
73 | """Test if attribute is Numeric.
74 |
75 | Returns:
76 | bool: True if the attribute is Numeric, False otherwise.
77 | """
78 | return self.__att_type is 'Numeric'
79 |
80 | def name(self):
81 | """Return the name of the attribute.
82 |
83 | Returns:
84 | str: The name of the attribute
85 | """
86 | return self.__name
87 |
88 | def num_values(self):
89 | """Return the number of possible values for the attribute.
90 |
91 | Returns:
92 | int: Number of possible values if attribute is Nominal.
93 | int: 0 if attribute is Numeric.
94 | """
95 | if self.__att_type == 'Nominal':
96 | return len(self.__values)
97 | else:
98 | return 0
99 |
100 | def type(self):
101 | """Return the type of the attribute.
102 |
103 | Returns:
104 | str: The type of the attribute.
105 | """
106 | return self.__att_type
107 |
108 | def value(self, index):
109 | """Return the value of the attribute at the given index.
110 |
111 | Args:
112 | index (int): The index of the attribute value to return.
113 |
114 | Returns:
115 | str: The value of attribute at the given position, if the attribute is Nominal.
116 | str: An empty string if the attribute is Numeric.
117 | """
118 | if self.__att_type is not 'Nominal':
119 | return ''
120 | else:
121 | return self.__values[index]
122 |
123 | def add_value(self, value):
124 | """Add a new value to the attribute.
125 | The value is always added to the end of the list of possible attribute values.
126 |
127 | Args:
128 | value (str): The new attribute value to be added.
129 | """
130 | self.__values.append(value)
131 |
132 | def set_index(self, index):
133 | """Set the index of the attribute.
134 |
135 | Args:
136 | index (int): The new index for the attribute.
137 | """
138 | self.__index = index
139 |
140 | def set_type(self, att_type):
141 | """Set the type of the attribute.
142 |
143 | Args:
144 | att_type (str): The type of the attribute.
145 |
146 | Raises:
147 | ValueError: If att_type is not 'Numeric' or 'Nominal'.
148 | """
149 | if att_type not in ['Numeric', 'Nominal']:
150 | raise ValueError('Attribute type should be \'Numeric\' or \'Nominal\'. {0} is not a supported attribute type.'.format(att_type))
151 | self.__att_type = att_type
152 |
153 | def set_numeric_range(self, lower_bound=-math.inf, upper_bound=math.inf):
154 | """Set the numeric range for the attribute.
155 |
156 | Args:
157 | lower_bound (float): The smallest possible value for the attribute. (default -math.inf)
158 | upper_bound (float): The largest possible value for the attribute. (default math.inf)
159 | """
160 | self.__lower_bound = lower_bound
161 | self.__upper_bound = upper_bound
162 |
163 | def lower_bound(self):
164 | """Return the lower numeric bound of the attribute.
165 |
166 | Returns:
167 | float: The lower numeric bound
168 | """
169 | return self.__lower_bound
170 |
171 | def upper_bound(self):
172 | """Return the upper numeric bound of the attribute.
173 |
174 | Returns:
175 | float: The upper numeric bound
176 | """
177 | return self.__upper_bound
178 |
--------------------------------------------------------------------------------
/HoeffdingTree/core/dataset.py:
--------------------------------------------------------------------------------
1 | from ..core.instance import Instance
2 |
3 | class Dataset(object):
4 | """A class for handling a dataset (set of instances).
5 |
6 | Note:
7 | This class is based on the Weka implementation (weka.core.Instances) to make porting existing
8 | Java algorithms an easier task.
9 |
10 | Args:
11 | attributes (list[Attributes]): The attributes of the dataset's instances.
12 | class_index (int): The index of the dataset's class attribute. (default -1)
13 | instances (list[Instance]): A list of instances of the dataset.
14 | If not specified an empty dataset is created. (default None)
15 | name (str): The name of the dataset. (default 'New dataset')
16 | """
17 |
18 | def __init__(self, attributes, class_index=-1, instances=None, name='New dataset'):
19 | # The attributes of the dataset's instances.
20 | self.__attributes = attributes
21 | # Set the indexes of the attributes in the dataset.
22 | for i in range(len(self.__attributes)):
23 | self.__attributes[i].set_index(i)
24 | # The index of the class attribute.
25 | self.__class_index = class_index
26 | # The set of instances of the dataset.
27 | self.__instances = instances
28 | # Associate all instances with the dataset.
29 | if self.__instances is not None:
30 | for inst in self.__instances:
31 | inst.set_dataset(self)
32 | else:
33 | # If no instances were given, set it to an empty list.
34 | self.__instances = []
35 | # The name of the dataset.
36 | self.__name = name
37 |
38 | def __str__(self):
39 | return 'Dataset \'{0}\'\n Attributes: {1}\n Class attribute: {2}\n Total instances: {3}'.format(
40 | self.__name, [att.name() for att in self.__attributes],
41 | self.attribute(self.__class_index).name(), len(self.__instances))
42 |
43 | def add(self, instance):
44 | """Add an instance to the dataset. Instances are always added to the end of the list.
45 |
46 | Args:
47 | instance (Instance): The instance to be added.
48 | """
49 | instance.set_dataset(self)
50 | self.__instances.append(instance)
51 |
52 | def attribute(self, index=None, name=None):
53 | """Return the attribute at the given index or with the given name.
54 |
55 | Args:
56 | index (int): The index of the attribute to be returned.
57 | name (str): The name of the attribute to be returned.
58 |
59 | Returns:
60 | Attribute: The requested attribute.
61 | None: If the specified attribute name does not exist.
62 | """
63 | if index is not None:
64 | return self.__attributes[index]
65 | else:
66 | for att in self.__attributes:
67 | if name == att.name():
68 | return att
69 | return None
70 |
71 | def class_attribute(self):
72 | """Return the class attribute.
73 |
74 | Returns:
75 | Attribute: The class attribute.
76 | """
77 | return self.attribute(self.__class_index)
78 |
79 | def class_index(self):
80 | """Return the index of the class attribute.
81 |
82 | Return:
83 | int: The index of the class attribute.
84 | -1: If the class attribute is not defined.
85 | """
86 | return self.__class_index
87 |
88 | def instance(self, index):
89 | """Return the instance at the given index.
90 |
91 | Args:
92 | index (int): The index of the instance to be returned.
93 |
94 | Returns:
95 | Instance: The instance at the given index.
96 | """
97 | return self.__instances[index]
98 |
99 | def num_attributes(self):
100 | """Return the number of attributes of the dataset's instances.
101 |
102 | Return:
103 | int: The number of attributes of the dataset's instances.
104 | """
105 | return len(self.__attributes)
106 |
107 | def num_classes(self):
108 | """Return the number of possible values for the class attribute.
109 |
110 | Return:
111 | int: The number of class values, if class attribute is Nominal.
112 | 1: If the class attribute is Numeric.
113 | """
114 | if self.class_attribute().type() is 'Numeric':
115 | return 1
116 | else:
117 | return self.class_attribute().num_values()
118 |
119 | def num_instances(self):
120 | """Return the number of instances in the dataset.
121 |
122 | Returns:
123 | int: The number of instances in the dataset.
124 | """
125 | return len(self.__instances)
126 |
127 | def name(self):
128 | """Return the name of the dataset.
129 |
130 | Return:
131 | str: The name of the dataset.
132 | """
133 | return self.__name
134 |
135 | def set_class(self, attribute):
136 | """Set the class attribute.
137 |
138 | Args:
139 | Attribute: The attribute to be set as class.
140 | """
141 | self.__class_index = attribute.index()
142 |
143 | def set_class_index(self, class_index):
144 | """Set the index of the class attribute.
145 |
146 | Args:
147 | int: The index of the attribute to be set as class.
148 | """
149 | self.__class_index = class_index
150 |
151 | def set_name(self, name):
152 | """Set the name of the dataset.
153 |
154 | Args:
155 | str: The new name of the dataset.
156 | """
157 | self.__name = name
158 |
159 | def get_attributes(self):
160 | """Return all attributes of the dataset's instances.
161 |
162 | Returns:
163 | list[Attribute]: A list containing all the attributes of the dataset's instances.
164 | """
165 | return self.__attributes
166 |
--------------------------------------------------------------------------------
/HoeffdingTree/core/instance.py:
--------------------------------------------------------------------------------
1 | from ..core.attribute import Attribute
2 | import math
3 |
4 | class Instance(object):
5 | """A class for handling an instance.
6 | All the values of the instance's attributes are stored as floating-point numbers.
7 | If the attribute is Nominal, the value corresponds to its index in the attribute's definition.
8 |
9 | Note:
10 | This class is based on the Weka implementation (weka.core.Instance) to make porting existing
11 | Java algorithms an easier task.
12 | Weka developers chose this approach of storing only Numeric values inside the instance,
13 | while Nominal values are stored in an Attribute object and only the index for its value is
14 | stored in an instance. Although confusing at first, it makes instance handling less messy
15 | since it only needs to take care of numbers (instead of numbers and strings).
16 |
17 | Args:
18 | att_values (list[float]): The instances's attribute values. (default None)
19 |
20 | Raises:
21 | TypeError: If att_values is None.
22 | """
23 |
24 | def __init__(self, att_values):
25 | if att_values is None:
26 | raise TypeError('Instance should be created with a list of attribute values.')
27 | # The list of attribute values for the instance.
28 | self.__att_values = att_values
29 | # The dataset with which this instance is associated (has access to its properties and/or attributes).
30 | self.__dataset = None
31 | self.__weight = 1
32 |
33 | def __str__(self):
34 | return 'Instance\n From dataset: {0}\n Attribute values: {1}\n Class: {2}'.format(
35 | self.__dataset.name() if self.__dataset is not None else 'This instance is not associated with a dataset.',
36 | self.__att_values, 'A dataset is required to set an attribute as class.' if self.__dataset is None else self.__att_values[self.__dataset.class_index()])
37 |
38 | def attribute(self, index):
39 | """Return the attribute with the given index.
40 |
41 | Args:
42 | index (int): The index of the attribute to be returned.
43 |
44 | Returns:
45 | Attribute: The attribute at the given index.
46 | """
47 | #TODO: Should check if the instance is associated to a dataset.
48 | return self.__dataset.attribute(index)
49 |
50 | def class_attribute(self):
51 | """Return the instance's class attribute. It is always its dataset's class attribute.
52 |
53 | Returns:
54 | Attribute: The class attribute of the instance.
55 | """
56 | return self.__dataset.class_attribute()
57 |
58 | def class_index(self):
59 | """Return the instance's index of the class attribute.
60 |
61 | Returns:
62 | int: The class attribute's index of the instance.
63 | """
64 | #TODO: Should check if the instance is associated to a dataset.
65 | return self.__dataset.class_index()
66 |
67 | def class_is_missing(self):
68 | """Test if the instance is missing a class.
69 |
70 | Returns:
71 | bool: True if the instance's class is missing, False otherwise.
72 |
73 | Raises:
74 | ValueError: If class is not set for the instance.
75 | """
76 | if self.class_index() < 0:
77 | raise ValueError("Class is not set.")
78 | return self.is_missing(self.class_index())
79 |
80 | def class_value(self):
81 | """Return the class value of the instance.
82 | If class attribute is Nominal, return the index of its value in the attribute's definition.
83 |
84 | Returns:
85 | int: The class attribute's index of the instance.
86 |
87 | Raises:
88 | ValueError: If the class attribute is not set in the dataset with which the instance is associated.
89 | """
90 | if self.class_index() < 0:
91 | raise ValueError('Class attribute is not set.')
92 | return self.value(index=self.class_index())
93 |
94 | def dataset(self):
95 | """Return the dataset this instance is associated with.
96 |
97 | Returns:
98 | Dataset: The dataset this instance is associated with.
99 | """
100 | return self.__dataset
101 |
102 | def is_missing(self, att_index):
103 | """Test if a value is missing.
104 |
105 | Args:
106 | att_index (int): The index of the attribute to be tested.
107 |
108 | Returns:
109 | bool: True if value is missing, False otherwise.
110 | """
111 | if math.isnan(self.__att_values[att_index]):
112 | return True
113 | else:
114 | return False
115 |
116 | def num_attributes(self):
117 | """Return the number of attributes of the instance.
118 |
119 | Returns:
120 | int: The number of attributes of the instance.
121 | """
122 | return len(self.__att_values)
123 |
124 | def num_classes(self):
125 | """Return the number of possible class values if class attribute is Nominal.
126 | If class attribute is Numeric it always returns 1.
127 |
128 | Returns:
129 | int: The number of possible class values if class attribute is Nominal.
130 | int: 1 if class attribute is Numeric.
131 | """
132 | return self.__dataset.num_classes()
133 |
134 | def num_values(self):
135 | """Return the number of the instance's values for its attributes.
136 | Always the same as self.num_attributes() since each instance has only one value set for each attribute.
137 |
138 | Returns:
139 | int: The number of the instance's values for its attributes.
140 | """
141 | return len(self.__att_values)
142 |
143 | def set_class_value(self, value):
144 | """Set the class value of the instance to the given value.
145 |
146 | Args:
147 | value (float): The value to be set as the instance's class value.
148 | """
149 | self.set_value(self.class_index(), value)
150 |
151 | def set_dataset(self, dataset):
152 | """Set the dataset to which the instance is associated.
153 | The dataset will not know about this instance so any changes in the dataset affecting its instances will not account for this instance.
154 |
155 | Args:
156 | Dataset: The dataset to which the instance is associated.
157 | """
158 | self.__dataset = dataset
159 |
160 | def set_value(self, att_index, value):
161 | """Set the instance's attribute at att_index to the given value.
162 |
163 | Note:
164 | Arg value can be either a float (for Numeric attributes) or a str (for Nominal attributes).
165 |
166 | Args:
167 | att_index (int): The index of the attribute to be set.
168 | value (float): A Numeric value to be set to the attribute at the given index.
169 | value (str): A Nominal value to be set to the attribute at the given index.
170 | """
171 | if isinstance(value, str):
172 | # Attribute is Nominal
173 | value_index = self.attribute(att_index).index_of_value(value)
174 | else:
175 | #Attribute is Numeric
176 | value_index = att_index
177 | self.__att_values[value_index] = value
178 |
179 | def set_weight(self, weight):
180 | """Set the weight of the instance.
181 |
182 | Args:
183 | weight (float): The weight.
184 | """
185 | self.__weight = weight
186 |
187 | def string_value(self, att_index=None, attribute=None):
188 | """Return the value of the attribute as a string.
189 |
190 | Args:
191 | att_index (int): The index of the attribute. (default None)
192 | attribute (Attribute): The attribute for which the value is to be returned. (default None)
193 |
194 | Returns:
195 | str: The value of the attribute as a string.
196 | """
197 | if attribute is None:
198 | attribute = self.__dataset.attribute(att_index)
199 | if att_index is None:
200 | att_index = attribute.index()
201 | if self.is_missing(att_index):
202 | return '?'
203 | return attribute.value(self.value(index=att_index))
204 |
205 | def value(self, index=None, attribute=None):
206 | """Return the value of an intance's attribute.
207 |
208 | Args:
209 | index (int): The index of the attribute which its value is to be returned.
210 | attribute (Attribute): The attribute which its value is to be returned.
211 |
212 | Returns:
213 | float: The instance's attribute value.
214 | """
215 | if index is not None:
216 | return self.__att_values[index]
217 | else:
218 | return self.__att_values[attribute.index()]
219 |
220 | def weight(self):
221 | """Return the weight of the instance.
222 |
223 | Returns:
224 | float: The weight of the instance.
225 | """
226 | return self.__weight
227 |
228 | def get_attributes(self):
229 | """Return all attributes of the instance.
230 |
231 | Returns:
232 | list[Attribute]: A list containing all the attributes of the instance.
233 | """
234 | attributes = [None for i in range(self.num_attributes())]
235 | for i in range(self.num_attributes()):
236 | attributes[i] = self.attribute(i)
237 | return attributes
238 |
--------------------------------------------------------------------------------
/HoeffdingTree/core/univariatenormalestimator.py:
--------------------------------------------------------------------------------
1 | from sys import float_info
2 | import math
3 | from ..core import utils
4 |
5 | class UnivariateNormalEstimator(object):
6 | """docstring for UnivariateNormalEstimator"""
7 | def __init__(self):
8 | self._weighted_sum = 0
9 | self._weighted_sum_squared = 0
10 | self._sum_of_weights = 0
11 | self._mean = 0
12 | self._variance = float_info.max
13 | self._min_var = 1e-12
14 | self.CONST = math.log(2 * math.pi)
15 |
16 | def __str__(self):
17 | self.update_mean_and_variance()
18 | return 'Mean: {0}, Variance: {1}'.format(self._mean, self._variance)
19 |
20 | def add_value(self, value, weight):
21 | self._weighted_sum += value * weight
22 | self._weighted_sum_squared += value * value * weight
23 | self._sum_of_weights += weight
24 |
25 | def update_mean_and_variance(self):
26 | self._mean = 0
27 | if self._sum_of_weights > 0:
28 | self._mean = self._weighted_sum / self._sum_of_weights
29 |
30 | self._variance = float_info.max
31 | if self._sum_of_weights > 0:
32 | self._variance = self._weighted_sum_squared / self._sum_of_weights - self._mean * self._mean
33 |
34 | if self._variance <= self._min_var:
35 | self._variance = self._min_var
36 |
37 | def predict_intervals(self, conf):
38 | self.update_mean_and_variance()
39 | val = utils.normal_inverse(1.0 - (1.0 - conf) / 2.0)
40 | arr = [[self._mean + val * math.sqrt(self._variance)],
41 | [self._mean - val * math.sqrt(self._variance)]]
42 | return arr
43 |
44 | def predict_quantile(self, percentage):
45 | self.update_mean_and_variance()
46 | return self._mean + utils.normal_inverse(percentage) * math.sqrt(self._variance)
47 |
48 | def log_density(self, value):
49 | self.update_mean_and_variance()
50 | val = -0.5 * (self.CONST + math.log(self._variance) + (value - self._mean) *
51 | (value - self._mean) / self._variance)
52 | return val
53 |
--------------------------------------------------------------------------------
/HoeffdingTree/core/utils.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | def normalize(floats, floats_sum=None):
4 | if floats_sum is None:
5 | floats_sum = 0.0
6 | for i in range(len(floats)):
7 | floats_sum += floats[i]
8 | if math.isnan(floats_sum):
9 | raise ValueError("Can't normalize list. Sum is NaN.")
10 | if floats_sum is 0:
11 | raise ValueError("Can't normalize list. Sum is zero.")
12 | for i in range(len(floats)):
13 | floats[i] /= floats_sum
14 |
15 | def normal_probability(a):
16 | x = a * 7.07106781186547524401e-1
17 | y = 0.5
18 | z = abs(x)
19 |
20 | if z < 7.07106781186547524401e-1:
21 | y += 0.5 * error_function(x)
22 | else:
23 | y *= error_function_complemented(z)
24 | if x > 0:
25 | y = 1.0 - y
26 | return y
27 |
28 | def error_function(x):
29 | T = [9.60497373987051638749E0,
30 | 9.00260197203842689217E1,
31 | 2.23200534594684319226E3,
32 | 7.00332514112805075473E3,
33 | 5.55923013010394962768E4]
34 |
35 | U = [3.35617141647503099647E1,
36 | 5.21357949780152679795E2,
37 | 4.59432382970980127987E3,
38 | 2.26290000613890934246E4,
39 | 4.92673942608635921086E4]
40 |
41 | if abs(x) > 1.0:
42 | return 1.0 - error_function_complemented(x)
43 |
44 | z = x * x
45 | y = x * polevl(z, T, 4) / p1evl(z, U, 5)
46 | return y
47 |
48 | def error_function_complemented(a):
49 | P = [2.46196981473530512524E-10,
50 | 5.64189564831068821977E-1,
51 | 7.46321056442269912687E0,
52 | 4.86371970985681366614E1,
53 | 1.96520832956077098242E2,
54 | 5.26445194995477358631E2,
55 | 9.34528527171957607540E2,
56 | 1.02755188689515710272E3,
57 | 5.57535335369399327526E2]
58 |
59 | Q = [1.32281951154744992508E1,
60 | 8.67072140885989742329E1,
61 | 3.54937778887819891062E2,
62 | 9.75708501743205489753E2,
63 | 1.82390916687909736289E3,
64 | 2.24633760818710981792E3,
65 | 1.65666309194161350182E3,
66 | 5.57535340817727675546E2]
67 |
68 | R = [5.64189583547755073984E-1,
69 | 1.27536670759978104416E0,
70 | 5.01905042251180477414E0,
71 | 6.16021097993053585195E0,
72 | 7.40974269950448939160E0,
73 | 2.97886665372100240670E0]
74 |
75 | S = [2.26052863220117276590E0,
76 | 9.39603524938001434673E0,
77 | 1.20489539808096656605E1,
78 | 1.70814450747565897222E1,
79 | 9.60896809063285878198E0,
80 | 3.36907645100081516050E0]
81 |
82 | if a < 0:
83 | x = -a
84 | else:
85 | x = a
86 |
87 | if x < 1:
88 | return 1.0 - error_function(a)
89 |
90 | z = -a * a
91 |
92 | if z < -7.09782712893383996732e2:
93 | if a < 0:
94 | return 2.0
95 | else:
96 | return 0.0
97 |
98 | z = math.exp(z)
99 |
100 | if x < 8:
101 | p = polevl(x, P, 8)
102 | q = p1evl(x, Q, 8)
103 | else:
104 | p = polevl(x, R, 5)
105 | q = p1evl(x, S, 6)
106 |
107 | y = (z * p) / q
108 |
109 | if a < 0:
110 | y = 2.0 - y
111 |
112 | if y == 0:
113 | if a < 0:
114 | return 2.0
115 | else:
116 | return 0.0
117 | return y
118 |
119 | def polevl(x, coef, N):
120 | ans = coef[0]
121 | for i in range(1, N + 1):
122 | ans = ans * x + coef[i]
123 | return ans
124 |
125 | def p1evl(x, coef, N):
126 | ans = x + coef[0]
127 | for i in range(1, N):
128 | ans = ans * x + coef[i]
129 | return ans
130 |
131 | def is_missing_value(val):
132 | return math.isnan(val)
133 |
134 | def eq(a, b):
135 | # Small deviation allowed in comparisons
136 | allowed_deviation = 1e-6
137 | return a is b or ((a - b < allowed_deviation) and (b - a < allowed_deviation))
138 |
139 | def entropy(array):
140 | return_value = 0
141 | sum_value = 0
142 |
143 | for i in range(len(array)):
144 | return_value -= ln_func(array[i])
145 | sum_value += array[i]
146 | if eq(sum_value, 0):
147 | return 0
148 | else:
149 | return (return_value + ln_func(sum_value)) / (sum_value * math.log(2))
150 |
151 | def ln_func(num):
152 | if num <= 0:
153 | return 0
154 | else:
155 | return num * math.log(num)
156 |
157 | def normal_inverse(y0):
158 | x = y = z = y2 = x0 = x1 = code = 0
159 |
160 | P0 = [-5.99633501014107895267E1,
161 | 9.80010754185999661536E1,
162 | -5.66762857469070293439E1,
163 | 1.39312609387279679503E1,
164 | -1.23916583867381258016E0]
165 |
166 | Q0 = [1.95448858338141759834E0,
167 | 4.67627912898881538453E0,
168 | 8.63602421390890590575E1,
169 | -2.25462687854119370527E2,
170 | 2.00260212380060660359E2,
171 | -8.20372256168333339912E1,
172 | 1.59056225126211695515E1,
173 | -1.18331621121330003142E0]
174 |
175 | P1 = [4.05544892305962419923E0,
176 | 3.15251094599893866154E1,
177 | 5.71628192246421288162E1,
178 | 4.40805073893200834700E1,
179 | 1.46849561928858024014E1,
180 | 2.18663306850790267539E0,
181 | -1.40256079171354495875E-1,
182 | -3.50424626827848203418E-2,
183 | -8.57456785154685413611E-4]
184 |
185 | Q1 = [1.57799883256466749731E1,
186 | 4.53907635128879210584E1,
187 | 4.13172038254672030440E1,
188 | 1.50425385692907503408E1,
189 | 2.50464946208309415979E0,
190 | -1.42182922854787788574E-1,
191 | -3.80806407691578277194E-2,
192 | -9.33259480895457427372E-4]
193 |
194 | P2 = [3.23774891776946035970E0,
195 | 6.91522889068984211695E0,
196 | 3.93881025292474443415E0,
197 | 1.33303460815807542389E0,
198 | 2.01485389549179081538E-1,
199 | 1.23716634817820021358E-2,
200 | 3.01581553508235416007E-4,
201 | 2.65806974686737550832E-6,
202 | 6.23974539184983293730E-9]
203 |
204 | Q2 = [6.02427039364742014255E0,
205 | 3.67983563856160859403E0,
206 | 1.37702099489081330271E0,
207 | 2.16236993594496635890E-1,
208 | 1.34204006088543189037E-2,
209 | 3.28014464682127739104E-4,
210 | 2.89247864745380683936E-6,
211 | 6.79019408009981274425E-9]
212 |
213 | if y0 <= 0.0 or y0 >= 1.0:
214 | raise ValueError(
215 | 'Area under Gaussian Probabily Density Function should be in the interval (0, 1).')
216 | s2pi = math.sqrt(2.0 * math.pi)
217 | code = 1
218 | y = y0
219 | if y > (1.0 - 0.13533528323661269189):
220 | y = 1.0 - y
221 | code = 0
222 |
223 | if y > 0.13533528323661269189:
224 | y = y - 0.5
225 | y2 = y * y
226 | x = y + y * (y2 * polevl(y2, P0, 4) / p1evl(y2, Q0, 8))
227 | x = x * s2pi
228 | return x
229 |
230 | x = math.sqrt(-2.0 * math.log(y))
231 | x0 = x - math.log(x) / x
232 |
233 | z = 1.0 / x
234 | if x < 8.0:
235 | x1 = z * polevl(z, P1, 8) / p1evl(z, Q1, 8)
236 | else:
237 | x1 = z * polevl(z, P2, 8) / p1evl(z, Q2, 8)
238 | x = x0 - x1
239 | if code is not 0:
240 | x = -x
241 | return x
--------------------------------------------------------------------------------
/HoeffdingTree/hoeffdingtree.py:
--------------------------------------------------------------------------------
1 | import math
2 | from operator import attrgetter
3 |
4 | from .core import utils
5 | from .core.attribute import Attribute
6 | from .core.instance import Instance
7 | from .core.dataset import Dataset
8 |
9 | from .ht.activehnode import ActiveHNode
10 | from .ht.ginisplitmetric import GiniSplitMetric
11 | from .ht.hnode import HNode
12 | from .ht.inactivehnode import InactiveHNode
13 | from .ht.infogainsplitmetric import InfoGainSplitMetric
14 | from .ht.leafnode import LeafNode
15 | from .ht.splitcandidate import SplitCandidate
16 | from .ht.splitmetric import SplitMetric
17 | from .ht.splitnode import SplitNode
18 |
19 | class HoeffdingTree(object):
20 | """Main class for a Hoeffding Tree, also known as Very Fast Decision Tree (VFDT)."""
21 | def __init__(self):
22 | self._header = None
23 | self._root = None
24 | self._grace_period = 200
25 | self._split_confidence = 0.0000001
26 | self._hoeffding_tie_threshold = 0.05
27 | self._min_frac_weight_for_two_branches_gain = 0.01
28 |
29 | # Split metric stuff goes here
30 | self.GINI_SPLIT = 0
31 | self.INFO_GAIN_SPLIT = 1
32 |
33 | self._selected_split_metric = self.INFO_GAIN_SPLIT
34 | self._split_metric = InfoGainSplitMetric(self._min_frac_weight_for_two_branches_gain)
35 | #self._selected_split_metric = self.GINI_SPLIT
36 | #self._split_metric = GiniSplitMetric()
37 |
38 | # Leaf prediction strategy stuff goes here
39 |
40 | # Only used when the leaf prediction strategy is baded on Naive Bayes, not useful right now
41 | #self._nb_threshold = 0
42 |
43 | self._active_leaf_count = 0
44 | self._inactive_leaf_count = 0
45 | self._decision_node_count = 0
46 |
47 | # Print out leaf models in the case of naive Bayes or naive Bayes adaptive leaves
48 | self._print_leaf_models = False
49 |
50 | def __str__(self):
51 | if self._root is None:
52 | return 'No model built yet!'
53 | return self._root.__str__(self._print_leaf_models)
54 |
55 | def reset(self):
56 | """Reset the classifier and set all node/leaf counters to zero."""
57 | self._root = None
58 | self._active_leaf_count = 0
59 | self._inactive_leaf_count = 0
60 | self._decision_node_count = 0
61 |
62 | def set_minimum_fraction_of_weight_info_gain(self, m):
63 | self._min_frac_weight_for_two_branches_gain = m
64 |
65 | def get_minimum_fraction_of_weight_info_gain(self):
66 | return self._min_frac_weight_for_two_branches_gain
67 |
68 | def set_grace_period(self, grace):
69 | self._grace_period = grace
70 |
71 | def get_grace_period(self):
72 | return self._grace_period
73 |
74 | def set_hoeffding_tie_threshold(self, ht):
75 | self._hoeffding_tie_threshold = ht
76 |
77 | def get_hoeffding_tie_threshold(self):
78 | return self._hoeffding_tie_threshold
79 |
80 | def set_split_confidence(self, sc):
81 | self._split_confidence = sc
82 |
83 | def get_split_confidence(self):
84 | return self._split_confidence
85 |
86 | def compute_hoeffding_bound(self, max_value, confidence, weight):
87 | """Calculate the Hoeffding bound.
88 |
89 | Args:
90 | max_value (float):
91 | confidence (float):
92 | weight (float):
93 |
94 | Returns:
95 | (float): The Hoeffding bound.
96 | """
97 | return math.sqrt(((max_value * max_value) * math.log(1.0 / confidence)) / (2.0 * weight))
98 |
99 | def build_classifier(self, dataset):
100 | """Build the classifier.
101 |
102 | Args:
103 | dataset (Dataset): The data to start training the classifier.
104 | """
105 | self.reset()
106 | self._header = dataset
107 | if self._selected_split_metric is self.GINI_SPLIT:
108 | self._split_metric = GiniSplitMetric()
109 | else:
110 | self._split_metric = InfoGainSplitMetric(self._min_frac_weight_for_two_branches_gain)
111 |
112 | for i in range(dataset.num_instances()):
113 | self.update_classifier(dataset.instance(i))
114 |
115 | def update_classifier(self, instance):
116 | """Update the classifier with the given instance.
117 |
118 | Args:
119 | instance (Instance): The new instance to be used to train the classifier.
120 | """
121 | if instance.class_is_missing():
122 | return
123 | if self._root is None:
124 | self._root = self.new_learning_node()
125 |
126 | l = self._root.leaf_for_instance(instance, None, None)
127 | actual_node = l.the_node
128 | if actual_node is None:
129 | actual_node = ActiveHNode()
130 | l.parent_node.set_child(l.parent_branch, actual_node)
131 |
132 | # ActiveHNode should be changed to a LearningNode interface if Naive Bayes nodes are used
133 | if isinstance(actual_node, InactiveHNode):
134 | actual_node.update_node(instance)
135 | if isinstance(actual_node, ActiveHNode):
136 | actual_node.update_node(instance)
137 | total_weight = actual_node.total_weight()
138 | if total_weight - actual_node.weight_seen_at_last_split_eval > self._grace_period:
139 | self.try_split(actual_node, l.parent_node, l.parent_branch)
140 | actual_node.weight_seen_at_last_split_eval = total_weight
141 |
142 | def distribution_for_instance(self, instance):
143 | """Return the class probabilities for an instance.
144 |
145 | Args:
146 | instance (Instance): The instance to calculate the class probabilites for.
147 |
148 | Returns:
149 | list[float]: The class probabilities.
150 | """
151 | class_attribute = instance.class_attribute()
152 | pred = []
153 |
154 | if self._root is not None:
155 | l = self._root.leaf_for_instance(instance, None, None)
156 | actual_node = l.the_node
157 | if actual_node is None:
158 | actual_node = l.parent_node
159 | pred = actual_node.get_distribution(instance, class_attribute)
160 | else:
161 | # All class values equally likely
162 | pred = [1 for i in range(class_attribute.num_values())]
163 | utils.normalize(pred)
164 |
165 | return pred
166 |
167 |
168 | def deactivate_node(self, to_deactivate, parent, parent_branch):
169 | """Prevent supplied node of growing.
170 |
171 | Args:
172 | to_deactivate (ActiveHNode): The node to be deactivated.
173 | parent (SplitNode): The parent of the node.
174 | parent_branch (str): The branch leading from the parent to the node.
175 | """
176 | leaf = InactiveHNode(to_deactivate.class_distribution)
177 |
178 | if parent is None:
179 | self._root = leaf
180 | else:
181 | parent.set_child(parent_branch, leaf)
182 |
183 | self._active_leaf_count -= 1
184 | self._inactive_leaf_count += 1
185 |
186 | def activate_node(self, to_activate, parent, parent_branch):
187 | """Allow supplied node to grow.
188 |
189 | Args:
190 | to_activate (InactiveHNode): The node to be activated.
191 | parent (SplitNode): The parent of the node.
192 | parent_branch (str): The branch leading from the parent to the node.
193 | """
194 | leaf = ActiveHNode()
195 | leaf.class_distribution = to_activate.class_distribution
196 |
197 | if parent is None:
198 | self._root = leaf
199 | else:
200 | parent.set_child(parent_branch, leaf)
201 |
202 | self._active_leaf_count += 1
203 | self._inactive_leaf_count -= 1
204 |
205 | def try_split(self, node, parent, parent_branch):
206 | """Try a split from the supplied node.
207 |
208 | Args:
209 | node (ActiveHNode): The node to split.
210 | parent (SplitNode): The parent of the node.
211 | parent_branch (str): The branch leading from the parent to the node.
212 | """
213 | # Non-pure?
214 | if node.num_entries_in_class_distribution() > 1:
215 | best_splits = node.get_possible_splits(self._split_metric)
216 | best_splits.sort(key=attrgetter('split_merit'))
217 |
218 | do_split = False
219 | if len(best_splits) < 2:
220 | do_split = len(best_splits) > 0
221 | else:
222 | # Compute Hoeffding bound
223 | metric_max = self._split_metric.get_metric_range(node.class_distribution)
224 | hoeffding_bound = self.compute_hoeffding_bound(
225 | metric_max, self._split_confidence, node.total_weight())
226 | best = best_splits[len(best_splits) - 1]
227 | second_best = best_splits[len(best_splits) - 2]
228 | if best.split_merit - second_best.split_merit > hoeffding_bound or hoeffding_bound < self._hoeffding_tie_threshold:
229 | do_split = True
230 |
231 | if do_split:
232 | best = best_splits[len(best_splits) - 1]
233 | if best.split_test is None:
234 | # preprune
235 | self.deactivate_node(node, parent, parent_branch)
236 | else:
237 | new_split = SplitNode(node.class_distribution, best.split_test)
238 |
239 | for i in range(best.num_splits()):
240 | new_child = self.new_learning_node()
241 | new_child.class_distribution = best.post_split_class_distributions[i]
242 | new_child.weight_seen_at_last_split_eval = new_child.total_weight()
243 | branch_name = ''
244 | if self._header.attribute(name=best.split_test.split_attributes()[0]).is_numeric():
245 | if i is 0:
246 | branch_name = 'left'
247 | else:
248 | branch_name = 'right'
249 | else:
250 | split_attribute = self._header.attribute(name=best.split_test.split_attributes()[0])
251 | branch_name = split_attribute.value(i)
252 | new_split.set_child(branch_name, new_child)
253 |
254 | self._active_leaf_count -= 1
255 | self._decision_node_count += 1
256 | self._active_leaf_count += best.num_splits()
257 |
258 | if parent is None:
259 | self._root = new_split
260 | else:
261 | parent.set_child(parent_branch, new_split)
262 |
263 | def new_learning_node(self):
264 | """Create a new learning node. Will always be an ActiveHNode while Naive Bayes
265 | nodes are not implemented.
266 |
267 | Returns:
268 | ActiveHNode: The new learning node.
269 | """
270 | # Leaf strategy should be handled here if/when the Naive Bayes approach is implemented
271 | return ActiveHNode()
272 |
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__init__.py
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/__init__.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/__init__.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/activehnode.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/activehnode.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/conditionalsufficientstats.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/conditionalsufficientstats.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/gaussianconditionalsufficientstats.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/gaussianconditionalsufficientstats.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/ginisplitmetric.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/ginisplitmetric.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/hnode.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/hnode.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/inactivehnode.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/inactivehnode.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/infogainsplitmetric.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/infogainsplitmetric.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/leafnode.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/leafnode.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/nominalconditionalsufficientstats.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/nominalconditionalsufficientstats.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/split.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/split.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/splitcandidate.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/splitcandidate.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/splitmetric.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/splitmetric.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/splitnode.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/splitnode.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/univariatenominalmultiwaysplit.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/univariatenominalmultiwaysplit.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/univariatenumericbinarysplit.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/univariatenumericbinarysplit.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/__pycache__/weightmass.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/HoeffdingTree/ht/__pycache__/weightmass.cpython-36.pyc
--------------------------------------------------------------------------------
/HoeffdingTree/ht/activehnode.py:
--------------------------------------------------------------------------------
1 | from ..ht.leafnode import LeafNode
2 | from ..ht.hnode import HNode
3 | from ..ht.gaussianconditionalsufficientstats import GaussianConditionalSufficientStats
4 | from ..ht.nominalconditionalsufficientstats import NominalConditionalSufficientStats
5 | from ..ht.splitcandidate import SplitCandidate
6 |
7 | class ActiveHNode(LeafNode):
8 | """A Hoeffding Tree node that supports growth."""
9 | def __init__(self):
10 | super().__init__()
11 | # The total weight of the instances seen at the last split evaluation.
12 | self.weight_seen_at_last_split_eval = 0
13 | # Statistics for the attributes.
14 | # Dict of tuples (attribute name, ConditionalSufficientStats).
15 | self._node_stats = {}
16 |
17 | def update_node(self, instance):
18 | """Update the node with the supplied instance.
19 |
20 | Args:
21 | instance (Instance): The instance to be used for updating the node.
22 | """
23 | self.update_distribution(instance)
24 | for i in range(instance.num_attributes()):
25 | a = instance.attribute(i)
26 | if i is not instance.class_index():
27 | stats = self._node_stats.get(a.name(), None)
28 | if stats is None:
29 | if a.is_numeric():
30 | stats = GaussianConditionalSufficientStats()
31 | else:
32 | stats = NominalConditionalSufficientStats()
33 | self._node_stats[a.name()] = stats
34 |
35 | stats.update(instance.value(attribute=a),
36 | instance.class_attribute().value(index=instance.class_value()),
37 | instance.weight())
38 |
39 | def get_possible_splits(self, split_metric):
40 | """Return a list of the possible split candidates.
41 |
42 | Args:
43 | split_metric (SplitMetric): The splitting metric to be used.
44 |
45 | Returns:
46 | list[SplitCandidate]: A list of the possible split candidates.
47 | """
48 | splits = []
49 | null_dist = []
50 | null_dist.append(self.class_distribution)
51 | null_split = SplitCandidate(None, null_dist,
52 | split_metric.evaluate_split(self.class_distribution, null_dist))
53 | splits.append(null_split)
54 |
55 | for attribute_name, stat in self._node_stats.items():
56 | split_candidate = stat.best_split(split_metric, self.class_distribution, attribute_name)
57 | if split_candidate is not None:
58 | splits.append(split_candidate)
59 |
60 | return splits
61 |
--------------------------------------------------------------------------------
/HoeffdingTree/ht/conditionalsufficientstats.py:
--------------------------------------------------------------------------------
1 | from abc import ABCMeta, abstractmethod
2 |
3 | class ConditionalSufficientStats(metaclass=ABCMeta):
4 | """A class for keeping record of the sufficient statistics for an attribute."""
5 | def __init__(self):
6 | # Lookup by class value
7 | # Dict of tuples (class value, attribute estimator)
8 | self._class_lookup = {}
9 |
10 | @abstractmethod
11 | def update(self, att_val, class_val, weight):
12 | """Update the statistics with the supplied attribute and class values.
13 |
14 | Args:
15 | att_val (float): The value of the attribute.
16 | class_val (str): The value of the class.
17 | weight (float): The weight of this observation.
18 | """
19 | pass
20 |
21 | @abstractmethod
22 | def probability_of_att_val_conditioned_on_class(self, att_val, class_val):
23 | """Return the probability of an attribute value conditioned on a class value.
24 |
25 | Args:
26 | att_val (float): The attribute value to compute the conditional probability for.
27 | class_val (str): The class value.
28 |
29 | Returns:
30 | float: The probability of the attribute value being conditioned on the given class value.
31 | """
32 | pass
33 |
34 | @abstractmethod
35 | def best_split(self, split_metric, pre_split_dist, att_name):
36 | """Return the best split.
37 |
38 | Args:
39 | split_metric (SplitMetric): The split metric to use.
40 | pre_split_dist (dict): The distribution of class values before the split.
41 | att_name (str): The name of the attribute being considered for splitting.
42 |
43 | Returns:
44 | SplitCandidate: The best split for the attribute.
45 | """
46 | pass
--------------------------------------------------------------------------------
/HoeffdingTree/ht/gaussianconditionalsufficientstats.py:
--------------------------------------------------------------------------------
1 | from ..ht.conditionalsufficientstats import ConditionalSufficientStats
2 | from ..ht.weightmass import WeightMass
3 | from ..ht.univariatenumericbinarysplit import UnivariateNumericBinarySplit
4 | from ..ht.splitcandidate import SplitCandidate
5 |
6 | from ..core.univariatenormalestimator import UnivariateNormalEstimator
7 | from ..core import utils
8 |
9 | from sortedcontainers import SortedList
10 | import math
11 |
12 | class GaussianEstimator(UnivariateNormalEstimator):
13 | """A Gaussian estimator for the GaussianConditionalSufficientStats class."""
14 | def __init__(self):
15 | super().__init__()
16 |
17 | def get_sum_of_weights(self):
18 | return self._sum_of_weights
19 |
20 | def probability_density(self, value):
21 | self.update_mean_and_variance()
22 | if self._sum_of_weights > 0:
23 | std_dev = math.sqrt(self._variance)
24 | if std_dev > 0:
25 | diff = value - self._mean
26 | return (1.0 / (self.CONST * std_dev)) * math.exp(-(diff * diff / (2.0 * self._variance)))
27 | if value == self._mean:
28 | return 1.0
29 | else:
30 | return 0.0
31 | return 0.0
32 |
33 | def weight_less_than_equal_and_greater_than(self, value):
34 | std_dev = math.sqrt(self._variance)
35 | equal_w = self.probability_density(value) * self._sum_of_weights
36 | less_w = None
37 | if std_dev > 0:
38 | less_w = utils.normal_probability(
39 | (value - self._mean) / std_dev) * self._sum_of_weights - equal_w
40 | elif value < self._mean:
41 | less_w = self._sum_of_weights - equal_w
42 | else:
43 | less_w = 0.0
44 | greater_w = self._sum_of_weights - equal_w - less_w
45 | return [less_w, equal_w, greater_w]
46 |
47 | class GaussianConditionalSufficientStats(ConditionalSufficientStats):
48 | """A class for keeping record of the sufficient statistics for a numeric attribute."""
49 | def __init__(self):
50 | super().__init__()
51 | self._min_val_observed_per_class = {}
52 | self._max_val_observed_per_class = {}
53 | self._num_bins = 10
54 |
55 | def set_num_bins(self, b):
56 | self._num_bins = b
57 |
58 | def get_num_bins(self):
59 | return self._num_bins
60 |
61 | def update(self, att_val, class_val, weight):
62 | """Update the statistics with the supplied attribute and class values.
63 |
64 | Args:
65 | att_val (float): The value of the attribute.
66 | class_val (str): The value of the class.
67 | weight (float): The weight of this observation.
68 | """
69 | if not utils.is_missing_value(att_val):
70 | norm = self._class_lookup.get(class_val, None)
71 | if norm is None:
72 | norm = GaussianEstimator()
73 | self._class_lookup[class_val] = norm
74 | self._min_val_observed_per_class[class_val] = att_val
75 | self._max_val_observed_per_class[class_val] = att_val
76 | else:
77 | if att_val < self._min_val_observed_per_class[class_val]:
78 | self._min_val_observed_per_class[class_val] = att_val
79 | if att_val > self._max_val_observed_per_class[class_val]:
80 | self._max_val_observed_per_class[class_val] = att_val
81 | norm.add_value(att_val, weight)
82 |
83 | def probability_of_att_val_conditioned_on_class(self, att_val, class_val):
84 | """Return the probability of an attribute value conditioned on a class value.
85 |
86 | Args:
87 | att_val (float): The attribute value to compute the conditional probability for.
88 | class_val (str): The class value.
89 |
90 | Returns:
91 | float: The probability of the attribute value being conditioned on the given class value.
92 | """
93 | norm = self._class_lookup.get(class_val, None)
94 | if norm is None:
95 | return 0
96 | return norm.probability_density(att_val)
97 |
98 | def _get_split_point_candidates(self):
99 | splits = SortedList()
100 | min_value = math.inf
101 | max_value = -math.inf
102 |
103 | for class_val, att_estimator in self._class_lookup.items():
104 | min_val_observed_for_class_val = self._min_val_observed_per_class.get(class_val, None)
105 | if min_val_observed_for_class_val is not None:
106 | if min_val_observed_for_class_val < min_value:
107 | min_value = min_val_observed_for_class_val
108 | max_val_observed_for_class_val = self._max_val_observed_per_class.get(class_val)
109 | if max_val_observed_for_class_val > max_value:
110 | max_value = max_val_observed_for_class_val
111 |
112 | if min_value < math.inf:
113 | new_bin = max_value - min_value
114 | new_bin /= (self._num_bins + 1)
115 | for i in range(self._num_bins):
116 | split = min_value + (new_bin * (i + 1))
117 | if split > min_value and split < max_value:
118 | splits.add(split)
119 | return splits
120 |
121 | def _class_dists_after_split(self, split_val):
122 | lhs_dist = {}
123 | rhs_dist = {}
124 |
125 | for class_val, att_estimator in self._class_lookup.items():
126 | if att_estimator is not None:
127 | if split_val < self._min_val_observed_per_class[class_val]:
128 | mass = rhs_dist.get(class_val, None)
129 | if mass is None:
130 | mass = WeightMass()
131 | rhs_dist[class_val] = mass
132 | mass.weight += att_estimator.get_sum_of_weights()
133 | elif split_val > self._max_val_observed_per_class[class_val]:
134 | mass = lhs_dist.get(class_val, None)
135 | if mass is None:
136 | mass = WeightMass()
137 | lhs_dist[class_val] = mass
138 | mass.weight += att_estimator.get_sum_of_weights()
139 | else:
140 | weights = att_estimator.weight_less_than_equal_and_greater_than(split_val)
141 | mass = lhs_dist.get(class_val, None)
142 | if mass is None:
143 | mass = WeightMass()
144 | lhs_dist[class_val] = mass
145 | mass.weight += weights[0] + weights[1]
146 | mass = rhs_dist.get(class_val, None)
147 | if mass is None:
148 | mass = WeightMass()
149 | rhs_dist[class_val] = mass
150 | mass.weight += weights[2]
151 |
152 | dists = [lhs_dist, rhs_dist]
153 | return dists
154 |
155 | def best_split(self, split_metric, pre_split_dist, att_name):
156 | """Return the best split.
157 |
158 | Args:
159 | split_metric (SplitMetric): The split metric to use.
160 | pre_split_dist (dict): The distribution of class values before the split.
161 | att_name (str): The name of the attribute being considered for splitting.
162 |
163 | Returns:
164 | SplitCandidate: The best split for the attribute.
165 | """
166 | best = None
167 | candidates = self._get_split_point_candidates()
168 | for candidate in candidates:
169 | post_split_dists = self._class_dists_after_split(candidate)
170 | split_merit = split_metric.evaluate_split(pre_split_dist, post_split_dists)
171 | if best is None or split_merit > best.split_merit:
172 | split = UnivariateNumericBinarySplit(att_name, candidate)
173 | best = SplitCandidate(split, post_split_dists, split_merit)
174 |
175 | return best
176 |
--------------------------------------------------------------------------------
/HoeffdingTree/ht/ginisplitmetric.py:
--------------------------------------------------------------------------------
1 | from ..ht.splitmetric import SplitMetric
2 |
3 | class GiniSplitMetric(SplitMetric):
4 | """The Gini split metric."""
5 | def evaluate_split(self, pre_dist, post_dist):
6 | total_weight = 0.0
7 | dist_weights = []
8 | for i in range(len(post_dist)):
9 | dist_weights.append(self.sum(post_dist[i]))
10 | total_weight += dist_weights[i]
11 | gini_metric = 0
12 | for i in range(len(post_dist)):
13 | gini_metric += (dist_weights[i] / total_weight) * self.gini(
14 | post_dist[i], dist_weights[i])
15 |
16 | return 1.0 - gini_metric
17 |
18 | def gini(self, dist, sum_of_weights=None):
19 | if sum_of_weights is None:
20 | sum_of_weights = self.sum(dist)
21 | gini_metric = 1.0
22 | for class_value, mass in dist.items():
23 | frac = mass.weight / sum_of_weights
24 | gini_metric -= frac * frac
25 | return gini_metric
26 |
27 | def get_metric_range(self, pre_dist):
28 | return 1.0
29 |
--------------------------------------------------------------------------------
/HoeffdingTree/ht/hnode.py:
--------------------------------------------------------------------------------
1 | from abc import ABCMeta, abstractmethod
2 | from ..ht.weightmass import WeightMass
3 | from ..core import utils
4 |
5 | class HNode(metaclass=ABCMeta):
6 | """Base for the Hoeffding Tree nodes.
7 |
8 | Args:
9 | class_distribution (dict): The class distribution used to create the node. (default None)
10 | """
11 | def __init__(self, class_distribution=None):
12 | if class_distribution is None:
13 | # Dict of tuples (class value, WeightMass)
14 | class_distribution = {}
15 | self.class_distribution = class_distribution
16 | self._leaf_num = None
17 | self._node_num = None
18 |
19 | def __str__(self, print_leaf=False):
20 | self.install_node_nums(0)
21 | # Wrapper for a string
22 | buff = ['']
23 | self._dump_tree(0, 0, buff)
24 | if print_leaf:
25 | buff[0] += "\n\n"
26 | self._print_leaf_models(buff)
27 | # Returns only the string
28 | return buff[0]
29 |
30 | def is_leaf(self):
31 | return True
32 |
33 | def num_entries_in_class_distribution(self):
34 | return len(self.class_distribution)
35 |
36 | def class_distribution_is_pure(self):
37 | count = 0
38 | for class_value, mass in self.class_distribution.items():
39 | if mass.weight > 0:
40 | count += 1
41 | if count > 1:
42 | break
43 | return count < 2
44 |
45 | def update_distribution(self, instance):
46 | if instance.class_is_missing():
47 | return
48 | class_val = instance.string_value(attribute=instance.class_attribute())
49 | mass = self.class_distribution.get(class_val, None)
50 | if mass is None:
51 | mass = WeightMass()
52 | mass.weight = 1.0
53 | self.class_distribution[class_val] = mass
54 |
55 | self.class_distribution[class_val].weight += instance.weight()
56 |
57 | def get_distribution(self, instance, class_attribute):
58 | dist = [0.0 for i in range(class_attribute.num_values())]
59 |
60 | for i in range(class_attribute.num_values()):
61 | mass = self.class_distribution.get(class_attribute.value(i), None)
62 | if mass is not None:
63 | dist[i] = mass.weight
64 | else:
65 | dist[i] = 1.0
66 |
67 | utils.normalize(dist)
68 | return dist
69 |
70 | def install_node_nums(self, node_num):
71 | node_num += 1
72 | self._node_num = node_num
73 | return node_num
74 |
75 | def _dump_tree(self, depth, leaf_count, buff):
76 | max_value = -1
77 | class_val = ''
78 | for class_value, mass in self.class_distribution.items():
79 | if mass.weight > max_value:
80 | max_value = mass.weight
81 | class_val = class_value
82 | buff[0] += '{0} ({1})'.format(class_val, max_value)
83 | leaf_count += 1
84 | self._leaf_num = leaf_count
85 | return leaf_count
86 |
87 | def _print_leaf_models(self, buff):
88 | pass
89 |
90 | def total_weight(self):
91 | tw = 0.0
92 | for class_value, mass in self.class_distribution.items():
93 | tw += mass.weight
94 | return tw
95 |
96 | def leaf_for_instance(self, instance, parent, parent_branch):
97 | from ..ht.leafnode import LeafNode
98 | return LeafNode(self, parent, parent_branch)
99 |
100 | @abstractmethod
101 | def update_node(self, instance):
102 | pass
103 |
--------------------------------------------------------------------------------
/HoeffdingTree/ht/inactivehnode.py:
--------------------------------------------------------------------------------
1 | from ..ht.leafnode import LeafNode
2 |
3 | class InactiveHNode(LeafNode):
4 | """A Hoeffding Tree node that is inactive (does not support growth)."""
5 | def __init__(self, class_distribution):
6 | super().__init__(class_distribution)
7 |
8 | def update_node(self, instance):
9 | self.update_distribution(instance)
10 |
--------------------------------------------------------------------------------
/HoeffdingTree/ht/infogainsplitmetric.py:
--------------------------------------------------------------------------------
1 | from ..ht.splitmetric import SplitMetric
2 | from ..core import utils
3 | import math
4 |
5 | class InfoGainSplitMetric(SplitMetric):
6 | """The Info Gain split metric."""
7 | def __init__(self, min_frac_weight_for_two_branches):
8 | self._min_frac_weight_for_two_branches = min_frac_weight_for_two_branches
9 |
10 | def evaluate_split(self, pre_dist, post_dist):
11 | pre = []
12 | for class_value, mass in pre_dist.items():
13 | pre.append(pre_dist[class_value].weight)
14 | pre_entropy = utils.entropy(pre)
15 |
16 | dist_weights = []
17 | total_weight = 0.0
18 | for i in range(len(post_dist)):
19 | dist_weights.append(self.sum(post_dist[i]))
20 | total_weight += dist_weights[i]
21 |
22 | frac_count = 0
23 | for d in dist_weights:
24 | if d / total_weight > self._min_frac_weight_for_two_branches:
25 | frac_count += 1
26 |
27 | if frac_count < 2:
28 | return -math.inf
29 |
30 | post_entropy = 0
31 | for i in range(len(post_dist)):
32 | d = post_dist[i]
33 | post = []
34 | for class_value, mass in d.items():
35 | post.append(mass.weight)
36 | post_entropy += dist_weights[i] * utils.entropy(post)
37 |
38 | if total_weight > 0:
39 | post_entropy /= total_weight
40 |
41 | return pre_entropy - post_entropy
42 |
43 | def get_metric_range(self, pre_dist):
44 | num_classes = len(pre_dist)
45 | if num_classes < 2:
46 | num_classes = 2
47 |
48 | return math.log2(num_classes)
49 |
--------------------------------------------------------------------------------
/HoeffdingTree/ht/leafnode.py:
--------------------------------------------------------------------------------
1 | from ..ht.hnode import HNode
2 |
3 | class LeafNode(HNode):
4 | """A Hoeffding Tree leaf node."""
5 | def __init__(self, node=None, parent_node=None, parent_branch=None):
6 | super().__init__()
7 | self.the_node = node
8 | self.parent_node = parent_node
9 | self.parent_branch = parent_branch
10 |
11 | def update_node(self, instance):
12 | if self.the_node is not None:
13 | self.the_node.update_distribution(instance)
14 | else:
15 | self.update_distribution(instance)
16 |
--------------------------------------------------------------------------------
/HoeffdingTree/ht/nominalconditionalsufficientstats.py:
--------------------------------------------------------------------------------
1 | from ..ht.conditionalsufficientstats import ConditionalSufficientStats
2 | from ..ht.weightmass import WeightMass
3 | from ..ht.splitcandidate import SplitCandidate
4 | from ..ht.univariatenominalmultiwaysplit import UnivariateNominalMultiwaySplit
5 | from ..core import utils
6 |
7 | class ValueDistribution(object):
8 | """Discrete distribution for the NominalConditionalSufficientStats class."""
9 | def __init__(self):
10 | self._dist = {}
11 | self.__sum = 0
12 |
13 | def add(self, val, weight):
14 | count = self._dist.get(val, None)
15 | if count is None:
16 | count = WeightMass()
17 | count.weight = 1.0
18 | self.__sum += 1.0
19 | self._dist[val] = count
20 | count.weight += weight
21 | self.__sum += weight
22 |
23 | def delete(self, val, weight):
24 | count = self._dist.get(val, None)
25 | if count is not None:
26 | count.weight -= weight
27 | self.__sum -= weight
28 |
29 | def get_weight(self, val):
30 | count = self._dist.get(val, None)
31 | if count is not None:
32 | return count.weight
33 | return 0.0
34 |
35 | def sum(self):
36 | return self.__sum
37 |
38 | class NominalConditionalSufficientStats(ConditionalSufficientStats):
39 | """A class for keeping record of the sufficient statistics for a nominal attribute."""
40 | def __init__(self):
41 | super().__init__()
42 | self._total_weight = 0
43 | self._missing_weight = 0
44 |
45 | def update(self, att_val, class_val, weight):
46 | if utils.is_missing_value(att_val):
47 | self._missing_weight += weight
48 | else:
49 | val_dist = self._class_lookup.get(class_val, None)
50 | if val_dist is None:
51 | val_dist = ValueDistribution()
52 | val_dist.add(att_val, weight)
53 | self._class_lookup[class_val] = val_dist
54 | else:
55 | val_dist.add(att_val, weight)
56 | self._total_weight += weight
57 |
58 | def probability_of_att_val_conditioned_on_class(self, att_val, class_val):
59 | val_dist = self._class_lookup.get(class_val, None)
60 | if val_dist is not None:
61 | return val_dist.get_weight(att_val) / val_dist.sum()
62 | return 0
63 |
64 | def _class_dists_after_split(self):
65 | split_dists = {}
66 | for class_val, att_dist in self._class_lookup.items():
67 | for att_val, att_count in att_dist._dist.items():
68 | cls_dist = split_dists.get(att_val, None)
69 | if cls_dist is None:
70 | cls_dist = {}
71 | split_dists[att_val] = cls_dist
72 |
73 | cls_count = cls_dist.get(class_val, None)
74 | if cls_count is None:
75 | cls_count = WeightMass()
76 | cls_dist[class_val] = cls_count
77 | cls_count.weight += att_count.weight
78 |
79 | result = []
80 | for att_index, dist in split_dists.items():
81 | result.append(dist)
82 | return result
83 |
84 | def best_split(self, split_metric, pre_split_dist, att_name):
85 | post_split_dists = self._class_dists_after_split()
86 | merit = split_metric.evaluate_split(pre_split_dist, post_split_dists)
87 | candidate = SplitCandidate(
88 | UnivariateNominalMultiwaySplit(att_name), post_split_dists, merit)
89 | return candidate
90 |
--------------------------------------------------------------------------------
/HoeffdingTree/ht/split.py:
--------------------------------------------------------------------------------
1 | from abc import ABCMeta, abstractmethod
2 |
3 | class Split(metaclass=ABCMeta):
4 | """Base for classes that handle splitting (UnivariateNominaMultiwaySplit
5 | and UnivariateNumericBinarySplit)."""
6 | def __init__(self):
7 | self._split_att_names = []
8 |
9 | @abstractmethod
10 | def branch_for_instance(self, instance):
11 | pass
12 |
13 | @abstractmethod
14 | def condition_for_branch(self, branch):
15 | pass
16 |
17 | def split_attributes(self):
18 | return self._split_att_names
--------------------------------------------------------------------------------
/HoeffdingTree/ht/splitcandidate.py:
--------------------------------------------------------------------------------
1 | class SplitCandidate(object):
2 | """Class for handling a split candidate."""
3 | def __init__(self, split_test, post_split_dists, merit):
4 | self.split_test = split_test
5 | self.post_split_class_distributions = post_split_dists
6 | self.split_merit = merit
7 |
8 | def num_splits(self):
9 | return len(self.post_split_class_distributions)
--------------------------------------------------------------------------------
/HoeffdingTree/ht/splitmetric.py:
--------------------------------------------------------------------------------
1 | from abc import ABCMeta, abstractmethod
2 |
3 | class SplitMetric(metaclass=ABCMeta):
4 | """Base for Info Gain and Gini split metrics."""
5 | def sum(self, dist):
6 | weight_sum = 0
7 | for class_value, mass in dist.items():
8 | weight_sum += dist[class_value].weight
9 | return weight_sum
10 |
11 | @abstractmethod
12 | def evaluate_split(self, pre_dist, post_dist):
13 | pass
14 |
15 | @abstractmethod
16 | def get_metric_range(self, pre_dist):
17 | pass
--------------------------------------------------------------------------------
/HoeffdingTree/ht/splitnode.py:
--------------------------------------------------------------------------------
1 | from ..ht.hnode import HNode
2 | from ..ht.leafnode import LeafNode
3 |
4 | class SplitNode(HNode):
5 | """A Hoeffding Tree node used for splits."""
6 | def __init__(self, class_distrib, split):
7 | super().__init__(class_distrib)
8 | self.split = split
9 | # Dict of tuples (branch, child)
10 | self.children = {}
11 |
12 | def branch_for_instance(self, instance):
13 | return self.split.branch_for_instance(instance)
14 |
15 | def is_leaf(self):
16 | return False
17 |
18 | def num_children(self):
19 | return len(self.children)
20 |
21 | def set_child(self, branch, child):
22 | self.children[branch] = child
23 |
24 | def leaf_for_instance(self, instance, parent, parent_branch):
25 | branch = self.branch_for_instance(instance)
26 | if branch is not None:
27 | child = self.children.get(branch, None)
28 | if child is not None:
29 | return child.leaf_for_instance(instance, self, branch)
30 | return LeafNode(None, self, branch)
31 | return LeafNode(self, parent, parent_branch)
32 |
33 | def update_node(self, instance):
34 | # Don't update the distribution
35 | pass
36 |
37 | def _dump_tree(self, depth, leaf_count, buff):
38 | for branch, child in self.children.items():
39 | if child is not None:
40 | buff[0] += '\n'
41 | for i in range(depth):
42 | buff[0] += '| '
43 | buff[0] += '{0}: '.format(self.split.condition_for_branch(branch))
44 | leaf_count = child._dump_tree(depth + 1, leaf_count, buff)
45 | return leaf_count
46 |
47 | def install_node_nums(self, node_num):
48 | node_num = super().install_node_nums(node_num)
49 |
50 | for branch, child in self.children.items():
51 | if child is not None:
52 | node_num = child.install_node_nums(node_num)
53 | return node_num
54 |
55 | def _print_leaf_models(self, buff):
56 | for branch, child in self.children.items():
57 | if child is not None:
58 | child._print_leaf_models(buff)
59 |
--------------------------------------------------------------------------------
/HoeffdingTree/ht/univariatenominalmultiwaysplit.py:
--------------------------------------------------------------------------------
1 | from ..ht.split import Split
2 |
3 | class UnivariateNominalMultiwaySplit(Split):
4 | """Multiway split based on a nominal attribute."""
5 | def __init__(self, att_name):
6 | super().__init__()
7 | self._split_att_names.append(att_name)
8 |
9 | def branch_for_instance(self, instance):
10 | att = instance.dataset().attribute(name=self._split_att_names[0])
11 | if att is None or instance.is_missing(att.index()):
12 | return None
13 | return att.value(instance.value(attribute=att))
14 |
15 | def condition_for_branch(self, branch):
16 | return '{0} = {1}'.format(self._split_att_names[0], branch)
17 |
--------------------------------------------------------------------------------
/HoeffdingTree/ht/univariatenumericbinarysplit.py:
--------------------------------------------------------------------------------
1 | from ..ht.split import Split
2 |
3 | class UnivariateNumericBinarySplit(Split):
4 | """Binary split based on a numeric attribute."""
5 | def __init__(self, att_name, split_point):
6 | super().__init__()
7 | self._split_att_names.append(att_name)
8 | self._split_point = split_point
9 |
10 | def branch_for_instance(self, instance):
11 | att = instance.dataset().attribute(name=self._split_att_names[0])
12 | if att is None or instance.is_missing(att.index()):
13 | return None
14 | if instance.value(attribute=att) <= self._split_point:
15 | return 'left'
16 | return 'right'
17 |
18 | def condition_for_branch(self, branch):
19 | result = self._split_att_names[0]
20 | if branch is 'left':
21 | result += ' <= '
22 | else:
23 | result += ' > '
24 | result += '{0}'.format(self._split_point)
25 | return result
26 |
--------------------------------------------------------------------------------
/HoeffdingTree/ht/weightmass.py:
--------------------------------------------------------------------------------
1 | class WeightMass(object):
2 | """Wrapper for a weight value."""
3 | def __init__(self):
4 | self.weight = 0
--------------------------------------------------------------------------------
/HoeffdingTree/main.py:
--------------------------------------------------------------------------------
1 | import csv
2 | from hoeffdingtree import *
3 |
4 | def open_dataset(filename, class_index, probe_instances=100):
5 | """ Open and initialize a dataset in CSV format.
6 | The CSV file needs to have a header row, from where the attribute names will be read, and a set
7 | of instances containing at least one example of each value of all nominal attributes.
8 |
9 | Args:
10 | filename (str): The name of the dataset file (including filepath).
11 | class_index (int): The index of the attribute to be set as class.
12 | probe_instances (int): The number of instances to be used to initialize the nominal
13 | attributes. (default 100)
14 |
15 | Returns:
16 | Dataset: A dataset initialized with the attributes and instances of the given CSV file.
17 | """
18 | if not filename.endswith('.csv'):
19 | raise TypeError(
20 | 'Unable to open \'{0}\'. Only datasets in CSV format are supported.'
21 | .format(filename))
22 | with open(filename) as f:
23 | fr = csv.reader(f)
24 | headers = next(fr)
25 |
26 | att_values = [[] for i in range(len(headers))]
27 | instances = []
28 | try:
29 | for i in range(probe_instances):
30 | inst = next(fr)
31 | instances.append(inst)
32 | for j in range(len(headers)):
33 | try:
34 | inst[j] = float(inst[j])
35 | att_values[j] = None
36 | except ValueError:
37 | inst[j] = str(inst[j])
38 | if isinstance(inst[j], str):
39 | if att_values[j] is not None:
40 | if inst[j] not in att_values[j]:
41 | att_values[j].append(inst[j])
42 | else:
43 | raise ValueError(
44 | 'Attribute {0} has both Numeric and Nominal values.'
45 | .format(headers[j]))
46 | # Tried to probe more instances than there are in the dataset file
47 | except StopIteration:
48 | pass
49 |
50 | attributes = []
51 | for i in range(len(headers)):
52 | if att_values[i] is None:
53 | attributes.append(Attribute(str(headers[i]), att_type='Numeric'))
54 | else:
55 | attributes.append(Attribute(str(headers[i]), att_values[i], 'Nominal'))
56 |
57 | dataset = Dataset(attributes, class_index)
58 | for inst in instances:
59 | for i in range(len(headers)):
60 | if attributes[i].type() == 'Nominal':
61 | inst[i] = int(attributes[i].index_of_value(str(inst[i])))
62 | dataset.add(Instance(att_values=inst))
63 |
64 | return dataset
65 |
66 | def main():
67 | filename = 'dataset_file.csv'
68 | dataset = open_dataset(filename, 1, probe_instances=10000)
69 | vfdt = HoeffdingTree()
70 |
71 | # Set some of the algorithm parameters
72 | vfdt.set_grace_period(50)
73 | vfdt.set_hoeffding_tie_threshold(0.05)
74 | vfdt.set_split_confidence(0.0001)
75 | # Split criterion, for now, can only be set on hoeffdingtree.py file.
76 | # This is only relevant when Information Gain is chosen as the split criterion
77 | vfdt.set_minimum_fraction_of_weight_info_gain(0.01)
78 |
79 | vfdt.build_classifier(dataset)
80 |
81 | # Simulate a data stream
82 | with open(filename) as f:
83 | stream = csv.reader(f)
84 | # Ignore the CSV headers
85 | next(stream)
86 | for item in stream:
87 | inst_values = list(item)
88 | for i in range(len(inst_values)):
89 | if dataset.attribute(index=i).type() == 'Nominal':
90 | inst_values[i] = int(dataset.attribute(index=i)
91 | .index_of_value(str(inst_values[i])))
92 | else:
93 | inst_values[i] = float(inst_values[i])
94 | new_instance = Instance(att_values=inst_values)
95 | new_instance.set_dataset(dataset)
96 | vfdt.update_classifier(new_instance)
97 | print(vfdt)
98 |
99 | if __name__ == '__main__':
100 | main()
101 |
102 |
--------------------------------------------------------------------------------
/README.assets/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/README.assets/.DS_Store
--------------------------------------------------------------------------------
/README.assets/image-20190830143305580.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/README.assets/image-20190830143305580.png
--------------------------------------------------------------------------------
/README.assets/image-20190830143415142.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/README.assets/image-20190830143415142.png
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Introduction
2 |
3 | Python code for ACDWM (Adaptive Chunk-based Dynamic Weighted Majority)
4 |
5 | Author: [Yang Lu](https://jasonyanglu.github.io/)
6 |
7 | Contact: lylylytc@gmail.com
8 |
9 | ## Run
10 |
11 | Run Python 3 by:
12 |
13 | ```shell
14 | main.py dataset_name.npz
15 | ```
16 |
17 | The dataset can be chosen by:
18 |
19 | drifting_gaussian_abrupt.npz
20 | drifting_gaussian_gradual.npz
21 | elec2_abrupt.npz
22 | elec2_gradual.npz
23 | hyperP_abrupt.npz
24 | hyperP_gradual.npz
25 | moving_gaussian_abrupt.npz
26 | moving_gaussian_gradual.npz
27 | noaa_abrupt.npz
28 | noaa_gradual.npz
29 | rotcb_abrupt.npz
30 | rotcb_gradual.npz
31 | rotsp_abrupt.npz
32 | rotsp_gradual.npz
33 | sea_abrupt.npz
34 | sea_gradual.npz
35 |
36 | ## Datasets
37 |
38 | ### Information
39 |
40 | * Moving Gaussian: This data stream consists of two Gaussian distributed classes with identity covariance and 2 dimensions. The initial coordinates of the mean of the two classes are [5,0] and [7,0]. They gradually move to [-5,0] and [-3,0] from the beginning to the half of the stream and then move back to the initial coordinates.
41 |
42 | * Drifting Gaussian: It is a linear combination of three Gaussian components and one of them is the minority class. The mean and variance of the Gaussian components are varying along all time.
43 |
44 | * SEA: It contains three attributes ranging from 0 to 10. Only the first two attributes are related to the class that is determined by $attr_1+attr_2\le \alpha$. The third attribute is treated as noise. The control parameter $\alpha$ is set at 15 for the first 1/3 and the last 1/3 chunks, and 5 for the second 1/3 chunks.
45 |
46 | * Hyper Plane: The gradually changed concepts are calculated by $f(\mathbf{x})=\sum_{i=1}^{d-1}a_i\cdot\frac{x_i+x_{i+1}}{x_i}$, where the dimension $d=10$ and $a_i$ is used to control the decision hyperplane.
47 |
48 | * Spiral: There are four spirals are rotating with a size-fixed two dimensional window. The position of the spirals are used to predict the class.
49 |
50 | * Checkerboard: It is a non-linear XOR classification problem. The data stream is produced by selecting from a size-fixed window in the rotating checkerboard.
51 |
52 | * Electricity: This dataset contains the changes of electricity price according to the time and demand in New South Wales, Australian. The class label is determined by the change of price over the last 24 hours.
53 |
54 | * Weather: This dataset contains the weather information over 50 years in Bellevue and Nebraska. The task is to predict whether a day is rainy or not.
55 |
56 |
57 |
58 |
59 |
60 | ### Drift Modes
61 |
62 | In the experiments, the imbalance ratio is changed by two prior drift modes:
63 |
64 | * Abrupt drift: The imbalance ratio is initially set at 0.01. After half of the data stream, the imbalance ratio suddenly changes to 0.99, namely the majority class becomes to the minority class with imbalance ratio 0.01. The prequential measures are reset at the position of the abrupt drift.
65 |
66 | * Gradual drift: The imbalance ratio is initially set at 0.01. After 1/3 of the data stream, the imbalance ratio starts to gradually increase until 0.99 at 2/3 of the data stream. The prequential measures are reset at the starting and ending position of the gradual drift.
67 |
68 | The imbalance ratio here refers to the percentage of positive class samples. To control the imbalance ratio, undersampling is done on every 1000 samples in the original data stream. The majority class is undersampled if the original imbalance ratio on this chunk is smaller than the assigned imbalance ratio, and the minority class is undersampled vice versa. As the original imbalance ratio of each dataset is different, the drift position after undersampling is also different.
69 |
70 |
71 |
72 |
73 |
74 | ## Paper
75 |
76 | Please cite the paper if the codes are helpful for you research.
77 |
78 | Yang Lu, Yiu-ming Cheung, and Yuan Yan Tang, “Adaptive Chunk-based Dynamic Weighted Majority for Imbalanced Data Streams with Concept Drift”, in *IEEE Transactions on Neural Networks and Learning Systems*, DOI:10.1109/TNNLS.2019.2951814.
--------------------------------------------------------------------------------
/check_measure.py:
--------------------------------------------------------------------------------
1 | from numpy import *
2 | from sklearn import metrics
3 |
4 |
5 | def prequential_measure(pred, label, reset_pos=array([0])):
6 | n = pred.size
7 | pq_result = {}
8 |
9 | pq_result['gm'] = zeros(n)
10 | pq_result['f1'] = zeros(n)
11 | pq_result['auc'] = zeros(n)
12 | pq_result['rec'] = zeros(n)
13 |
14 | for i in range(n):
15 | start_pos = sum(i >= reset_pos) - 1
16 | pq_result['gm'][i] = gm_measure(pred[reset_pos[start_pos]:i + 1], label[reset_pos[start_pos]:i + 1])
17 | pq_result['f1'][i] = f1_measure(pred[reset_pos[start_pos]:i + 1], label[reset_pos[start_pos]:i + 1])
18 | pq_result['auc'][i] = auc_measure(pred[reset_pos[start_pos]:i + 1], label[reset_pos[start_pos]:i + 1])
19 | pq_result['rec'][i] = rec_measure(pred[reset_pos[start_pos]:i + 1], label[reset_pos[start_pos]:i + 1])
20 |
21 | return pq_result
22 |
23 |
24 | def gm_measure(pred, label):
25 | label = label.reshape(-1)
26 | tp = sum(bitwise_and(label == 1, pred == 1))
27 | fn = sum(bitwise_and(label == 1, pred == -1))
28 | tn = sum(bitwise_and(label == -1, pred == -1))
29 | fp = sum(bitwise_and(label == -1, pred == 1))
30 |
31 | if tp + fn == 0 or tn + fp == 0:
32 | gm = 0
33 | else:
34 | gm = sqrt(tp / (tp + fn) * tn / (tn + fp))
35 |
36 | return gm
37 |
38 |
39 | def f1_measure(pred, label):
40 | label = label.reshape(-1)
41 | tp = sum(bitwise_and(label == 1, pred == 1))
42 | fn = sum(bitwise_and(label == 1, pred == -1))
43 | tn = sum(bitwise_and(label == -1, pred == -1))
44 | fp = sum(bitwise_and(label == -1, pred == 1))
45 |
46 | if tp + fp != 0:
47 | precision = tp / (tp + fp)
48 | else:
49 | precision = 0
50 |
51 | if tp + fn != 0:
52 | recall = tp / (tp + fn)
53 | else:
54 | recall = 0
55 |
56 | if precision == 0 and recall == 0:
57 | f1 = 0
58 | else:
59 | f1 = 2 * precision * recall / (precision + recall)
60 |
61 | return f1
62 |
63 |
64 | def auc_measure(pred, label):
65 | fpr, tpr, thresholds = metrics.roc_curve(label, pred, pos_label=1)
66 | try:
67 | auc = metrics.auc(fpr, tpr)
68 | except ValueError:
69 | auc = 0
70 |
71 | if isnan(auc):
72 | auc = 0
73 |
74 | return auc
75 |
76 |
77 | def rec_measure(pred, label):
78 | if sum(label == 1) > sum(label == -1):
79 | min_class = -1
80 | else:
81 | min_class = 1
82 |
83 | label = label.reshape(-1)
84 | tp = sum(bitwise_and(label == min_class, pred == min_class))
85 | fn = sum(bitwise_and(label == min_class, pred == -min_class))
86 | tn = sum(bitwise_and(label == -min_class, pred == -min_class))
87 | fp = sum(bitwise_and(label == -min_class, pred == min_class))
88 |
89 | if tp + fn == 0:
90 | rec = 0
91 | else:
92 | rec = tp / (tp + fn)
93 |
94 | return rec
95 |
--------------------------------------------------------------------------------
/chunk_based_methods.py:
--------------------------------------------------------------------------------
1 | from numpy import *
2 | from check_measure import *
3 | from underbagging import *
4 | from subunderbagging import *
5 | from sklearn.metrics import f1_score
6 | from sklearn.neighbors import NearestNeighbors
7 | from sklearn.tree import DecisionTreeClassifier
8 | from itertools import combinations
9 | import cvxpy
10 | import time
11 |
12 | import abc
13 |
14 |
15 | class ChunkBase:
16 |
17 | def __init__(self):
18 |
19 | self.ensemble = list()
20 | self.chunk_count = 0
21 | self.train_count = 0
22 | self.w = array([])
23 | self.buf_data = array([])
24 | self.buf_label = array([])
25 |
26 | def _predict_base(self, test_data, prob_output=False):
27 |
28 | if len(self.ensemble) == 0:
29 | pred = zeros(test_data.shape[0])
30 | else:
31 | pred = zeros([test_data.shape[0], len(self.ensemble)])
32 | for i in range(len(self.ensemble)):
33 | if prob_output:
34 | pred[:, i] = self.ensemble[i].predict_proba(test_data)[:, 1]
35 | else:
36 | pred[:, i] = self.ensemble[i].predict(test_data)
37 |
38 | return pred
39 |
40 | @abc.abstractmethod
41 | def _update_chunk(self, data, label):
42 | pass
43 |
44 | def update(self, single_data, single_label):
45 |
46 | pred = self.predict(single_data.reshape(1, -1))
47 |
48 | if self.buf_label.size < self.chunk_size:
49 | self.buf_data = r_[self.buf_data.reshape(-1, single_data.shape[0]), single_data.reshape(1, -1)]
50 | self.buf_label = r_[self.buf_label, single_label]
51 | self.train_count += 1
52 |
53 | if self.buf_label.size == self.chunk_size or self.train_count == self.data_num:
54 | print('Data ' + str(self.train_count) + ' / ' + str(self.data_num))
55 | self._update_chunk(self.buf_data, self.buf_label)
56 | self.buf_data = array([])
57 | self.buf_label = array([])
58 |
59 | return pred
60 |
61 | def update_chunk(self, data, label):
62 |
63 | pred = self.predict(data)
64 | self._update_chunk(data, label)
65 |
66 | return pred
67 |
68 | def predict(self, test_data):
69 |
70 | all_pred = sign(self._predict_base(test_data))
71 | if len(self.w) != 0:
72 | pred = sign(dot(all_pred, self.w))
73 | else:
74 | pred = all_pred
75 |
76 | return pred
77 |
78 | def calculate_err(self, all_pred, label):
79 |
80 | ensemble_size = all_pred.shape[1]
81 | err = zeros(ensemble_size)
82 | for i in range(ensemble_size):
83 | if self.err_func == 'gm':
84 | err[i] = 1 - gm_measure(all_pred[:, i], label)
85 |
86 | elif self.err_fun == 'f1':
87 | err[i] = 1 - f1_score(label, all_pred[:, i])
88 |
89 | return err
90 |
91 |
92 | class UB(ChunkBase):
93 |
94 | def __init__(self, data_num, r=0.5, chunk_size=1000):
95 |
96 | ChunkBase.__init__(self)
97 |
98 | self.data_num = data_num
99 | self.r = r
100 | self.stored_data = array([])
101 | self.stored_label = array([])
102 | self.chunk_size = chunk_size
103 |
104 | self.w = array([1])
105 |
106 | def _update_chunk(self, data, label):
107 |
108 | pos_idx = label == 1
109 | neg_idx = label == -1
110 |
111 | # accumulate the minority class samples
112 | self.stored_data = r_[self.stored_data.reshape(-1, data.shape[1]), data[pos_idx]]
113 | self.stored_label = r_[self.stored_label, label[pos_idx]]
114 | sampling_data = r_[self.stored_data, data[neg_idx]]
115 | sampling_label = r_[self.stored_label, label[neg_idx]]
116 |
117 | model = UnderBagging(r=self.r, sampling_class=-1)
118 | model.train(sampling_data, label)
119 |
120 | # only one ensemble classifier is kept
121 | self.ensemble = list()
122 | self.ensemble.append(model)
123 | self.chunk_count += 1
124 | all_pred = sign(self._predict_base(data))
125 |
126 | if self.chunk_count > 1:
127 | pred = all_pred
128 | else:
129 | pred = zeros_like(label)
130 |
131 | pred = sign(pred)
132 |
133 | return pred
134 |
135 |
136 | class REA(ChunkBase):
137 |
138 | def __init__(self, data_num, f=0.5, k=10, chunk_size=1000):
139 |
140 | ChunkBase.__init__(self)
141 |
142 | self.data_num = data_num
143 | self.f = f
144 | self.k = k
145 | self.stored_data = array([])
146 | self.stored_label = array([])
147 | self.chunk_size = chunk_size
148 |
149 | def _update_chunk(self, data, label):
150 |
151 | pos_idx = label == 1
152 | neg_idx = label == -1
153 | pos_num = sum(pos_idx)
154 | neg_num = sum(neg_idx)
155 |
156 | if pos_num > neg_num:
157 | min_class = -1
158 | gamma = neg_num / pos_num
159 | else:
160 | min_class = 1
161 | gamma = pos_num / neg_num
162 |
163 | if self.f > self.chunk_count * gamma:
164 | sampling_data = r_[self.stored_data.reshape(-1, data.shape[1]), data]
165 | sampling_label = r_[self.stored_label, label]
166 |
167 | else:
168 | nbrs = NearestNeighbors(n_neighbors=self.k).fit(data)
169 | _, nn_idx = nbrs.kneighbors(self.stored_data)
170 | delta = zeros_like(self.stored_label)
171 | for i in range(delta.size):
172 | delta[i] = sum([x in nonzero(label == min_class)[0] for x in nn_idx[i]])
173 | sort_idx = argsort(-delta)
174 | add_num = int((self.f - gamma) * label.size)
175 | sampling_data = r_[self.stored_data[sort_idx[:add_num]], data]
176 | sampling_label = r_[self.stored_label[sort_idx[:add_num]], label]
177 |
178 | model = DecisionTreeClassifier(max_leaf_nodes=10, min_samples_leaf=5, max_depth=5)
179 | model.fit(sampling_data, sampling_label)
180 | self.ensemble.append(model)
181 | all_pred = sign(self._predict_base(data, prob_output=True))
182 | all_pred[neg_idx] = 1 - all_pred[neg_idx]
183 | err = mean((1 - all_pred) ** 2, 0)
184 | self.w = log(1 / err)
185 |
186 | self.chunk_count += 1
187 | all_pred[neg_idx] = 1 - all_pred[neg_idx]
188 | all_pred -= 0.5
189 |
190 | if self.chunk_count > 1:
191 | pred = dot(all_pred[:, :-1], self.w[:-1])
192 | else:
193 | pred = zeros_like(label)
194 |
195 | pred = sign(pred)
196 |
197 | self.stored_data = r_[self.stored_data.reshape(-1, data.shape[1]), data[label == min_class]]
198 | self.stored_label = r_[self.stored_label, label[label == min_class]]
199 |
200 | return pred
201 |
202 |
203 | class DFGWIS(ChunkBase):
204 |
205 | def __init__(self, fea_num, data_num, fea_group_num=50, w_lambda=0.5, bin_num=30, T=11, train_ratio=0.85,
206 | chunk_size=1000):
207 |
208 | ChunkBase.__init__(self)
209 |
210 | self.fea_num = fea_num
211 | self.data_num = data_num
212 | self.fea_group_num = fea_group_num
213 | self.w_lambda = w_lambda
214 | self.bin_num = bin_num
215 | self.T = T
216 | self.train_ratio = train_ratio
217 | self.chunk_size = chunk_size
218 |
219 | self.stored_data = list()
220 | self.stored_label = list()
221 | self.s = 0
222 | self.pred = []
223 |
224 | self.fea_group_num = min(2 ** fea_num - 1, self.fea_group_num)
225 |
226 | all_comb = list()
227 | for i in range(fea_num):
228 | all_comb += combinations(range(fea_num), i + 1)
229 |
230 | self.fea_comb = list()
231 | rand_idx = random.permutation(len(all_comb))[:self.fea_group_num]
232 | for i in range(self.fea_group_num):
233 | self.fea_comb.append(all_comb[rand_idx[i]])
234 |
235 | self.ws = zeros(self.fea_group_num)
236 |
237 | def _train(self, data, label, delta):
238 | pos_idx = label == 1
239 | neg_idx = label == -1
240 | pos_num = sum(pos_idx)
241 |
242 | P_data_size = 0
243 | for i in range(self.s, self.chunk_count - 1):
244 | P_data_size += sum(self.stored_label[i] == 1)
245 |
246 | if pos_num + P_data_size > delta:
247 | self.s += 1
248 |
249 | P_data = array([]).reshape(-1, self.fea_num)
250 | ts = array([])
251 |
252 | for i in range(self.s, self.chunk_count):
253 | P_data = r_[P_data, self.stored_data[i][self.stored_label[i] == 1]]
254 | ts = r_[ts, i * ones(sum(self.stored_label[i] == 1))]
255 |
256 | N_data = data[neg_idx]
257 |
258 | pos_num = P_data.shape[0]
259 | neg_num = N_data.shape[0]
260 | rand_idx = random.permutation(pos_num)
261 | P_data = P_data[rand_idx]
262 | ts = ts[rand_idx].astype(int)
263 | N_data = N_data[random.permutation(neg_num)]
264 |
265 | pos_train_num = int(self.train_ratio * pos_num)
266 | neg_train_num = int(self.train_ratio * neg_num)
267 | train_data = r_[P_data[:pos_train_num], N_data[:neg_train_num]]
268 | train_label = r_[ones(pos_train_num), -ones(neg_train_num)]
269 | train_ts = ts[:pos_train_num]
270 | hold_data = r_[P_data[pos_train_num:], N_data[neg_train_num:]]
271 | hold_label = r_[ones(pos_num - pos_train_num), -ones(neg_num - neg_train_num)]
272 |
273 | hold_pred = zeros([hold_label.size, self.fea_group_num])
274 | self.ensemble = list()
275 | for fea_comb_i in range(self.fea_group_num):
276 | self._learnH(train_data[:, self.fea_comb[fea_comb_i]], train_label, train_ts)
277 | hold_pred = self._predict_base(hold_data)
278 |
279 | # solve convex optimization problem
280 | c = ones_like(hold_label)
281 | c[hold_label == 1] = sum(hold_label == -1) / sum(hold_label == 1)
282 |
283 | w = cvxpy.Variable(self.fea_group_num)
284 | obj = cvxpy.Minimize(c.T * cvxpy.logistic(-cvxpy.mul_elemwise(hold_label, hold_pred * w)))
285 | constraints = [cvxpy.sum_entries(w) == 1, w >= 0]
286 |
287 | prob = cvxpy.Problem(obj, constraints)
288 | try:
289 | prob.solve()
290 | except(cvxpy.error.SolverError):
291 | prob.solve(solver=cvxpy.CVXOPT)
292 | self.wd = array(w.value).squeeze()
293 |
294 | # print('optimization time: %f' % (time.time() - start_time))
295 |
296 | def _test(self, data, previous_data):
297 |
298 | pq = zeros(self.fea_num)
299 | for fea_i in range(self.fea_num):
300 | bin_min = min(r_[data[:, fea_i], previous_data[:, fea_i]])
301 | bin_max = max(r_[data[:, fea_i], previous_data[:, fea_i]])
302 | bin_gap = (bin_min - bin_max) / (self.bin_num - 1)
303 |
304 | p = zeros(self.bin_num)
305 | q = zeros(self.bin_num)
306 | for j in range(self.bin_num):
307 | if j + 1 != self.bin_num:
308 | p[j] = sum(logical_and(data[:, fea_i] >= bin_min + j * bin_gap,
309 | data[:, fea_i] < bin_min + (j + 1) * bin_gap))
310 | q[j] = sum(logical_and(previous_data[:, fea_i] >= bin_min + j * bin_gap,
311 | previous_data[:, fea_i] < bin_min + (j + 1) * bin_gap))
312 | else:
313 | p[j] = sum(logical_and(data[:, fea_i] >= bin_min + j * bin_gap,
314 | data[:, fea_i] <= bin_max))
315 | q[j] = sum(logical_and(previous_data[:, fea_i] >= bin_min + j * bin_gap,
316 | previous_data[:, fea_i] <= bin_max))
317 |
318 | p /= sum(p)
319 | q /= sum(q)
320 | pq[fea_i] = sqrt(sum((sqrt(p) - sqrt(q)) ** 2))
321 |
322 | for fea_comb_i in range(self.fea_group_num):
323 | fea_idx = array(self.fea_comb[fea_comb_i])
324 | self.ws[fea_comb_i] = 1 - (mean(pq[fea_idx])) / sqrt(2)
325 | pred = self._predict_base(data)
326 |
327 | alpha = self.w_lambda * self.ws + (1 - self.w_lambda) * self.wd
328 | return sign(dot(pred, alpha))
329 |
330 | def _importance_sampling(self, data, ts):
331 |
332 | t = max(ts)
333 | l = min(ts)
334 | data_num = data.shape[0]
335 |
336 | D = zeros(t + 1)
337 | u = zeros([t + 1, self.fea_num])
338 | v = zeros([t + 1, self.fea_num])
339 | for k in range(l, t + 1):
340 | D[k] = sum(ts == k)
341 |
342 | for j in range(data.shape[1]):
343 | u[k, j] = sum(data[ts == k, j] / sum(ts == k))
344 | v[k, j] = sum((data[ts == k, j] - u[k, j]) ** 2) / (sum(ts == k) - 1)
345 |
346 | w = zeros(data_num)
347 | for i in range(data_num):
348 | gamma = 1
349 |
350 | for j in range(data.shape[1]):
351 | k = ts[i]
352 | Dk = 1 / sqrt(2 * pi * v[k, j]) * exp(-(data[i, j] - u[k, j]) ** 2 / (2 * v[k, j]))
353 | Dt = 1 / sqrt(2 * pi * v[t, j]) * exp(-(data[i, j] - u[t, j]) ** 2 / (2 * v[t, j]))
354 | gamma *= Dk / Dt
355 |
356 | beta = 1 / (D[ts[i]] / D[t] * gamma)
357 | w[i] = 1 / (1 + exp(-(beta - 0.5)))
358 |
359 | w /= sum(w)
360 | return w
361 |
362 | def _learnH(self, data, label, ts):
363 |
364 | w = self._importance_sampling(data[label == 1], ts)
365 | model = UnderBagging(T=self.T, pos_weight=w, replace=True)
366 | model.train(data, label)
367 | self.ensemble.append(model)
368 |
369 | def _predict_base(self, test_data, prob_output=False):
370 |
371 | pred = zeros([test_data.shape[0], len(self.ensemble)])
372 | for i in range(len(self.ensemble)):
373 | if prob_output:
374 | pred[:, i] = self.ensemble[i].predict_proba(test_data[:, self.fea_comb[i]])[:, 1]
375 | else:
376 | pred[:, i] = self.ensemble[i].predict(test_data[:, self.fea_comb[i]])
377 |
378 | return pred
379 |
380 | def _update_chunk(self, data, label):
381 |
382 | pos_idx = label == 1
383 | neg_idx = label == -1
384 | pos_num = sum(pos_idx)
385 | neg_num = sum(neg_idx)
386 |
387 | self.chunk_count += 1
388 |
389 | self.stored_data.append(data)
390 | self.stored_label.append(label)
391 |
392 | if self.chunk_count > 1:
393 | self.pred = self._test(data, self.stored_data[self.chunk_count - 2])
394 | else:
395 | self.pred = zeros_like(label)
396 |
397 | self._train(data, label, delta=neg_num)
398 |
399 | def update(self, single_data, single_label):
400 |
401 | if self.buf_label.size < self.chunk_size:
402 | self.buf_data = r_[
403 | self.buf_data.reshape(-1, single_data.shape[0]), single_data.reshape(-1, single_data.shape[0])]
404 | self.buf_label = r_[self.buf_label, single_label]
405 | self.train_count += 1
406 |
407 | if self.buf_label.size == self.chunk_size or self.train_count == self.data_num:
408 | print('Data ' + str(self.train_count) + ' / ' + str(self.data_num))
409 | self._update_chunk(self.buf_data, self.buf_label)
410 | self.buf_data = array([])
411 | self.buf_label = array([])
412 |
413 | if len(self.pred) != 0:
414 | pred = self.pred
415 | self.pred = []
416 | else:
417 | pred = []
418 |
419 | return pred
420 |
421 |
422 | class LearnppNIE(ChunkBase):
423 |
424 | def __init__(self, data_num, chunk_size, T=5, a=0.5, b=10, err_func='gm'):
425 | ChunkBase.__init__(self)
426 |
427 | self.T = T
428 | self.data_num = data_num
429 | self.chunk_size = chunk_size
430 | self.a = a
431 | self.b = b
432 | self.err_func = err_func
433 | self.beta = array([[0.0]])
434 |
435 | def _update_chunk(self, data, label):
436 |
437 | model = UnderBagging(T=self.T, auto_r=True)
438 | model.train(data, label)
439 | self.ensemble.append(model)
440 | self.chunk_count += 1
441 | all_pred = sign(self._predict_base(data))
442 |
443 | if self.chunk_count > 1:
444 | pred = dot(all_pred[:, :-1], self.w)
445 | else:
446 | pred = zeros_like(label)
447 |
448 | pred = sign(pred)
449 |
450 | err = self.calculate_err(all_pred, label)
451 |
452 | if err[-1] > 0.5:
453 | model = UnderBagging(T=self.T, auto_r=True)
454 | model.train(data, label)
455 | self.ensemble[-1] = model
456 | all_pred = sign(self._predict_base(data))
457 | err = self.calculate_err(all_pred, label)
458 | if err[-1] > 0.5:
459 | err[-1] = 0.5
460 |
461 | err[err > 0.5] = 0.5
462 |
463 | if self.chunk_count == 1:
464 | self.beta[0, 0] = err / (1 - err)
465 | else:
466 | self.beta = pad(self.beta, ((0, 1), (0, 1)), 'constant', constant_values=(0))
467 | self.beta[:self.chunk_count, self.chunk_count - 1] = err / (1 - err)
468 |
469 | self.w = zeros(self.chunk_count)
470 | for k in range(self.chunk_count):
471 | omega = array(range(1, self.chunk_count - k + 1))
472 | omega = 1 / (1 + exp(-self.a * (omega - self.b)))
473 | omega /= sum(omega)
474 | beta_hat = sum(omega * self.beta[k, k:self.chunk_count])
475 | self.w[k] = log(1 / beta_hat)
476 |
477 | return pred
478 |
--------------------------------------------------------------------------------
/chunk_size_select.py:
--------------------------------------------------------------------------------
1 | from numpy import *
2 | import matplotlib.pyplot as plt
3 | import matplotlib.mlab as mlab
4 | from scipy.stats import f
5 | from scipy.stats import chi2
6 | from subunderbagging import *
7 | from check_measure import *
8 | from sklearn.model_selection import train_test_split
9 |
10 |
11 | class ChunkSizeBase:
12 |
13 | def __init__(self, fix_num, init_num=100):
14 | self.fix_num = fix_num
15 | self.init_num = init_num
16 | self.enough = 0
17 | self.chunk_data = array([])
18 | self.chunk_label = array([])
19 | self.chunk_count = zeros(2)
20 | self.round = 0
21 |
22 | def update(self, data, label):
23 | if self.enough == 1:
24 | self.chunk_data = array([])
25 | self.chunk_label = array([])
26 | self.enough = 0
27 | self.chunk_count = zeros(2)
28 |
29 | if label == 1:
30 | self.chunk_count[1] += 1
31 | else:
32 | self.chunk_count[0] += 1
33 | self.chunk_data = r_[self.chunk_data.reshape(-1, data.size), data.reshape(1, -1)]
34 | self.chunk_label = r_[self.chunk_label, label]
35 |
36 | self.check_condition()
37 |
38 | def get_enough(self):
39 | return self.enough
40 |
41 | def get_chunk(self):
42 | return self.chunk_data, self.chunk_label
43 |
44 |
45 | class ChunkSizeSelect(ChunkSizeBase):
46 |
47 | def __init__(self, chunk_min=100, min_min=5, P=250, T=100, Q=1000, nt=10, delta=0.05, init_num=100, k_mode=2,
48 | mute=1):
49 |
50 | self.chunk_min = chunk_min
51 | self.min_min = min_min
52 | self.P = P
53 | self.T = T
54 | self.Q = Q
55 | self.nt = nt
56 | self.alpha = delta
57 | self.init_num = init_num
58 | self.k_mode = k_mode
59 | self.mute = mute
60 |
61 | self.chunk_count = zeros(2)
62 | self.chunk_data = array([])
63 | self.chunk_label = array([])
64 | self.var_0 = []
65 | self.var_1 = []
66 | self.round = 0
67 | self.data_count = 0
68 | self.test_data = []
69 | self.enough = 0
70 | self.store_chunk_data = []
71 | self.store_chunk_label = []
72 | self.min_class = 0
73 |
74 | def update(self, data, label):
75 |
76 | if self.enough == 1:
77 | self.enough = 0
78 | self.store_chunk_data = self.chunk_data
79 | self.store_chunk_label = self.chunk_label
80 | self.chunk_data = array([])
81 | self.chunk_label = array([])
82 |
83 | if label == 1:
84 | self.chunk_count[1] += 1
85 | else:
86 | self.chunk_count[0] += 1
87 | self.chunk_data = r_[self.chunk_data.reshape(-1, data.size), data.reshape(1, -1)]
88 | self.chunk_label = r_[self.chunk_label, label]
89 |
90 | self.check_condition()
91 |
92 | def check_condition(self):
93 | self.data_count += 1
94 |
95 | if sum(self.chunk_label == 1) > sum(self.chunk_label == -1):
96 | self.min_class = -1
97 | else:
98 | self.min_class = 1
99 |
100 | if self.round == 0 and min(self.chunk_count) > 0 and sum(self.chunk_count) >= self.init_num:
101 | self.test_data = self.chunk_data[random.permutation(self.chunk_label.size)[:self.nt]]
102 | self.store_chunk_data = self.chunk_data
103 | self.store_chunk_label = self.chunk_label
104 | self.chunk_count = zeros(2)
105 | self.enough = 1
106 | self.round += 1
107 |
108 | elif min(self.chunk_count) >= self.min_min and sum(self.chunk_count) >= self.chunk_min:
109 |
110 | self.chunk_count = zeros(2)
111 | model = SubUnderBagging(Q=self.Q, T=self.T, k_mode=self.k_mode)
112 |
113 | if len(self.var_0) == 0:
114 | model.train(self.chunk_data, self.chunk_label)
115 | pred_result = model.predict(self.test_data[-self.nt:], self.P)
116 | self.var_0 = var(pred_result, 0)
117 | self.store_chunk_data = self.chunk_data
118 | self.store_chunk_label = self.chunk_label
119 | self.chunk_data = array([])
120 | self.chunk_label = array([])
121 | else:
122 | model.train(r_[self.store_chunk_data, self.chunk_data], r_[self.store_chunk_label, self.chunk_label])
123 | pred_result = model.predict(self.test_data[-self.nt:], self.P)
124 | self.var_1 = var(pred_result, 0)
125 | p = self.check_significance()
126 | if not self.mute:
127 | print('v0: %f / v1: %f' % (mean(self.var_0), mean(self.var_1)))
128 | print(p)
129 |
130 | if p < self.alpha:
131 | if not self.mute:
132 | print('Add more samples')
133 | self.var_0 = self.var_1
134 | self.store_chunk_data = r_[self.store_chunk_data, self.chunk_data]
135 | self.store_chunk_label = r_[self.store_chunk_label, self.chunk_label]
136 | self.chunk_data = array([])
137 | self.chunk_label = array([])
138 | else:
139 | if not self.mute:
140 | print('Enough samples')
141 | print('---------------------------------------------------------')
142 | self.test_data = r_[self.test_data, self.store_chunk_data[self.store_chunk_label == self.min_class]]
143 | model = SubUnderBagging(Q=self.Q, T=self.T, k_mode=self.k_mode)
144 | model.train(self.chunk_data, self.chunk_label)
145 | pred_result = model.predict(self.test_data[-self.nt:], self.P)
146 | self.var_0 = var(pred_result, 0)
147 | self.enough = 1
148 |
149 | self.round += 1
150 |
151 | def check_significance(self, n=100):
152 | f_p = []
153 | for i in range(self.nt):
154 | if self.var_1[i] != 0:
155 | f_p.append(1 - f.cdf(self.var_0[i] / self.var_1[i], n - 1, n - 1))
156 | f_p = [x for x in f_p if x != 0]
157 | K = -2 * sum(log(array(f_p)))
158 | chi2_p_value = 1 - chi2.cdf(K, 2 * len(f_p))
159 |
160 | return chi2_p_value
161 |
162 | def get_chunk(self):
163 | return self.store_chunk_data, self.store_chunk_label
164 |
165 | def get_chunk_2(self):
166 | return r_[self.store_chunk_data, self.chunk_data], r_[self.store_chunk_label, self.chunk_label]
167 |
168 |
169 | class FixMinorityChunkSizeSelect(ChunkSizeBase):
170 |
171 | def check_condition(self):
172 | if (self.round == 0 and min(self.chunk_count) > 0 and sum(self.chunk_count) >= self.init_num) or \
173 | (min(self.chunk_count) == self.fix_num):
174 | self.enough = 1
175 | self.round += 1
176 |
177 |
178 | class FixChunkSizeSelect(ChunkSizeBase):
179 |
180 | def check_condition(self):
181 |
182 | if sum(self.chunk_count) >= self.fix_num:
183 | if min(self.chunk_count) == 0:
184 | self.chunk_count = zeros(2)
185 | else:
186 | self.enough = 1
187 |
188 |
189 | class ADWIN(ChunkSizeBase):
190 |
191 | def __init__(self, delta=0.05, max_num=1000, init_num=100):
192 |
193 | self.enough = 0
194 | self.chunk_data = array([])
195 | self.chunk_label = array([])
196 | self.chunk_count = zeros(2)
197 | self.delta = delta
198 | self.max_num = max_num
199 | self.init_num = init_num
200 | self.round = 0
201 |
202 | def check_condition(self):
203 |
204 | if min(self.chunk_count) > 0:
205 | n = self.chunk_label.size
206 | if n >= self.max_num or (self.round == 0 and sum(self.chunk_count >= self.init_num)):
207 | self.enough = 1
208 | self.round += 1
209 | else:
210 | norm_data = (self.chunk_data - self.chunk_data.min(axis=0)) / (
211 | self.chunk_data.max(axis=0) - self.chunk_data.min(axis=0))
212 | for i in range(n - 1):
213 | mu_diff = abs(mean(norm_data[:i + 1], 0) - mean(norm_data[i + 1:], 0))
214 | m = 1 / (1 / (i + 1) + 1 / (n - i - 1))
215 | eps_cut = sqrt(1 / (2 * m) * log(4 / (self.delta / n)))
216 | if max(mu_diff) > eps_cut:
217 | self.enough = 1
218 | self.round += 1
219 | break
220 |
221 |
222 | class PERM(ChunkSizeBase):
223 |
224 | def __init__(self, P=100, delta=0.05, m=100, max_num=1000, init_num=100):
225 |
226 | self.enough = 0
227 | self.chunk_data = array([])
228 | self.chunk_label = array([])
229 | self.chunk_count = zeros(2)
230 | self.P = P
231 | self.delta = delta
232 | self.m = m
233 | self.max_num = max_num
234 | self.init_num = init_num
235 | self.store_chunk_data = array([])
236 | self.store_chunk_label = array([])
237 | self.round = 0
238 |
239 | def update(self, data, label):
240 |
241 | if self.enough == 1:
242 | self.enough = 0
243 | self.chunk_count = zeros(2)
244 | self.store_chunk_data = self.chunk_data
245 | self.store_chunk_label = self.chunk_label
246 | self.chunk_data = array([])
247 | self.chunk_label = array([])
248 |
249 | if label == 1:
250 | self.chunk_count[1] += 1
251 | else:
252 | self.chunk_count[0] += 1
253 | self.chunk_data = r_[self.chunk_data.reshape(-1, data.size), data.reshape(1, -1)]
254 | self.chunk_label = r_[self.chunk_label, label]
255 |
256 | self.check_condition()
257 |
258 | def check_condition(self):
259 |
260 | if self.round == 0 and min(self.chunk_count) > 1 and sum(self.chunk_count) >= self.init_num:
261 | self.enough = 1
262 | self.round += 1
263 | self.store_chunk_data = self.chunk_data
264 | self.store_chunk_label = self.chunk_label
265 | elif sum(self.chunk_count) >= self.m and min(self.chunk_count) > 1:
266 | self.chunk_count = zeros(2)
267 | if self.round == 1:
268 | self.store_chunk_data = self.chunk_data
269 | self.store_chunk_label = self.chunk_label
270 | self.chunk_data = array([])
271 | self.chunk_label = array([])
272 | else:
273 | if self.detect() or sum(self.store_chunk_label.size) >= self.max_num:
274 | print('enough')
275 | self.enough = 1
276 | else:
277 | print('not enough')
278 | self.store_chunk_data = r_[self.store_chunk_data, self.chunk_data]
279 | self.store_chunk_label = r_[self.store_chunk_label, self.chunk_label]
280 | self.chunk_data = array([])
281 | self.chunk_label = array([])
282 |
283 | self.round += 1
284 |
285 | def detect(self):
286 |
287 | m1 = self.store_chunk_label.size
288 | m2 = self.chunk_label.size
289 | model_ord = self.train(self.store_chunk_data, self.store_chunk_label)
290 | loss_ord = self.predict(model_ord, self.chunk_data, self.chunk_label)
291 |
292 | all_data = r_[self.store_chunk_data, self.chunk_data]
293 | all_label = r_[self.store_chunk_label, self.chunk_label]
294 | loss_perm = zeros(self.P)
295 |
296 | if sum(all_label == 1) < sum(all_label == -1):
297 | min_class = 1
298 | else:
299 | min_class = -1
300 |
301 | for i in range(self.P):
302 | X_train, X_test, y_train, y_test = train_test_split(all_data, all_label, test_size=m2 / (m2 + m1),
303 | stratify=all_label)
304 |
305 | if sum(y_train == min_class) == 0:
306 | temp_train = X_train[0]
307 | X_train[0] = X_test[nonzero(y_test == min_class)[0][0]]
308 | X_test[nonzero(y_test == min_class)[0][0]] = temp_train
309 | y_train[0] = min_class
310 | y_test[nonzero(y_test == min_class)[0][0]] = -min_class
311 |
312 | model_perm = self.train(X_train, y_train)
313 | loss_perm[i] = self.predict(model_perm, X_test, y_test)
314 |
315 | test_value = (1 + sum(loss_ord < loss_perm)) / (self.P + 1)
316 | if test_value < self.delta:
317 | return True
318 | else:
319 | return False
320 |
321 | @staticmethod
322 | def train(data, label):
323 |
324 | model = SubUnderBagging(Q=100, T=100)
325 | model.train(data, label)
326 |
327 | return model
328 |
329 | @staticmethod
330 | def predict(model, data, label):
331 |
332 | pred_result = model.predict(data, P=1)
333 | pred_result = sign(pred_result - 0.5)
334 | loss = 1 - gm_measure(pred_result, label)
335 |
336 | return loss
337 |
338 | def get_chunk(self):
339 | return self.store_chunk_data, self.store_chunk_label
340 |
341 | def get_chunk_2(self):
342 | return r_[self.store_chunk_data, self.chunk_data], r_[self.store_chunk_label, self.chunk_label]
343 |
--------------------------------------------------------------------------------
/data/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/.DS_Store
--------------------------------------------------------------------------------
/data/drifting_gaussian_abrupt.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/drifting_gaussian_abrupt.npz
--------------------------------------------------------------------------------
/data/drifting_gaussian_gradual.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/drifting_gaussian_gradual.npz
--------------------------------------------------------------------------------
/data/elec2_abrupt.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/elec2_abrupt.npz
--------------------------------------------------------------------------------
/data/elec2_gradual.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/elec2_gradual.npz
--------------------------------------------------------------------------------
/data/hyperP_abrupt.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/hyperP_abrupt.npz
--------------------------------------------------------------------------------
/data/hyperP_gradual.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/hyperP_gradual.npz
--------------------------------------------------------------------------------
/data/moving_gaussian_abrupt.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/moving_gaussian_abrupt.npz
--------------------------------------------------------------------------------
/data/moving_gaussian_gradual.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/moving_gaussian_gradual.npz
--------------------------------------------------------------------------------
/data/noaa_abrupt.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/noaa_abrupt.npz
--------------------------------------------------------------------------------
/data/noaa_gradual.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/noaa_gradual.npz
--------------------------------------------------------------------------------
/data/rotcb_abrupt.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/rotcb_abrupt.npz
--------------------------------------------------------------------------------
/data/rotcb_gradual.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/rotcb_gradual.npz
--------------------------------------------------------------------------------
/data/rotsp_abrupt.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/rotsp_abrupt.npz
--------------------------------------------------------------------------------
/data/rotsp_gradual.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/rotsp_gradual.npz
--------------------------------------------------------------------------------
/data/sea_abrupt.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/sea_abrupt.npz
--------------------------------------------------------------------------------
/data/sea_gradual.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jasonyanglu/ACDWM/08005b62919340c869056e7450f388503b61b245/data/sea_gradual.npz
--------------------------------------------------------------------------------
/dwmil.py:
--------------------------------------------------------------------------------
1 | # Implement DWMIL
2 | # By Yang Lu, 25/01/2018
3 |
4 | from numpy import *
5 | from subunderbagging import *
6 | from underbagging import *
7 | from sklearn.metrics import f1_score
8 | from check_measure import *
9 | from chunk_based_methods import ChunkBase
10 | from sklearn.model_selection import StratifiedKFold
11 | import pdb
12 |
13 |
14 | class DWMIL(ChunkBase):
15 |
16 | def __init__(self, data_num, chunk_size=1000, theta=0.1, err_func='gm', r=1):
17 | ChunkBase.__init__(self)
18 |
19 | self.data_num = data_num
20 | self.chunk_size = chunk_size
21 | self.theta = theta
22 | self.err_func = err_func
23 | self.r = r
24 |
25 | self.ensemble_size_record = array([])
26 |
27 | def _update_chunk(self, data, label):
28 | model = UnderBagging(r=self.r, auto_T=True)
29 | model.train(data, label)
30 | self.ensemble.append(model)
31 | self.chunk_count += 1
32 | self.w = append(self.w, 1)
33 | all_pred = sign(self._predict_base(data))
34 |
35 | if self.chunk_count > 1:
36 | pred = dot(all_pred[:, :-1], self.w[:-1])
37 | else:
38 | pred = zeros_like(label)
39 |
40 | pred = sign(pred)
41 | err = self.calculate_err(all_pred, label)
42 | self.w = (1 - err) * self.w
43 |
44 | remove_idx = nonzero(self.w < self.theta)[0]
45 | if len(remove_idx) != 0:
46 | for index in sorted(remove_idx, reverse=True):
47 | del self.ensemble[index]
48 | self.w = delete(self.w, remove_idx)
49 | self.chunk_count -= remove_idx.size
50 |
51 | self.ensemble_size_record = r_[self.ensemble_size_record, len(self.ensemble)]
52 |
53 | return pred
54 |
55 |
56 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | # ACDWM (Adaptive Chunk-based Dynamic Weighted Majority)
2 | # Example: python main.py sea_abrupt.npz
3 |
4 | from numpy import *
5 | from chunk_size_select import *
6 | from dwmil import *
7 | from chunk_based_methods import *
8 | from online_methods import *
9 | from check_measure import *
10 | import matplotlib.pyplot as plt
11 | import sys
12 |
13 | data_name = sys.argv[1]
14 |
15 | load_data = load('data/' + data_name)
16 | data = load_data['data']
17 | label = load_data['label']
18 | reset_pos = load_data['reset_pos'].astype(int)
19 |
20 | data_num = data.shape[0]
21 | chunk_size = 1000
22 |
23 | run_num = 1
24 |
25 | pq_result_acdwm = [{} for _ in range(run_num)]
26 |
27 | for run_i in range(run_num):
28 |
29 | acss = ChunkSizeSelect()
30 | model_acdwm = DWMIL(data_num=data_num, chunk_size=0)
31 | pred_acdwm = array([])
32 |
33 | print('Round ' + str(run_i))
34 | for i in range(data_num):
35 | acss.update(data[i], label[i])
36 | if i == data_num - 1:
37 | chunk_data, chunk_label = acss.get_chunk_2()
38 | pred_acdwm = append(pred_acdwm, model_acdwm.predict(chunk_data))
39 | elif acss.get_enough() == 1:
40 | chunk_data, chunk_label = acss.get_chunk()
41 | pred_acdwm = append(pred_acdwm, model_acdwm.update_chunk(chunk_data, chunk_label))
42 |
43 | pq_result_acdwm[run_i] = prequential_measure(pred_acdwm, label, reset_pos)
44 |
45 | print('acdwm: %f' % mean([pq_result_acdwm[i]['gm'][-1] for i in range(run_num)]))
46 |
--------------------------------------------------------------------------------
/main_compare.py:
--------------------------------------------------------------------------------
1 | # Compare ACDWM with other online learning methods
2 | # Example: python main_compare.py sea_abrupt.npz
3 |
4 | from numpy import *
5 | from chunk_size_select import *
6 | from dwmil import *
7 | from chunk_based_methods import *
8 | from online_methods import *
9 | from check_measure import *
10 | import matplotlib.pyplot as plt
11 | import sys
12 |
13 | data_name = sys.argv[1]
14 |
15 | load_data = load('data/' + data_name)
16 | data = load_data['data']
17 | label = load_data['label']
18 | reset_pos = load_data['reset_pos'].astype(int)
19 |
20 | data_num = data.shape[0]
21 | chunk_size = 1000
22 |
23 | run_num = 1
24 |
25 | pq_result_ub = [{} for _ in range(run_num)]
26 | pq_result_rea = [{} for _ in range(run_num)]
27 | pq_result_dwmil = [{} for _ in range(run_num)]
28 | pq_result_acdwm = [{} for _ in range(run_num)]
29 | pq_result_learnpp_nie = [{} for _ in range(run_num)]
30 | pq_result_dfgw_is = [{} for _ in range(run_num)]
31 | pq_result_oob = [{} for _ in range(run_num)]
32 | pq_result_ddm_oci = [{} for _ in range(run_num)]
33 | pq_result_hlfr = [{} for _ in range(run_num)]
34 | pq_result_pauc_ph = [{} for _ in range(run_num)]
35 |
36 | for run_i in range(run_num):
37 |
38 | acss = ChunkSizeSelect()
39 |
40 | model_ub = UB(data_num=data_num, chunk_size=chunk_size)
41 | model_rea = REA(data_num=data_num, chunk_size=chunk_size)
42 | model_dwmil = DWMIL(data_num=data_num, chunk_size=chunk_size)
43 | model_acdwm = DWMIL(data_num=data_num, chunk_size=0)
44 | model_learnpp_nie = LearnppNIE(data_num=data_num, chunk_size=chunk_size)
45 | model_dfgw_is = DFGWIS(fea_num=data.shape[1], data_num=data_num, chunk_size=chunk_size)
46 | model_oob = OOB(silence=False)
47 | model_ddm_oci = DDM_OCI()
48 | model_hlfr = HLFR()
49 | model_pauc_ph = PAUC_PH()
50 |
51 | pred_ub = array([])
52 | pred_rea = array([])
53 | pred_dwmil = array([])
54 | pred_acdwm = array([])
55 | pred_learnpp_nie = array([])
56 | pred_dfgw_is = array([])
57 | pred_oob = array([])
58 | pred_ddm_oci = array([])
59 | pred_hlfr = array([])
60 | pred_pauc_ph = array([])
61 |
62 | print('Round ' + str(run_i))
63 | for i in range(data_num):
64 |
65 | pred_ub = append(pred_ub, model_ub.update(data[i], label[i]))
66 | pred_rea = append(pred_rea, model_rea.update(data[i], label[i]))
67 |
68 | pred_dwmil = append(pred_dwmil, model_dwmil.update(data[i], label[i]))
69 | pred_learnpp_nie = append(pred_learnpp_nie, model_learnpp_nie.update(data[i], label[i]))
70 | pred_dfgw_is = append(pred_dfgw_is, model_dfgw_is.update(data[i], label[i]))
71 |
72 | pred_oob = append(pred_oob, model_oob.update(data[i], label[i]))
73 | pred_ddm_oci = append(pred_ddm_oci, model_ddm_oci.update(data[i], label[i]))
74 | pred_hlfr = append(pred_hlfr, model_hlfr.update(data[i], label[i]))
75 | pred_pauc_ph = append(pred_pauc_ph, model_pauc_ph.update(data[i], label[i]))
76 |
77 | # acdwm
78 | acss.update(data[i], label[i])
79 | if i == data_num - 1:
80 | chunk_data, chunk_label = acss.get_chunk_2()
81 | pred_acdwm = append(pred_acdwm, model_acdwm.predict(chunk_data))
82 | elif acss.get_enough() == 1:
83 | chunk_data, chunk_label = acss.get_chunk()
84 | pred_acdwm = append(pred_acdwm, model_acdwm.update_chunk(chunk_data, chunk_label))
85 |
86 | pq_result_ub[run_i] = prequential_measure(pred_ub, label, reset_pos)
87 | pq_result_rea[run_i] = prequential_measure(pred_rea, label, reset_pos)
88 | pq_result_dwmil[run_i] = prequential_measure(pred_dwmil, label, reset_pos)
89 | pq_result_acdwm[run_i] = prequential_measure(pred_acdwm, label, reset_pos)
90 | pq_result_learnpp_nie[run_i] = prequential_measure(pred_learnpp_nie, label, reset_pos)
91 | pq_result_dfgw_is[run_i] = prequential_measure(pred_dfgw_is, label, reset_pos)
92 | pq_result_oob[run_i] = prequential_measure(pred_oob, label, reset_pos)
93 | pq_result_ddm_oci[run_i] = prequential_measure(pred_ddm_oci, label, reset_pos)
94 | pq_result_hlfr[run_i] = prequential_measure(pred_hlfr, label, reset_pos)
95 | pq_result_pauc_ph[run_i] = prequential_measure(pred_pauc_ph, label, reset_pos)
96 |
97 |
98 | print('ub: %f' % mean([pq_result_ub[i]['gm'][-1] for i in range(run_num)]))
99 | print('rea: %f' % mean([pq_result_rea[i]['gm'][-1] for i in range(run_num)]))
100 | print('learnpp_nie: %f' % mean([pq_result_learnpp_nie[i]['gm'][-1] for i in range(run_num)]))
101 | print('dfgw_is: %f' % mean([pq_result_dfgw_is[i]['gm'][-1] for i in range(run_num)]))
102 | print('oob: %f' % mean([pq_result_oob[i]['gm'][-1] for i in range(run_num)]))
103 | print('ddm_oci: %f' % mean([pq_result_ddm_oci[i]['gm'][-1] for i in range(run_num)]))
104 | print('hlfr: %f' % mean([pq_result_hlfr[i]['gm'][-1] for i in range(run_num)]))
105 | print('pauc_ph: %f' % mean([pq_result_pauc_ph[i]['gm'][-1] for i in range(run_num)]))
106 | print('dwmil: %f' % mean([pq_result_dwmil[i]['gm'][-1] for i in range(run_num)]))
107 | print('acdwm: %f' % mean([pq_result_acdwm[i]['gm'][-1] for i in range(run_num)]))
108 |
--------------------------------------------------------------------------------
/online_methods.py:
--------------------------------------------------------------------------------
1 | from underbagging import *
2 | from HoeffdingTree.hoeffdingtree import HoeffdingTree
3 | from HoeffdingTree.core.attribute import Attribute
4 | from HoeffdingTree.core.dataset import Dataset
5 | from HoeffdingTree.core.instance import Instance
6 | from scipy.stats.mstats import mquantiles
7 | from queue import Queue
8 | from sklearn.model_selection import train_test_split
9 | import time
10 |
11 | import abc
12 |
13 |
14 | class OnlineBase:
15 |
16 | @abc.abstractmethod
17 | def update(self, data, label):
18 | pass
19 |
20 |
21 | class DDM_OCI(OnlineBase):
22 |
23 | def __init__(self, decay_factor=0.9):
24 |
25 | self.decay_factor = decay_factor
26 |
27 | self.oob_model = OOB()
28 | self.pos_rec = 0
29 | self.neg_rec = 0
30 | self.stored_data = array([])
31 | self.stored_label = array([])
32 | self.warning = False
33 | self.p = array([])
34 | self.s = array([])
35 | self.ddm_n = 0
36 | self.train_count = 0
37 |
38 | def update(self, data, label):
39 |
40 | if self.train_count % 1000 == 0:
41 | print('Data ' + str(self.train_count))
42 |
43 | # store data since warning is issued
44 | if self.warning:
45 | self.stored_data = r_[self.stored_data.reshape(-1, data.size), data.reshape(1, -1)]
46 | self.stored_label = r_[self.stored_label, label]
47 |
48 | # update and predict
49 | pred = self.oob_model.update(data, label)
50 | self.ddm_n += 1
51 | self.train_count += 1
52 |
53 | # trace minority class recall and detect drift
54 | if label == 1:
55 | self.pos_rec = self.decay_factor * self.pos_rec + (1 - self.decay_factor) * (pred == label)
56 | else:
57 | self.neg_rec = self.decay_factor * self.neg_rec + (1 - self.decay_factor) * (pred == label)
58 |
59 | min_class = self.oob_model.get_minority_class()
60 | if min_class == -1:
61 | self.p = append(self.p, self.neg_rec)
62 | else:
63 | self.p = append(self.p, self.pos_rec)
64 | self.s = append(self.s, sqrt(self.p[-1] * (1 - self.p[-1]) / self.ddm_n))
65 | p_max = max(self.p)
66 | s_max = max(self.s)
67 |
68 | if self.p[-1] - self.s[-1] < p_max - 2 * s_max and self.warning == False:
69 | self.warning = True
70 | # print('Warning!')
71 | elif self.p[-1] - self.s[-1] < p_max - 3 * s_max and self.warning == True:
72 | # reset model
73 | # print('Drift detected!')
74 | self.oob_model = OOB()
75 | self.pos_rec = 0
76 | self.neg_rec = 0
77 | self.warning = False
78 | self.p = array([])
79 | self.s = array([])
80 | self.ddm_n = 0
81 | for i in range(self.stored_data.shape[0]):
82 | self.oob_model.update(self.stored_data[i], self.stored_label[i])
83 | self.stored_data = array([])
84 | self.stored_label = array([])
85 |
86 | return pred
87 |
88 |
89 | class HLFR(OnlineBase):
90 |
91 | def __init__(self, decay_factor=0.9, warn_sig=0.01, detect_sig=0.0001, perm_sig=0.05, W=100, P=100):
92 |
93 | self.decay_factor = decay_factor
94 | self.warn_sig = warn_sig
95 | self.detect_sig = detect_sig
96 | self.perm_sig = perm_sig
97 | self.W = W
98 | self.P = P
99 |
100 | self.rate_name = ['tpr', 'tnr', 'ppv', 'npv']
101 |
102 | self.oob_model = OOB()
103 | self.stored_data = array([])
104 | self.stored_label = array([])
105 | self.warning = False
106 | self.R = {n: 0 for n in self.rate_name}
107 | self.C = ones([2, 2])
108 | self.window_data = Queue(2 * W)
109 | self.window_label = Queue(2 * W)
110 | self.pot_count = -1
111 | self.train_count = 0
112 | self.stored_decay = array([])
113 |
114 | def update(self, data, label):
115 |
116 | if self.train_count % 1000 == 0:
117 | print('Data ' + str(self.train_count))
118 |
119 | # store data since warning is issued
120 | if self.warning:
121 | self.stored_data = r_[self.stored_data.reshape(-1, data.size), data.reshape(1, -1)]
122 | self.stored_label = r_[self.stored_label, label]
123 | if self.window_data.full():
124 | self.window_data.get()
125 | self.window_label.get()
126 | self.window_data.put(data)
127 | self.window_label.put(label)
128 |
129 | # permutation test
130 | if self.pot_count != -1:
131 | pred = sign(self.oob_model.predict(data))
132 |
133 | if self.pot_count == self.window_data.qsize():
134 | window_data = array(self.window_data.queue)
135 | window_label = array(self.window_label.queue)
136 | if not self._permutation_test(window_data, window_label):
137 | print('Level II detected at %d !' % self.train_count)
138 | self.oob_model = OOB()
139 |
140 | for i in range(self.W):
141 | self.oob_model.update(window_data[self.W + i], window_label[self.W + i])
142 | self.pot_count = -1
143 | else:
144 | self.pot_count += 1
145 |
146 | else:
147 | # update and predict
148 | pred = self.oob_model.update(data, label)
149 |
150 | # trace four rates and detect drift
151 | self.C[int(pred / 2 + 0.5), int(label / 2 + 0.5)] = self.C[int(pred / 2 + 0.5), int(label / 2 + 0.5)] + 1
152 |
153 | warn_bd = {n: 0 for n in self.rate_name}
154 | detect_bd = {n: 0 for n in self.rate_name}
155 | time_a = time.time()
156 | for rate in self.rate_name:
157 | if (rate == 'tpr' and label == 1) or (rate == 'tnr' and label == -1) or \
158 | (rate == 'ppv' and pred == 1) or (rate == 'npv' and pred == -1):
159 | self.R[rate] = self.decay_factor * self.R[rate] + (1 - self.decay_factor) * (pred == label)
160 |
161 | if rate in ['tpr', 'tnr']:
162 | N = self.C[0, int(rate == 'tpr')] + self.C[1, int(rate == 'tpr')]
163 | P = self.C[int(rate == 'tpr'), int(rate == 'tpr')] / N
164 | else:
165 | N = self.C[int(rate == 'ppv'), 0] + self.C[int(rate == 'ppv'), 1]
166 | P = self.C[int(rate == 'ppv'), int(rate == 'ppv')] / N
167 |
168 | warn_bd[rate] = self._bound_table(P, self.warn_sig, int(N))
169 | detect_bd[rate] = self._bound_table(P, self.detect_sig, int(N))
170 |
171 | if (sum([self.R[rate] > warn_bd[rate][1] for rate in self.rate_name]) > 0 or \
172 | sum([self.R[rate] < warn_bd[rate][0] for rate in self.rate_name]) > 0) and \
173 | not self.warning:
174 | print('Warning at %d !' % self.train_count)
175 | self.warning = True
176 | elif sum([self.R[rate] > warn_bd[rate][1] for rate in self.rate_name]) == 0 and \
177 | sum([self.R[rate] < warn_bd[rate][0] for rate in self.rate_name]) == 0 and \
178 | self.warning:
179 | print('Warning cancel at %d !' % self.train_count)
180 | self.warning = False
181 | self.stored_data = array([])
182 | self.stored_label = array([])
183 |
184 | if (sum([self.R[rate] > detect_bd[rate][1] for rate in self.rate_name]) > 0 or \
185 | sum([self.R[rate] < detect_bd[rate][0] for rate in self.rate_name]) > 0) and \
186 | len(self.stored_label) > 0:
187 | # reset model
188 | print('Level I detected at %d !' % self.train_count)
189 | self.oob_model = OOB()
190 | self.warning = False
191 | self.R = {n: 0 for n in self.rate_name}
192 | self.C = ones([2, 2])
193 |
194 | for i in range(self.stored_data.shape[0]):
195 | self.oob_model.update(self.stored_data[i], self.stored_label[i])
196 | self.stored_data = array([])
197 | self.stored_label = array([])
198 | self.pot_count = 0
199 |
200 | self.train_count += 1
201 |
202 | return pred
203 |
204 | def _bound_table(self, P, alpha, N, MC=100):
205 |
206 | if len(self.stored_decay) < N:
207 | for i in range(len(self.stored_decay), N):
208 | self.stored_decay = append(self.stored_decay, self.decay_factor ** i)
209 | R = zeros(MC)
210 | for i in range(MC):
211 | bin_rand_num = random.binomial(1, P, N)
212 | R[i] = (1 - self.decay_factor) * sum(bin_rand_num * self.stored_decay[:N])
213 |
214 | bd = zeros(2)
215 | bd[0] = mquantiles(R, alpha)
216 | bd[1] = mquantiles(R, 1 - alpha)
217 |
218 | return bd
219 |
220 | def _permutation_test(self, data, label):
221 |
222 | model_ord = OOB()
223 | for i in range(self.W):
224 | model_ord.update(data[i], label[i])
225 | pred_ord = sign(model_ord.predict(data[self.W:]))
226 | loss_ord = sum(pred_ord != label[self.W:])
227 |
228 | loss_perm = zeros(self.P)
229 | # print('Permutation test')
230 | for p in range(self.P):
231 | try:
232 | X_train, X_test, y_train, y_test = train_test_split(data, label,
233 | test_size=0.5, stratify=label)
234 | except ValueError:
235 | return False
236 | model_perm = OOB()
237 | for _ in range(self.W):
238 | model_perm.update(X_train[i], y_train[i])
239 | pred_perm = sign(model_ord.predict(X_test))
240 | loss_perm[p] = sum(pred_ord != y_test)
241 |
242 | test_value = (1 + sum(loss_ord < loss_perm)) / (self.P + 1)
243 | if test_value < self.perm_sig:
244 | return True
245 | else:
246 | return False
247 |
248 |
249 | class PAUC_PH(OnlineBase):
250 |
251 | def __init__(self, window_size=1000, ph_delta=0.1, ph_lambda=100):
252 |
253 | self.window_size = window_size
254 | self.ph_delta = ph_delta
255 | self.ph_lambda = ph_lambda
256 |
257 | self.oob_model = OOB(prob=True)
258 | self.W_score = array([])
259 | self.W_label = array([])
260 | self.m = array([])
261 | self.auc = array([])
262 |
263 | self.train_count = 0
264 | self.crt_count = 0
265 | self.n = 0
266 | self.p = 0
267 |
268 | def update(self, data, label):
269 |
270 | if self.train_count % 1000 == 0:
271 | print('Data ' + str(self.train_count))
272 |
273 | # update and predict
274 | score = self.oob_model.update(data, label)
275 | self.train_count += 1
276 | self.crt_count += 1
277 |
278 | auc = self._prequential_auc(score, label)
279 | self.auc = r_[self.auc, auc]
280 |
281 | if self._ph_test(auc) == True:
282 | # print('Drift detected at %d !' % self.train_count)
283 |
284 | self.oob_model = OOB(prob=True)
285 | self.W_score = array([])
286 | self.W_label = array([])
287 | self.m = array([])
288 | self.auc = array([])
289 |
290 | self.crt_count = 0
291 | self.n = 0
292 | self.p = 0
293 |
294 | return sign(score)
295 |
296 | def _prequential_auc(self, score, label):
297 |
298 | if self.crt_count > self.window_size:
299 | del_idx = (self.crt_count - 1) % self.window_size
300 | self.W_score = delete(self.W_score, del_idx)
301 | if self.W_label[del_idx] == 1:
302 | self.p -= 1
303 | else:
304 | self.n -= 1
305 | self.W_label = delete(self.W_label, del_idx)
306 |
307 | self.W_score = r_[self.W_score, score]
308 | self.W_label = r_[self.W_label, label]
309 |
310 | if label == 1:
311 | self.p += 1
312 | else:
313 | self.n += 1
314 |
315 | sort_idx = argsort(-self.W_score)
316 | self.W_score = self.W_score[sort_idx]
317 | self.W_label = self.W_label[sort_idx]
318 |
319 | AUC = 0
320 | c = 0
321 | for i in range(self.W_score.size):
322 | if self.W_label[i] == 1:
323 | c += 1
324 | else:
325 | AUC += c
326 | if self.p * self.n != 0:
327 | return AUC / (self.p * self.n)
328 | else:
329 | return 0
330 |
331 | def _ph_test(self, auc):
332 |
333 | temp = (1 - self.auc) - mean(1 - self.auc) - self.ph_delta
334 | m_t = sum(temp[temp > 0])
335 | self.m = r_[self.m, m_t]
336 | if abs(m_t - min(self.m)) > self.ph_lambda:
337 | return True
338 | else:
339 | return False
340 |
341 |
342 | class OOB():
343 |
344 | def __init__(self, T=11, theta=0.9, prob=False, silence=True):
345 |
346 | self.T = T
347 | self.theta = theta
348 | self.prob = prob
349 | self.silence = silence
350 |
351 | # Hoeffding tree ensemble init
352 | self.ensemble = list()
353 | for t in range(self.T):
354 | vfdt = HoeffdingTree()
355 | vfdt.set_grace_period(50)
356 | vfdt.set_hoeffding_tie_threshold(0.05)
357 | vfdt.set_split_confidence(0.0001)
358 | vfdt.set_minimum_fraction_of_weight_info_gain(0.01)
359 | self.ensemble.append(vfdt)
360 |
361 | self.train_count = 0
362 | self.w = array([0.5, 0.5])
363 |
364 | def _init_dataset(self, data, label):
365 |
366 | fea_num = data.size
367 | attributes = []
368 | for i in range(fea_num):
369 | attributes.append(Attribute(str(i), att_type='Numeric'))
370 | attributes.append(Attribute('Label', ['-1', '1'], att_type='Nominal'))
371 |
372 | self.dataset = Dataset(attributes, fea_num)
373 |
374 | inst_values = list(r_[data, label])
375 | inst_values[fea_num] = int(attributes[fea_num].index_of_value(str(int(label))))
376 | self.dataset.add(Instance(att_values=inst_values))
377 |
378 | for t in range(self.T):
379 | self.ensemble[t].build_classifier(self.dataset)
380 |
381 | def update(self, data, label):
382 |
383 | fea_num = data.size
384 | if self.train_count % 1000 == 0 and self.silence == False:
385 | print('Data ' + str(self.train_count))
386 |
387 | # format sample and predict
388 | if self.train_count == 0:
389 | pred = 0
390 | else:
391 | inst_values = list(r_[data, label])
392 | inst_values[fea_num] = int(self.dataset.attribute(index=fea_num).index_of_value(str(int(label))))
393 | new_instance = Instance(att_values=inst_values)
394 | new_instance.set_dataset(self.dataset)
395 | pred = self._predict(new_instance)
396 |
397 | # update prob
398 | self.w[0] = self.theta * self.w[0] + (1 - self.theta) * (label == -1)
399 | self.w[1] = self.theta * self.w[1] + (1 - self.theta) * (label == 1)
400 |
401 | # calculate sampling rate
402 | if label == 1 and self.w[1] < self.w[0]:
403 | sampling_rate = self.w[0] / self.w[1]
404 | elif label == -1 and self.w[1] > self.w[0]:
405 | sampling_rate = self.w[1] / self.w[0]
406 | else:
407 | sampling_rate = 1
408 |
409 | # incrementally train Hoeffding tree
410 | if self.train_count == 0:
411 | self._init_dataset(data, label)
412 | else:
413 | for t in range(self.T):
414 | K = random.poisson(sampling_rate)
415 | for _ in range(K):
416 | self.ensemble[t].update_classifier(new_instance)
417 |
418 | self.train_count += 1
419 |
420 | if self.prob:
421 | return pred
422 | else:
423 | return sign(pred)
424 |
425 | def _predict(self, data):
426 |
427 | pred = zeros([self.T])
428 | for t in range(self.T):
429 | pred[t] = self.ensemble[t].distribution_for_instance(data)[1]
430 | pred[t] = (pred[t] - 0.5) * 2
431 |
432 | return mean(pred)
433 |
434 | def predict(self, data):
435 |
436 | if len(data.shape) == 1:
437 | data = data.reshape(1, data.size)
438 | fea_num = data.size
439 | data_num = data.shape[0]
440 | fea_num = data.shape[1]
441 | pred = zeros([self.T, data_num])
442 |
443 | for t in range(self.T):
444 | for i in range(data_num):
445 | inst_values = list(r_[data[i], 1])
446 | inst_values[fea_num] = int(self.dataset.attribute(index=fea_num).index_of_value(str(1)))
447 | new_instance = Instance(att_values=inst_values)
448 | new_instance.set_dataset(self.dataset)
449 | pred[t, i] = self.ensemble[t].distribution_for_instance(new_instance)[1]
450 | pred[t, i] = (pred[t, i] - 0.5) * 2
451 |
452 | return mean(pred, 0)
453 |
454 | def get_minority_class(self):
455 |
456 | if self.w[0] < self.w[1]:
457 | return -1
458 | else:
459 | return 1
460 |
--------------------------------------------------------------------------------
/requirments.txt:
--------------------------------------------------------------------------------
1 | cvxpy==0.4.9
2 | matplotlib==3.1.0
3 | numpy==1.16.4
4 | scikit-learn==0.21.2
5 | scipy==1.2.1
--------------------------------------------------------------------------------
/subunderbagging.py:
--------------------------------------------------------------------------------
1 | from numpy import *
2 | from sklearn import tree
3 | from sklearn.tree import DecisionTreeClassifier
4 |
5 |
6 | class SubUnderBagging:
7 |
8 | def __init__(self, Q=1000, T=100, k_mode=2):
9 | self.Q = Q
10 | self.T = T
11 | self.k_mode = k_mode
12 |
13 | self.model = list()
14 |
15 | def train(self, data, label):
16 | data_num = label.size
17 | neg_num = sum(label == -1)
18 | pos_num = sum(label == 1)
19 | neg_idx = nonzero(label == -1)[0]
20 | pos_idx = nonzero(label == 1)[0]
21 |
22 | # k = int(sqrt(min(neg_num, pos_num)))
23 | k = int(sqrt(data_num))
24 |
25 | for j in range(self.Q):
26 |
27 | all_pos_idx = pos_idx
28 | random.shuffle(all_pos_idx)
29 | all_neg_idx = neg_idx
30 | random.shuffle(all_neg_idx)
31 | all_idx = array(range(data_num))
32 | random.shuffle(all_idx)
33 |
34 | # compare k and class size
35 | if self.k_mode == 1:
36 | if k / 2 < min(pos_num, neg_num):
37 | sampling_idx = r_[all_neg_idx[:int(k / 2)], all_pos_idx[:int(k / 2)]]
38 | else:
39 | if neg_num > pos_num:
40 | sampling_idx = r_[all_neg_idx[:k - pos_num], all_pos_idx]
41 | else:
42 | sampling_idx = r_[all_neg_idx, all_pos_idx[:k - neg_num]]
43 | elif self.k_mode == 2:
44 | if neg_num > pos_num:
45 | sampling_idx = r_[all_neg_idx[:k], all_pos_idx]
46 | else:
47 | sampling_idx = r_[all_neg_idx, all_pos_idx[:k]]
48 |
49 | sampling_data = data[sampling_idx]
50 | sampling_label = label[sampling_idx]
51 |
52 | self.model.append(DecisionTreeClassifier(max_depth=1))
53 | self.model[j] = self.model[j].fit(sampling_data, sampling_label)
54 |
55 | def predict(self, test_data, P):
56 | test_num = test_data.shape[0]
57 | temp_result = zeros([P, self.T, test_num])
58 | all_pred = zeros([self.Q, test_num])
59 |
60 | for i_Q in range(self.Q):
61 | all_pred[i_Q, :] = self.model[i_Q].predict_proba(test_data)[:, 1]
62 |
63 | for i_P in range(P):
64 | rand_idx = random.permutation(self.Q)
65 | temp_result[i_P, :, :] = all_pred[rand_idx[:self.T], :]
66 |
67 | pred_result = mean(temp_result, 1)
68 |
69 | return pred_result
70 |
--------------------------------------------------------------------------------
/underbagging.py:
--------------------------------------------------------------------------------
1 | from numpy import *
2 | from sklearn import tree
3 | from sklearn.tree import DecisionTreeClassifier
4 | import math
5 |
6 |
7 | class UnderBagging:
8 |
9 | def __init__(self, T=11, r=1.0, sampling_class=0, pos_weight=[], neg_weight=[],
10 | replace=False, auto_T=False, auto_r=False):
11 | # sampling_class is 0 for undersampling the majority class
12 |
13 | self.T = T
14 | self.r = r
15 | self.sampling_class = sampling_class
16 | self.pos_weight = pos_weight
17 | self.neg_weight = neg_weight
18 | self.replace = replace
19 | self.auto_T = auto_T
20 | self.auto_r = auto_r
21 | self.model = list()
22 |
23 | def train(self, data, label):
24 |
25 | data_num = label.size
26 | neg_num = sum(label == -1)
27 | pos_num = sum(label == 1)
28 | neg_idx = nonzero(label == -1)[0]
29 | pos_idx = nonzero(label == 1)[0]
30 |
31 | if len(self.pos_weight) == 0:
32 | self.pos_weight = ones(pos_num) / pos_num
33 | if len(self.neg_weight) == 0:
34 | self.neg_weight = ones(neg_num) / neg_num
35 |
36 | if (neg_num > pos_num and self.sampling_class == 0) or self.sampling_class == -1:
37 | if self.auto_r:
38 | neg_sampling_num = math.ceil(neg_num / self.T)
39 | else:
40 | neg_sampling_num = math.ceil(pos_num / self.r)
41 | pos_sampling_num = pos_num
42 |
43 | else:
44 | if self.auto_r:
45 | pos_sampling_num = math.ceil(pos_num / self.T)
46 | else:
47 | pos_sampling_num = math.ceil(neg_num / self.r)
48 | neg_sampling_num = neg_num
49 |
50 | if self.auto_T:
51 | T = int(maximum(math.ceil(maximum(pos_num, neg_num) / minimum(pos_num, neg_num) * self.r), self.T))
52 | if T % 2 == 0:
53 | T += 1
54 | else:
55 | T = self.T
56 |
57 | for j in range(T):
58 |
59 | if neg_num != 0 and pos_num != 0:
60 |
61 | all_pos_idx = pos_idx
62 | random.shuffle(all_pos_idx)
63 | all_neg_idx = neg_idx
64 | random.shuffle(all_neg_idx)
65 |
66 | if self.replace:
67 | sampling_idx = r_[all_neg_idx[random.choice(neg_num, neg_sampling_num, p=self.neg_weight)],
68 | all_pos_idx[random.choice(pos_num, pos_sampling_num, p=self.pos_weight)]]
69 | else:
70 | sampling_idx = r_[all_neg_idx[:neg_sampling_num], all_pos_idx[:pos_sampling_num]]
71 |
72 | sampling_data = data[sampling_idx]
73 | sampling_label = label[sampling_idx]
74 |
75 | self.model.append(DecisionTreeClassifier())
76 | self.model[j] = self.model[j].fit(sampling_data, sampling_label)
77 |
78 | else:
79 | self.model.append([])
80 |
81 | def predict(self, test_data):
82 | test_num = test_data.shape[0]
83 | temp_result = zeros([len(self.model), test_num])
84 |
85 | for i in range(len(self.model)):
86 | if self.model[i] != []:
87 | temp_result[i, :] = self.model[i].predict(test_data)
88 | else:
89 | temp_result[i, :] = zeros(test_num)
90 |
91 | pred_result = mean(temp_result, 0)
92 |
93 | return pred_result
94 |
--------------------------------------------------------------------------------