├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── README_ko.md ├── assets └── merge_similar_clusters.png ├── description.py ├── setup.py ├── soyclustering ├── __init__.py ├── _keyword.py ├── _kmeans.py ├── _postprocess.py ├── _spherical_kmeans_core.pyx ├── _utils.py └── _visualize.py ├── tests └── test_kmeans.py └── tutorial.ipynb /.gitattributes: -------------------------------------------------------------------------------- 1 | tutorial* linguist-vendored 2 | 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # MacOS 2 | .DS_Store 3 | 4 | # Python 5 | .pyc 6 | __pycache__/ 7 | dist/ 8 | build/ 9 | *.egg-info/ 10 | 11 | # Experiments 12 | tmp/ 13 | 14 | # Jupyter notebook 15 | .ipynb_checkpoints/ 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # soyclustering: Python clustering algorithm library for document clustering 2 | 3 | This package is implementation of **Improving spherical k-means for document clustering: Fast initialization, sparse centroid projection, and efficient cluster labeling** (Kim et al., 2020). 4 | 5 | Cosine is more effective than Euclidean when measuring the distance between two high-dimensional (or sometimes, sparse) documents vectors. 6 | However, scikit-learn k-means package provides only Euclidean based k-means. 7 | Additionally, labeling clusters can be very helpful for interpreting the clustering results. 8 | 9 | Spherical k-means works well both with sparse vector representation such as Bag-of-Words model or distributed representation such as Doc2Vec or other document embedding methods. 10 | In lower dimensional vector space, Silhouette score method is useful to define the number of clusters (`k`). 11 | However Silhouette score method does not work well in a high-dimensional vector space such as Bag-of-Words and Doc2Vec model space. 12 | One of the heuristic methods to define the number of clusters is to train k-means with large `k` first and subsequently merge similar ones. 13 | This method is also useful for preventing the Uniform Effect, which causes the size of all clusters to be similar. 14 | 15 | `soyclustering` provides Spherical k-means (k-means which uses Cosine distance as a distance metric) and keyword extraction-based clustering labeling function. 16 | Furthermore, the function for visualizing pairwise distances between centroids will help you to check whether redundant clusters exist, allowing you to remove redundant clusters by merging them. 17 | `soyclustering` also provides a fast initialization method that is effective in a high-dimensional vector space. 18 | When the size of the input data is large, the initialization method sets k to be 1000. 19 | The below table decsribes relative speed-up of proposed initialization method with alpha=3 compared to kmeans++ (x times faster) 20 | 21 | | Dataset name | num rows | num features | num of nonzero (percent) | k=10 | k=20 | k=50 | k=100 | 22 | | --- | --- | --- | --- | --- | --- | --- | --- | 23 | | A6 blogs | 63,153 | 91,302 | 18,051,341 (0.313 %)| x 265 | x 257 | x 213 | x 150 | 24 | | Tucson blogs | 105,755 | 81,497 | 29,192,999 (0.339 %) | x 388 | x 440 | x 306 | x 244 | 25 | | Sonata blogs | 229,253 | 85,129 | 60,861,803 (0.312 \$) | x 785 | x 841 | x 614 | x 495 | 26 | | IMDb reviews | 1,228,348 | 68,049 | 181,411,713 (0.217 %) | x 803 | x 714 | x 1988 | x 1787 | 27 | | Reuter RCV1 | 804,414 | 47,236 | 60,915,113 (0.160 %) | x 439 | x 713 | x 850 | x 772 | 28 | | MovieLens 20M | 138,493 | 131,262 | 20,000,263 (0.110 %) | x 202 | x 213 | x 214 | x 184 | 29 | | Yelp reviews | 5,261,669 | 27,247 | 365,341,887 (0.255 %) | x 368 | x 908 | x 1508 | x 2917 | 30 | 31 | 32 | ## Install 33 | 34 | Using pip 35 | 36 | ``` 37 | pip install soyclustering 38 | ``` 39 | 40 | 41 | ## Usage 42 | 43 | You can read a matrix market file as follows. Note that the file must include tokenized outputs. Although the spherical k-means function can be used for inputs in distributed representation such as Doc2Vec, our cluster labeling algorithm works only for Bag-of-Words model. 44 | 45 | ```python 46 | from scipy.io import mmread 47 | x = mmread(mm_file).tocsr() 48 | ``` 49 | 50 | Sperical k-means can be used as follows. init='similar_cut' indicates our initializer that is effective in a high-dimensional vector space. If you want to preserve the sparsity of the centroid vector, you can set minimum_df_factor. Other interfaces are similar to those of scikit-learn k-means function. With fit_predict, you can retrieve the labels from the clustering result. 51 | 52 | ```python 53 | from soyclustering import SphericalKMeans 54 | spherical_kmeans = SphericalKMeans( 55 | n_clusters=1000, 56 | max_iter=10, 57 | verbose=1, 58 | init='similar_cut', 59 | sparsity='minimum_df', 60 | minimum_df_factor=0.05 61 | ) 62 | 63 | labels = spherical_kmeans.fit_predict(x) 64 | ``` 65 | 66 | When the verbose mode is set, computation speed and the level of sparsity during the initizalition and each iteration is printed. 67 | 68 | ``` 69 | initialization_time=1.218108 sec, sparsity=0.00796 70 | n_iter=1, changed=29969, inertia=15323.440, iter_time=4.435 sec, sparsity=0.116 71 | n_iter=2, changed=5062, inertia=11127.620, iter_time=4.466 sec, sparsity=0.108 72 | n_iter=3, changed=2179, inertia=10675.314, iter_time=4.463 sec, sparsity=0.105 73 | n_iter=4, changed=1040, inertia=10491.637, iter_time=4.449 sec, sparsity=0.103 74 | n_iter=5, changed=487, inertia=10423.503, iter_time=4.437 sec, sparsity=0.103 75 | n_iter=6, changed=297, inertia=10392.490, iter_time=4.483 sec, sparsity=0.102 76 | n_iter=7, changed=178, inertia=10373.646, iter_time=4.442 sec, sparsity=0.102 77 | n_iter=8, changed=119, inertia=10362.625, iter_time=4.449 sec, sparsity=0.102 78 | n_iter=9, changed=78, inertia=10355.905, iter_time=4.438 sec, sparsity=0.102 79 | n_iter=10, changed=80, inertia=10350.703, iter_time=4.452 sec, sparsity=0.102 80 | ``` 81 | 82 | Cluster labeling can be used to intrepret the clustering results. The `proportion_keywords` function of `soyclustering` uses a keyword extraction-based method to return keywords describing each cluster. For its input arguments, you need to provide cluster centroid vectors, a list of vocabularies (as str) and labels. 83 | 84 | ```python 85 | from soyclustering import proportion_keywords 86 | 87 | centers = spherical_kmeans.cluster_centers_ 88 | idx2vocab = ['list', 'of', 'str', 'vocab'] 89 | keywords = proportion_keywords(centers, labels, index2word=idx2vocab) 90 | ``` 91 | 92 | The table in below is the results of cluster labels from a trained k-means with k=1,000 and 1.2M documents. 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 |
The meaning of cluster
(Human label)
Algorithm based extracted clustering labels
The movie “Titanic" iceberg, zane, sinking, titanic, rose, winslet, camerons, 1997, leonardo, leo, ship, cameron, dicaprio, kate, tragedy, jack, di saster, james, romance, love, effects, special, story, people, best, ever, made
Heros in Marvle comics (Avengers) zemo, chadwick, boseman, bucky, panther, holland, cap, infinity, mcu, russo, civil, bvs, antman, winter, ultron, airport, ave ngers, marvel, captain, superheroes, soldier, stark, evans, america, iron, spiderman, downey, tony, superhero, heroes
Alien movies such as Cover-field or District 9 skyline, jarrod, balfour, strause, invasion, independence, cloverfield, angeles, district, los, worlds, aliens, alien, la, budget, scifi, battle, cgi, day, effects, war, special, ending, bad, better, why, they, characters, their, people
Horror movies gayheart, loretta, candyman, legends, urban, witt, campus, tara, reid, legend, alicia, englund, leto, rebecca, jared, scream, murders, slasher, helen, killer, student, college, students, teen, summer, cut, horror, final, sequel, scary
The movie “The Matrix" neo, morpheus, neos, oracle, trinity, zion, architect, hacker, reloaded, revolutions, wachowski, fishburne, machines, agents, matrix, keanu, smith, reeves, agent, jesus, machine, computer, humans, fighting, fight, world, cool, real, special, effects
128 | 129 | Setting a large `k` leads to redundant clusters. You can identify these redundant clusters by carefully examining the pairwise distance between the clusters. 130 | 131 | ```python 132 | from soyclustering import visualize_pairwise_distance 133 | 134 | # visualize pairwise distance matrix 135 | fig = visualize_pairwise_distance(centers, max_dist=.7, sort=True) 136 | ``` 137 | 138 | If you find redundant clusters, you can easily merge them into a single cluster. 139 | 140 | ```python 141 | from soyclustering import merge_close_clusters 142 | 143 | group_centers, groups = merge_close_clusters(centers, labels, max_dist=.5) 144 | fig = visualize_pairwise_distance(group_centers, max_dist=.7, sort=True) 145 | ``` 146 | 147 | After merging, you can check the size of dark squares in the diagonal entries of the pairwise distance matrix. If the redundant clusters are indeed successfully merged, the number of dark sqaures in the diagonal entries should have been reduced. 148 | 149 | ![](https://github.com/lovit/clustering4docs/blob/master/assets/merge_similar_clusters.png) 150 | 151 | The function `merge_close_clusters` groups similar clusters, in which the distance between them is smaller than `max_dist`. 152 | The centroid of the new cluster is a weighted average of original centroid vectors. 153 | From the variable `groups`, you can return the cluster indices prior and after merging. 154 | 155 | ```python 156 | for group in groups: 157 | print(group) 158 | ``` 159 | 160 | ``` 161 | [0, 19, 57, 68, 88, 115, 202, 223, 229, 237] 162 | [1] 163 | [2] 164 | [3, 4, 5, 8, 12, 14, 16, 18, 20, 22, 26, 28, ...] 165 | [6, 25, 29, 32, 37, 43, 45, 48, 53, 56, 65, ...] 166 | [7, 17, 34, 41, 52, 59, 76, 79, 84, 87, 93, ...] 167 | [9, 15, 24, 47, 51, 97] 168 | [10, 100, 139] 169 | [11, 23, 251] 170 | ... 171 | ``` 172 | 173 | ## See more 174 | 175 | In addition, the repository [`kmeans_to_pyLDAvis`](https://github.com/lovit/kmeans_to_pyLDAvis) provides k-means visualization using `PyLDAVis` 176 | 177 | ## References 178 | 179 | - Kim, H., Kim, H. K., & Cho, S. (2020). Improving spherical k-means for document clustering: Fast initialization, sparse centroid projection, and efficient cluster labeling. Expert Systems with Applications, 150, 113288. 180 | -------------------------------------------------------------------------------- /README_ko.md: -------------------------------------------------------------------------------- 1 | # soyclustering: Python clustering algorithm library for document clustering 2 | 3 | 문서 군집화를 위해서는 Euclidean distance 가 아닌 Cosine distance 를 이용하는 Spherical k-means 를 이용해야 합니다. 그러나 scikit-learn 의 sklearn.cluster.KMeans 는 Spherical k-means 를 제공하지 않습니다. 또한 문서 군집화 결과를 해석하기 위하여 각 클러스터의 레이블을 달아야 합니다. 4 | 5 | soyclustering 은 문서 군집화를 위한 spherical k-means 알고리즘과 centroid 기반 cluster labeling algorithm 을 제공합니다. 6 | 7 | Spherical k-means 는 bag-of-words model 과 같은 sparse vector 와 Doc2Vec 과 같은 distribted repsentation 모두에서 잘 작동합니다. 하지만, cluster labeling 은 sparse vector 로 표현된 centroid vectors 를 기준으로 작동합니다. 8 | 9 | 또한 k-means 계열 군집화 알고리즘을 이용할 때 사용자는 적절한 k 를 결정해야 합니다. Silhouette score 와 같은 방법이 있지만, 이는 저차원 벡터 공간의 군집화에 적합하며, bag-of-words model 이나 distributed representation 과 같은 고차원 공간에서는 적합한 방법이 아닙니다. Uniform effect 와 같은 현상을 피할 수 있는 현실적인 방법은 예상하는 것보다 더 많은 군집의 수를 k 로 설정한 뒤, 비슷한 군집을 하나의 군집으로 후처리 과정에서 묶는 것입니다. 10 | 11 | soyclustering 은 이를 위해 centroid vectors 의 pairwise distance matrix 를 시각화 함으로써, 현재 군집화의 결과에 중복 군집은 없는지 살펴보며, 비슷한 군집들을 하나의 군집으로 묶는 후처리 과정을 제공합니다. 12 | 13 | 그리고 k-means 의 initializer 로 이용되는 k-means++ 은 역시 저차원 벡터 공간에서 작동하는 알고리즘입니다. 고차원 공간에서는 매우 느린 initialization 성능을 보이기 때문에 soyclustering 은 이를 개선하는 fast initializer 를 제공합니다. 14 | 15 | ## Usage 16 | 17 | 토크나이징이 되어 있는 matrix market 형식의 파일을 읽습니다. Doc2Vec 과 같은 distributed representation 에 대해서도 spherical k-means 는 작동하지만, cluster labeling algorithm 은 bag-of-words model 에서만 작동합니다. 18 | 19 | ```python 20 | from scipy.io import mmread 21 | x = mmread(mm_file).tocsr() 22 | ``` 23 | 24 | 구현된 spherical k-means 는 아래처럼 이용할 수 있습니다. init='similar_cut' 은 고차원 벡터에서 효율적으로 작동하는 initializer 입니다. 또한 centroid 의 sparsity 를 유지하기 위해 minimum_df 방법을 이용할 수 있습니다. 그 외의 interface 는 scikit-learn 의 k-means 와 동일합니다. fit_predict 를 통하여 군집화 결과의 labels 를 얻을 수 있습니다. 25 | 26 | ```python 27 | from soyclustering import SphericalKMeans 28 | spherical_kmeans = SphericalKMeans( 29 | n_clusters=1000, 30 | max_iter=10, 31 | verbose=1, 32 | init='similar_cut', 33 | sparsity='minimum_df', 34 | minimum_df_factor=0.05 35 | ) 36 | 37 | labels = spherical_kmeans.fit_predict(x) 38 | ``` 39 | 40 | Verbose mode 일 때에는 initialization 과 매 iteration 에서의 계산 시간과 centroid vectors 의 sparsity 가 출력됩니다. 41 | 42 | ``` 43 | initialization_time=1.218108 sec, sparsity=0.00796 44 | n_iter=1, changed=29969, inertia=15323.440, iter_time=4.435 sec, sparsity=0.116 45 | n_iter=2, changed=5062, inertia=11127.620, iter_time=4.466 sec, sparsity=0.108 46 | n_iter=3, changed=2179, inertia=10675.314, iter_time=4.463 sec, sparsity=0.105 47 | n_iter=4, changed=1040, inertia=10491.637, iter_time=4.449 sec, sparsity=0.103 48 | n_iter=5, changed=487, inertia=10423.503, iter_time=4.437 sec, sparsity=0.103 49 | n_iter=6, changed=297, inertia=10392.490, iter_time=4.483 sec, sparsity=0.102 50 | n_iter=7, changed=178, inertia=10373.646, iter_time=4.442 sec, sparsity=0.102 51 | n_iter=8, changed=119, inertia=10362.625, iter_time=4.449 sec, sparsity=0.102 52 | n_iter=9, changed=78, inertia=10355.905, iter_time=4.438 sec, sparsity=0.102 53 | n_iter=10, changed=80, inertia=10350.703, iter_time=4.452 sec, sparsity=0.102 54 | ``` 55 | 56 | 군집화 결과의 해석을 위하여 cluster labeling 을 수행합니다. soyclustering 이 제공하는 proportion keywords 함수는 keyword extraction 방법에 기반하여 각 군집의 키워드를 추출합니다. input arguments 로 군집화 결과 얻는 cluster centroid vectors 와 list of str 형식으로 이뤄진 vocab list 가 필요합니다. 또한 각 군집의 크기를 측정할 수 있는 labels 를 입력해야 합니다. 57 | 58 | ```python 59 | from soyclustering import proportion_keywords 60 | 61 | centers = spherical_kmeans.cluster_centers_ 62 | idx2vocab = ['list', 'of', 'str', 'vocab'] 63 | keywords = proportion_keywords(centers, labels, index2word=idx2vocab) 64 | ``` 65 | 66 | 1,226k 개의 문서로 이뤄진 IMDB reviews 에 대하여 k=1000 으로 설정하여 spherical k-means 를 학습한 뒤, 위의 proportion keywords 함수를 이용하여 군집 레이블을 추출하였습니다. 아래는 5 개 군집의 예시입니다. 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 |
군집의 의미키워드 (레이블)
영화 “타이타닉” iceberg, zane, sinking, titanic, rose, winslet, camerons, 1997, leonardo, leo, ship, cameron, dicaprio, kate, tragedy, jack, di saster, james, romance, love, effects, special, story, people, best, ever, made
Marvle comics 의 heros (Avengers) zemo, chadwick, boseman, bucky, panther, holland, cap, infinity, mcu, russo, civil, bvs, antman, winter, ultron, airport, ave ngers, marvel, captain, superheroes, soldier, stark, evans, america, iron, spiderman, downey, tony, superhero, heroes
Cover-field, District 9 등 외계인 관련 영화 skyline, jarrod, balfour, strause, invasion, independence, cloverfield, angeles, district, los, worlds, aliens, alien, la, budget, scifi, battle, cgi, day, effects, war, special, ending, bad, better, why, they, characters, their, people
살인자가 출연하는 공포 영화 gayheart, loretta, candyman, legends, urban, witt, campus, tara, reid, legend, alicia, englund, leto, rebecca, jared, scream, murders, slasher, helen, killer, student, college, students, teen, summer, cut, horror, final, sequel, scary
영화 “매트릭스" neo, morpheus, neos, oracle, trinity, zion, architect, hacker, reloaded, revolutions, wachowski, fishburne, machines, agents, matrix, keanu, smith, reeves, agent, jesus, machine, computer, humans, fighting, fight, world, cool, real, special, effects
102 | 103 | 예상하는 것보다 큰 k 를 설정하면 몇 개의 군집들은 비슷한 centroid vectors 를 지닙니다. 이러한 군집이 존재하는지 확인하기 위해서는 pairwise distance matrix 를 살펴봐야 합니다. 104 | 105 | ```python 106 | from soyclustering import visualize_pairwise_distance 107 | 108 | # visualize pairwise distance matrix 109 | fig = visualize_pairwise_distance(centers, max_dist=.7, sort=True) 110 | ``` 111 | 112 | 그리고 비슷한 군집들이 있다면 이를 하나의 군집으로 묶을 수 있습니다. 113 | 114 | ```python 115 | from soyclustering import merge_close_clusters 116 | 117 | group_centers, groups = merge_close_clusters(centers, labels, max_dist=.5) 118 | fig = visualize_pairwise_distance(group_centers, max_dist=.7, sort=True) 119 | ``` 120 | 121 | 그 뒤 다시 groups 된 centroid vectors 를 살펴보면 아래의 그림과 같습니다. diagonal elements 만 진한 색이 띈다면 각각의 군집이 서로 상이하다는 의미입니다. 122 | 123 | ![](https://github.com/lovit/clustering4docs/blob/master/assets/merge_similar_clusters.png) 124 | 125 | merge_close_clusters 함수는 centroids 가 주어지면 Cosine distance 가 최대 max_dist 를 넘지 않는 군집들을 하나의 그룹으로 묶습니다. group centroid vectors 는 원 군집의 크기 (labels) 에 비례한 weighted average of centroids 로 계산됩니다. 126 | 127 | groups 는 각 군집이 어떤 그룹으로 묶였는지 nested list 로 표현됩니다. 128 | 129 | ```python 130 | for group in groups: 131 | print(group) 132 | ``` 133 | 134 | ``` 135 | [0, 19, 57, 68, 88, 115, 202, 223, 229, 237] 136 | [1] 137 | [2] 138 | [3, 4, 5, 8, 12, 14, 16, 18, 20, 22, 26, 28, ...] 139 | [6, 25, 29, 32, 37, 43, 45, 48, 53, 56, 65, ...] 140 | [7, 17, 34, 41, 52, 59, 76, 79, 84, 87, 93, ...] 141 | [9, 15, 24, 47, 51, 97] 142 | [10, 100, 139] 143 | [11, 23, 251] 144 | ... 145 | ``` 146 | 147 | ## See more 148 | 149 | pyLDAvis 를 이용하면 군집화 결과를 시각적으로 해석할 수 있습니다. 이에 관련한 코드는 다음의 github 에서 제공합니다. [kmeans_to_pyLDAvis](https://github.com/lovit/kmeans_to_pyLDAvis) 150 | -------------------------------------------------------------------------------- /assets/merge_similar_clusters.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lovit/clustering4docs/684649a1719913a4f41b3fc2c9ada82233c273fa/assets/merge_similar_clusters.png -------------------------------------------------------------------------------- /description.py: -------------------------------------------------------------------------------- 1 | __title__ = 'soyclustering' 2 | __version__ = '0.0.1' 3 | __author__ = 'Lovit' 4 | __license__ = 'GPL v3' 5 | __copyright__ = 'Copyright 2017 Lovit' -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import soyclustering 2 | from setuptools import setup, find_packages 3 | 4 | with open('README.md', encoding='utf-8') as f: 5 | long_description = f.read() 6 | 7 | setup( 8 | name="soyclustering", 9 | version=soyclustering.__version__, 10 | author=soyclustering.__author__, 11 | author_email='soy.lovit@gmail.com', 12 | url='https://github.com/lovit/clustering4docs', 13 | description="Python library for document clustering", 14 | long_description=long_description, 15 | long_description_content_type="text/markdown", 16 | install_requires=["numpy>=1.1"], 17 | keywords = ['document clustering', 'clustering labeling'], 18 | packages=find_packages() 19 | ) 20 | -------------------------------------------------------------------------------- /soyclustering/__init__.py: -------------------------------------------------------------------------------- 1 | __title__ = 'soyclustering' 2 | __version__ = '0.2.0' 3 | __author__ = 'Lovit' 4 | __license__ = 'GPL v3' 5 | __copyright__ = 'Copyright 2017 Lovit' 6 | 7 | from ._kmeans import SphericalKMeans 8 | from ._keyword import proportion_keywords 9 | from ._postprocess import merge_close_clusters 10 | from ._visualize import visualize_pairwise_distance 11 | from ._visualize import pairwise_distance_to_matplotlib_figure 12 | -------------------------------------------------------------------------------- /soyclustering/_keyword.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def proportion_keywords(centers, labels=None, min_score=0.5, topk=200, 5 | candidates_topk=300, index2word=None, stopwords=None): 6 | """ 7 | Arguments 8 | --------- 9 | centers : numpy.ndarray 10 | Shape = (k, p) 11 | k : num of clusters 12 | p : num of features 13 | labels : numpy.ndarray or None 14 | Shape = (n,) 15 | n : num of documents in the dataset 16 | It is used as cluster size weight. If the value is None, 17 | it assumes that all size of clusters are equal. 18 | min_score : float 19 | 0 < min_score < 1 20 | Minimum keyword score. The words corresponding less than the score will be 21 | removed from set of keywords. 22 | topk : int 23 | The number of keywords 24 | candidates_topk : int 25 | The number of keyword candidates 26 | index2word : list of str or None 27 | If the value is not None, the length must be p (num of features) 28 | If the value is None, it returns keywords as integer index 29 | stopwords : set of str or None 30 | The set of words that will be removed from keyword set by force 31 | 32 | Returns 33 | ------- 34 | keywords_in_clusters : nested list 35 | The length of list equals with num of clusters 36 | [[(keyword, score), (keyword, score), ... ], 37 | [(keyword, score), (keyword, score), ... ] 38 | ... 39 | ] 40 | """ 41 | 42 | def l1_normalize(x): return x/x.sum() 43 | 44 | password_as_idx = stopwords and isinstance(list(stopwords)[0], int) 45 | 46 | n_clusters, n_features = centers.shape 47 | total_frequency = np.zeros(n_features) 48 | 49 | if labels is not None: 50 | n_samples_in_cluster = np.bincount(labels, minlength=n_clusters) 51 | else: 52 | n_samples_in_cluster = np.asarray([1] * n_clusters) 53 | 54 | for c, n_docs in enumerate(n_samples_in_cluster): 55 | total_frequency += (centers[c] * n_docs) 56 | total_sum = total_frequency.sum() 57 | 58 | keywords = [] 59 | for c, n_docs in enumerate(n_samples_in_cluster): 60 | if n_docs == 0: 61 | keywords.append([]) 62 | continue 63 | 64 | n_prop = l1_normalize(total_frequency - (centers[c] * n_docs)) 65 | p_prop = l1_normalize(centers[c]) 66 | 67 | indices = np.where(p_prop > 0)[0] 68 | indices = sorted(indices, key=lambda idx: - 69 | p_prop[idx])[:candidates_topk] 70 | keywords_c = [(idx, p_prop[idx] / (p_prop[idx] + n_prop[idx])) 71 | for idx in indices] 72 | keywords_c= [t for t in keywords_c if t[1] >= min_score] 73 | keywords_c = sorted(keywords_c, key=lambda x: -x[1]) 74 | 75 | if stopwords and password_as_idx: 76 | keywords_c = [t for t in keywords_c if t[0] not in stopwords] 77 | 78 | if index2word is not None: 79 | keywords_c = [(index2word[idx], score) for idx, score in keywords_c] 80 | if stopwords and not password_as_idx: 81 | keywords_c = [t for t in keywords_c if t[0] not in stopwords] 82 | 83 | keywords.append(keywords_c) 84 | 85 | 86 | if topk > 0: 87 | keywords = [keyword[:topk] for keyword in keywords] 88 | 89 | return keywords 90 | -------------------------------------------------------------------------------- /soyclustering/_kmeans.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import os 3 | import numpy as np 4 | import scipy.sparse as sp 5 | import time 6 | 7 | from sklearn.metrics.pairwise import cosine_distances 8 | from sklearn.metrics import pairwise_distances_argmin_min 9 | from sklearn.preprocessing import normalize 10 | from sklearn.utils.extmath import stable_cumsum 11 | from sklearn.utils import check_random_state 12 | from sklearn.utils import check_array 13 | from sklearn.utils import as_float_array 14 | 15 | from ._utils import inner_product 16 | from ._utils import check_sparsity 17 | 18 | 19 | class SphericalKMeans: 20 | """Spherical k-Means clustering 21 | 22 | Parameters 23 | ---------- 24 | n_clusters : int, optional, default: 8 25 | The number of clusters to form as well as the number of centroids to generate. 26 | init : str or numpy.ndarray, default: 'similar_cut' 27 | One of ['similar_cut', 'k-means++', 'random'] or an numpy.ndarray 28 | Method for initialization, defaults to 'k-means++' 29 | - 'similar_cut' 30 | It is an k-means initialization method for high-dimensional vector space + Cosine. 31 | See `Improving spherical k-means for document clustering (Kim et al., 2020)` for detail. 32 | - 'k-means++' 33 | It selects initial cluster centers for k-mean clustering in a smart way to speed up convergence. 34 | See https://en.wikipedia.org/wiki/K-means%2B%2B for detail. 35 | - 'random' 36 | choose k observations (rows) at random from data for the initial centroids. 37 | - If an ndarray is passed, it should be of shape (n_clusters, n_features) and gives the initial centers. 38 | sparsity: str or None, default: None 39 | One of ['sculley', 'minimum_df', None] 40 | Method for preserving sparsity of centroids. 41 | 'sculley': L1 ball projection method. 42 | Reference: David Sculley. Web-scale k-means clustering. 43 | In Proceedings of international conference on World wide web,2010. 44 | It requires two parameters `radius` and `epsilon`. 45 | `radius`: default 10 46 | `epsilon`: default 5 47 | 'minium_df': Pruning method. It drops elements to zero which lower 48 | than beta / |DF(C)|. DF(C) is the document number of a cluster and 49 | beta is constant parameter. 50 | It requires one parameter `minimum_df_factor` a.k.a beta 51 | `minimum_df_factor`: default 0.01 52 | max_iter : int, default: 10 53 | Maximum number of iterations of the k-means algorithm for a single run. 54 | It does not need large number. k-means algorithms converge fast. 55 | tol : float, default: 1e-4 56 | Relative tolerance with regards to inertia to declare convergence 57 | verbose : int, default 0 58 | Verbosity mode. 59 | random_state : int, RandomState instance or None, optional, default: None 60 | If int, random_state is the seed used by the random number generator; 61 | If RandomState instance, random_state is the random number generator; 62 | If None, the random number generator is the RandomState instance used 63 | by `numpy.random`. 64 | debug_directory: str, default: None 65 | When debug_directory is not None, model save three informations. 66 | First one is logs. It contains iteration time, loss, and sparsity. 67 | Second one is temporal cluster labels for all iterations. Third one 68 | is temporal cluster centroid vector for all iterations. 69 | algorithm : str, default None 70 | Computation algorithm. 71 | Ignored 72 | max_similar: float, default: 0.5 73 | 'similar_cut initializer' argument. The initializer select a point randomly, 74 | and then remove points within distance <= `max_similar` from candidates of 75 | next centroid. It works only when you set `init`='similar_cut'. 76 | alpha: float, default: 3.0 77 | 'similar_cut initializer' argument. |candidates of initial centroids| / `n_clusters` 78 | It works only when you set `init`='similar_cut'. 79 | `alpha` must be larger than 1.0 80 | radius: float, default: 10.0 81 | 'sculley L1 projection' argument. It works only when you set `sparsity`='sculley' 82 | epsilon: float, default: 5.0 83 | 'sculley L1 projection' argument. It works only when you set `sparsity`='sculley' 84 | minimum_df_factor: float, default: 0.01 85 | 'minimum df L1 projection' argument. It works only when you set `sparsity`='minimum_df' 86 | `minimum_df_factor` must be real number between (0, 1) 87 | 88 | Attributes 89 | ---------- 90 | cluster_centers_ : array, [n_clusters, n_features] 91 | Coordinates of cluster centers 92 | labels_ : 93 | Labels of each point 94 | inertia_ : float 95 | Sum of squared distances of samples to their closest cluster center. 96 | 97 | Examples 98 | -------- 99 | >>> from soyclustering import SphericalKMeans 100 | >>> from scipy.io import mmread 101 | >>> x = mmread(mm_file).tocsr() 102 | >>> spherical_kmeans = SphericalKMeans(n_clusters=100, random_state=0) 103 | >>> labels = spherical_kmeans.fit_predict(X) 104 | >>> spherical_kmeans.cluster_centers_ 105 | 106 | See also 107 | -------- 108 | To be described. 109 | 110 | Notes 111 | ------ 112 | The k-means problem is solved using Lloyd's algorithm. 113 | The average complexity is given by O(k n T), were n is the number of 114 | samples and T is the number of iteration. 115 | In practice, the k-means algorithm is very fast (one of the fastest 116 | clustering algorithms available), but it falls in local minima. 117 | However, the probability of facing local minima is low if we use 118 | enough large k for document clustering. 119 | """ 120 | 121 | def __init__(self, n_clusters=8, init='similar_cut', sparsity=None, 122 | max_iter=10, tol=0.0001, verbose=0, random_state=None, 123 | debug_directory=None, algorithm=None, max_similar=0.5, 124 | alpha=3, radius=10.0, epsilon=5.0, minimum_df_factor=0.01): 125 | 126 | self.n_clusters = n_clusters 127 | self.init = init 128 | self.sparsity = sparsity 129 | self.max_iter = max_iter 130 | self.tol = tol 131 | self.verbose = verbose 132 | self.random_state = random_state 133 | self.debug_directory = debug_directory 134 | self.algorithm = algorithm 135 | 136 | # similar-cut initialization 137 | self.max_similar = max_similar 138 | self.alpha = alpha 139 | 140 | # sculley L1 projection 141 | self.radius = radius 142 | self.epsilon = epsilon 143 | 144 | # minimum df L1 projection 145 | self.minimum_df_factor = minimum_df_factor 146 | 147 | def _check_fit_data(self, X): 148 | """Verify that the number of samples given is larger than k 149 | Verify input data x is sparse matrix 150 | """ 151 | X = check_array(X, accept_sparse='csr', dtype=[np.float64, np.float32]) 152 | if X.shape[0] < self.n_clusters: 153 | raise ValueError("n_samples=%d should be >= n_clusters=%d" % ( 154 | X.shape[0], self.n_clusters)) 155 | if not sp.issparse(X): 156 | raise ValueError( 157 | "Input must be instance of scipy.sparse.csr_matrix") 158 | return X 159 | 160 | def fit(self, X, y=None): 161 | """Compute k-means clustering. 162 | 163 | Parameters 164 | ---------- 165 | X : scipy.sparse.csr_matrix, shape=(n_samples, n_features) 166 | Training instances 167 | y : Ignored 168 | """ 169 | X = self._check_fit_data(X) 170 | 171 | self.cluster_centers_, self.labels_, self.inertia_, = \ 172 | k_means( 173 | X, n_clusters=self.n_clusters, init=self.init, 174 | sparsity=self.sparsity, max_iter=self.max_iter, 175 | verbose=self.verbose, tol=self.tol, random_state=self.random_state, 176 | debug_directory=self.debug_directory, algorithm=self.algorithm, 177 | max_similar=self.max_similar, alpha=self.alpha, radius=self.radius, 178 | epsilon=self.epsilon, minimum_df_factor=self.minimum_df_factor 179 | ) 180 | return self 181 | 182 | def fit_predict(self, X, y=None): 183 | """Compute cluster centers and predict cluster index for each sample. 184 | 185 | Convenience method; equivalent to calling `fit(X)` followed by `predict(X)`. 186 | 187 | Parameters 188 | ---------- 189 | X : scipy.sparse.csr_matrix, shape = (n_samples, n_features) 190 | New data to be assigned to the closest cluster. 191 | y : Ignored 192 | 193 | Returns 194 | ------- 195 | labels : array, shape = (n_samples,) 196 | Index of the cluster each sample belongs to. 197 | """ 198 | return self.fit(X).labels_ 199 | 200 | def transform(self, X): 201 | """Transform X to a cluster-distance space. 202 | In the new space, each dimension is the distance to the cluster centers. 203 | Note that even if X is sparse, the array returned by `transform` will typically be dense. 204 | 205 | Parameters 206 | ---------- 207 | X : scipy.sparse.csr_matrix 208 | shape = (n_samples, n_features) 209 | New data to be transformed to cluster center-distance matrix. 210 | 211 | Returns 212 | ------- 213 | D : numpy.ndarray 214 | shape = (n_samples, k) 215 | D[doc_idx, cluster_idx] = distance(doc_idx, cluster_idx) 216 | """ 217 | if not hasattr(self, 'cluster_centers_'): 218 | raise RuntimeError( 219 | '`transform` function needs centroid vectors. Train SphericalKMeans first.') 220 | 221 | X = self._check_fit_data(X) 222 | return self._transform(X) 223 | 224 | def _transform(self, X): 225 | """guts of transform method; no input validation""" 226 | return cosine_distances(X, self.cluster_centers_) 227 | 228 | 229 | def _tolerance(X, tol): 230 | """The minimum number of points which are re-assigned to other cluster.""" 231 | return max(1, int(X.shape[0] * tol)) 232 | 233 | 234 | def k_means(X, n_clusters, init='similar_cut', sparsity=None, max_iter=10, 235 | verbose=False, tol=1e-4, random_state=None, debug_directory=None, 236 | algorithm=None, max_similar=0.5, alpha=3, radius=10.0, 237 | epsilon=5.0, minimum_df_factor=0.01): 238 | 239 | if max_iter <= 0: 240 | raise ValueError('Number of iterations should be a positive number,' 241 | ' got %d instead' % max_iter) 242 | 243 | X = as_float_array(X) 244 | tol = _tolerance(X, tol) 245 | 246 | labels, inertia, centers, debug_header = None, None, None, None 247 | 248 | if debug_directory: 249 | # Create debug header 250 | strf_now = datetime.datetime.now() 251 | debug_header = str(strf_now).replace( 252 | ':', '-').replace(' ', '_').split('.')[0] 253 | 254 | # Check debug_directory 255 | if not os.path.exists(debug_directory): 256 | os.makedirs(debug_directory) 257 | 258 | # For a single thread, run a k-means once 259 | centers, labels, inertia, n_iter_ = kmeans_single( 260 | X, n_clusters, max_iter=max_iter, init=init, sparsity=sparsity, 261 | verbose=verbose, tol=tol, random_state=random_state, 262 | debug_directory=debug_directory, debug_header=debug_header, 263 | algorithm=algorithm, max_similar=max_similar, alpha=alpha, 264 | radius=radius, epsilon=epsilon, minimum_df_factor=minimum_df_factor) 265 | 266 | # parallelisation of k-means runs 267 | # TODO 268 | 269 | return centers, labels, inertia 270 | 271 | 272 | def initialize(X, n_clusters, init, random_state, max_similar, alpha): 273 | n_samples = X.shape[0] 274 | 275 | # Random selection 276 | if isinstance(init, str) and init == 'random': 277 | np.random.seed(random_state) 278 | seeds = random_state.permutation(n_samples)[:n_clusters] 279 | centers = X[seeds, :].todense() 280 | # Customized initial centroids 281 | elif hasattr(init, '__array__'): 282 | centers = np.array(init, dtype=X.dtype) 283 | if centers.shape[0] != n_clusters: 284 | raise ValueError('the number of customized initial points ' 285 | 'should be same with n_clusters parameter' 286 | ) 287 | elif callable(init): 288 | centers = init(X, n_clusters, random_state=random_state) 289 | centers = np.asarray(centers, dtype=X.dtype) 290 | elif isinstance(init, str) and init == 'k-means++': 291 | centers = _k_init(X, n_clusters, random_state) 292 | elif isinstance(init, str) and init == 'similar_cut': 293 | centers = _similar_cut_init( 294 | X, n_clusters, random_state, max_similar, alpha) 295 | # Sophisticated initialization 296 | # TODO 297 | else: 298 | raise ValueError('the init parameter for spherical k-means should be ' 299 | 'random, ndarray, k-means++ or similar_cut' 300 | ) 301 | centers = normalize(centers) 302 | return centers 303 | 304 | 305 | def _k_init(X, n_clusters, random_state): 306 | """Init n_clusters seeds according to k-means++ 307 | It modified for Spherical k-means 308 | 309 | Parameters 310 | ----------- 311 | X : sparse matrix, shape (n_samples, n_features) 312 | n_clusters : integer 313 | The number of seeds to choose 314 | random_state : numpy.RandomState 315 | The generator used to initialize the centers. 316 | 317 | Notes 318 | ----- 319 | Selects initial cluster centers for k-mean clustering in a smart way 320 | to speed up convergence. see: Arthur, D. and Vassilvitskii, S. 321 | "k-means++: the advantages of careful seeding". ACM-SIAM symposium 322 | on Discrete algorithms. 2007 323 | Version ported from http://www.stanford.edu/~darthur/kMeansppTest.zip, 324 | which is the implementation used in the aforementioned paper. 325 | """ 326 | 327 | n_samples, n_features = X.shape 328 | centers = np.empty((n_clusters, n_features), dtype=X.dtype) 329 | random_state = check_random_state(random_state) 330 | 331 | # Set the number of local seeding trials if none is given 332 | # This is what Arthur/Vassilvitskii tried, but did not report 333 | # specific results for other than mentioning in the conclusion 334 | # that it helped. 335 | 336 | # Pick first center randomly 337 | center_id = random_state.randint(n_samples) 338 | centers[0] = X[center_id].toarray() 339 | 340 | # Initialize list of closest distances and calculate current potential 341 | closest_dist_sq = cosine_distances(centers[0, np.newaxis], X)[0] ** 2 342 | current_pot = closest_dist_sq.sum() 343 | 344 | # Pick the remaining n_clusters-1 points 345 | for c in range(1, n_clusters): 346 | # Choose center candidates by sampling with probability proportional 347 | # to the squared distance to the closest existing center 348 | rand_vals = random_state.random_sample() * current_pot 349 | candidate_ids = np.searchsorted(stable_cumsum(closest_dist_sq), 350 | rand_vals) 351 | 352 | centers[c] = X[candidate_ids].toarray() 353 | 354 | # Compute distances to center candidates 355 | new_dist_sq = cosine_distances(X[candidate_ids, :], X)[0] ** 2 356 | closest_dist_sq = np.minimum(new_dist_sq, closest_dist_sq) 357 | current_pot = closest_dist_sq.sum() 358 | 359 | return centers 360 | 361 | 362 | def _similar_cut_init(X, n_clusters, random_state, max_similar=0.5, sample_factor=3): 363 | 364 | n_data, n_features = X.shape 365 | centers = np.empty((n_clusters, n_features), dtype=X.dtype) 366 | 367 | np.random.seed(random_state) 368 | n_subsamples = min(n_data, int(sample_factor * n_clusters)) 369 | permutation = np.random.permutation(n_data) 370 | X_sub = X[permutation[:n_subsamples]] 371 | n_samples = X_sub.shape[0] 372 | 373 | # Pick first center randomly 374 | center_id = np.random.randint(n_samples) 375 | center_set = {center_id} 376 | centers[0] = X[center_id].toarray() 377 | candidates = np.asarray(range(n_samples)) 378 | 379 | # Pick the remaining n_clusters-1 points 380 | for c in range(1, n_clusters): 381 | closest_dist = inner_product( 382 | X_sub[center_id, :], X_sub[candidates, :].T) 383 | 384 | # Remove center similar points from candidates 385 | remains = np.where(closest_dist.todense() < max_similar)[1] 386 | if len(remains) == 0: 387 | break 388 | 389 | np.random.shuffle(remains) 390 | center_id = candidates[remains[0]] 391 | 392 | centers[c] = X_sub[center_id].toarray() 393 | candidates = candidates[remains[1:]] 394 | center_set.add(center_id) 395 | 396 | # If not enough center point search, random sample n_clusters - c points 397 | n_requires = n_clusters - 1 - c 398 | if n_requires > 0: 399 | if n_requires < (n_data - n_subsamples): 400 | random_centers = permutation[n_subsamples:n_subsamples+n_requires] 401 | else: 402 | center_set = set(permutation[np.asarray(list(center_set))]) 403 | random_centers = [] 404 | for idx in np.random.permutation(n_samples): 405 | if idx in center_set: 406 | continue 407 | random_centers.append(idx) 408 | if len(random_centers) == n_requires: 409 | break 410 | 411 | for i, center_id in enumerate(random_centers): 412 | centers[c+i+1] = X[center_id].toarray() 413 | 414 | return centers 415 | 416 | 417 | def kmeans_single(X, n_clusters, max_iter=10, init='similar_cult', sparsity=None, 418 | verbose=0, tol=1, random_state=None, debug_directory=None, 419 | debug_header=None, algorithm=None, max_similar=0.5, alpha=3, 420 | radius=10.0, epsilon=5.0, minimum_df_factor=0.01): 421 | 422 | _initialize_time = time.time() 423 | centers = initialize(X, n_clusters, init, random_state, max_similar, alpha) 424 | _initialize_time = time.time() - _initialize_time 425 | 426 | degree_of_sparsity = None 427 | degree_of_sparsity = check_sparsity(centers) 428 | ds_strf = ', sparsity={:.3}'.format( 429 | degree_of_sparsity) if degree_of_sparsity is not None else '' 430 | initial_state = 'initialization_time={} sec{}'.format( 431 | '%f' % _initialize_time, ds_strf) 432 | 433 | if verbose: 434 | print(initial_state) 435 | 436 | if debug_directory: 437 | log_path = '{}/{}_logs.txt'.format(debug_directory, debug_header) 438 | with open(log_path, 'w', encoding='utf-8') as f: 439 | f.write('{}\n'.format(initial_state)) 440 | 441 | centers, labels, inertia, n_iter_ = _kmeans_single_banilla( 442 | X, sparsity, n_clusters, centers, max_iter, verbose, 443 | tol, debug_directory, debug_header, 444 | radius, epsilon, minimum_df_factor) 445 | 446 | return centers, labels, inertia, n_iter_ 447 | 448 | 449 | def _kmeans_single_banilla(X, sparsity, n_clusters, centers, max_iter, 450 | verbose, tol, debug_directory, debug_header, 451 | radius, epsilon, minimum_df_factor): 452 | 453 | n_samples = X.shape[0] 454 | labels_old = np.zeros((n_samples,), dtype=np.int) 455 | 456 | for n_iter_ in range(1, max_iter + 1): 457 | 458 | _iter_time = time.time() 459 | 460 | labels, distances = pairwise_distances_argmin_min( 461 | X, centers, metric='cosine') 462 | centers = _update(X, labels, distances, n_clusters) 463 | inertia = distances.sum() 464 | 465 | if n_iter_ == 0: 466 | n_diff = n_samples 467 | else: 468 | diff = np.where((labels_old - labels) != 0)[0] 469 | n_diff = len(diff) 470 | 471 | labels_old = labels 472 | 473 | if isinstance(sparsity, str) and sparsity == 'sculley': 474 | centers = _sculley_projections(centers, radius, epsilon) 475 | elif isinstance(sparsity, str) and sparsity == 'minimum_df': 476 | centers = _minimum_df_projections( 477 | X, centers, labels_old, minimum_df_factor) 478 | 479 | _iter_time = time.time() - _iter_time 480 | 481 | degree_of_sparsity = None 482 | degree_of_sparsity = check_sparsity(centers) 483 | ds_strf = ', sparsity={:.3}'.format( 484 | degree_of_sparsity) if degree_of_sparsity is not None else '' 485 | state = 'n_iter={}, changed={}, inertia={}, iter_time={} sec{}'.format( 486 | n_iter_, n_diff, '%.3f' % inertia, '%.3f' % _iter_time, ds_strf) 487 | 488 | if debug_directory: 489 | # Log message 490 | log_path = '{}/{}_logs.txt'.format(debug_directory, debug_header) 491 | with open(log_path, 'a', encoding='utf-8') as f: 492 | f.write('{}\n'.format(state)) 493 | 494 | # Temporal labels 495 | label_path = '{}/{}_label_iter{}.txt'.format( 496 | debug_directory, debug_header, n_iter_) 497 | with open(label_path, 'a', encoding='utf-8') as f: 498 | for label in labels: 499 | f.write('{}\n'.format(label)) 500 | 501 | # Temporal cluster_centroid 502 | center_path = '{}/{}_centroids_iter{}.csv'.format( 503 | debug_directory, debug_header, n_iter_) 504 | np.savetxt(center_path, centers) 505 | 506 | if verbose: 507 | print(state) 508 | 509 | if n_diff <= tol: 510 | if verbose and (n_iter_ + 1 < max_iter): 511 | print('Early converged.') 512 | break 513 | 514 | return centers, labels, inertia, n_iter_ 515 | 516 | 517 | def _update(X, labels, distances, n_clusters): 518 | 519 | n_featuers = X.shape[1] 520 | centers = np.zeros((n_clusters, n_featuers)) 521 | 522 | n_samples_in_cluster = np.bincount(labels, minlength=n_clusters) 523 | empty_clusters = np.where(n_samples_in_cluster == 0)[0] 524 | n_empty_clusters = empty_clusters.shape[0] 525 | 526 | data = X.data 527 | indices = X.indices 528 | indptr = X.indptr 529 | 530 | if n_empty_clusters > 0: 531 | # find points to reassign empty clusters to 532 | far_from_centers = distances.argsort()[::-1][:n_empty_clusters] 533 | 534 | # reassign labels to empty clusters 535 | for i in range(n_empty_clusters): 536 | centers[empty_clusters[i]] = X[far_from_centers[i]].toarray() 537 | n_samples_in_cluster[empty_clusters[i]] = 1 538 | labels[far_from_centers[i]] = empty_clusters[i] 539 | 540 | # cumulate centroid vector 541 | for i, curr_label in enumerate(labels): 542 | for ind in range(indptr[i], indptr[i + 1]): 543 | j = indices[ind] 544 | centers[curr_label, j] += data[ind] 545 | 546 | # L2 normalization 547 | centers = normalize(centers) 548 | return centers 549 | 550 | 551 | def _sculley_projections(centers, radius, epsilon): 552 | n_clusters = centers.shape[0] 553 | for c in range(n_clusters): 554 | centers[c] = _sculley_projection(centers[c], radius, epsilon) 555 | centers = normalize(centers) 556 | return centers 557 | 558 | 559 | def _sculley_projection(center, radius, epsilon): 560 | def l1_norm(x): 561 | return abs(x).sum() 562 | 563 | def inf_norm(x): 564 | return abs(x).max() 565 | 566 | upper, lower = inf_norm(center), 0 567 | current = l1_norm(center) 568 | 569 | larger_than = radius * (1 + epsilon) 570 | smaller_than = radius 571 | 572 | _n_iter = 0 573 | theta = 0 574 | 575 | while current > larger_than or current < smaller_than: 576 | theta = (upper + lower) / 2.0 # Get L1 value for this theta 577 | current = sum([v for v in (abs(center) - theta) if v > 0]) 578 | if current <= radius: 579 | upper = theta 580 | else: 581 | lower = theta 582 | 583 | # for safety, preventing infinite loops 584 | _n_iter += 1 585 | if _n_iter > 10000: 586 | break 587 | if upper - lower < 0.001: 588 | break 589 | 590 | signs = np.sign(center) 591 | projection = [max(0, ci) for ci in (abs(center) - theta)] 592 | projection = np.asarray( 593 | [ci * signs[i] if ci > 0 else 0 for i, ci in enumerate(projection)]) 594 | return projection 595 | 596 | 597 | def L1_projection(v, z): 598 | m = v.copy() 599 | m.sort() 600 | m = m[::-1] 601 | 602 | pho = 0 603 | for j, mj in enumerate(m): 604 | t = mj - (m[:j + 1].sum() - z) / (1 + j) 605 | if t < 0: 606 | break 607 | pho = j 608 | 609 | theta = (m[:pho + 1].sum() - z) / (pho + 1) 610 | v_ = np.asarray([max(vi - theta, 0) for vi in v]) 611 | return v_ 612 | 613 | 614 | def _minimum_df_projections(X, centers, labels_, minimum_df_factor): 615 | n_clusters = centers.shape[0] 616 | centers_ = sp.csr_matrix(centers.copy()) 617 | 618 | data = centers_.data 619 | indptr = centers_.indptr 620 | 621 | n_samples_in_cluster = np.bincount(labels_, minlength=n_clusters) 622 | min_value = np.asarray([(minimum_df_factor / n_samples_in_cluster[c]) 623 | if n_samples_in_cluster[c] > 1 else 0 for c in range(n_clusters)]) 624 | for c in range(n_clusters): 625 | for ind in range(indptr[c], indptr[c + 1]): 626 | if data[ind] ** 2 < min_value[c]: 627 | data[ind] = 0 628 | centers_ = centers_.todense() 629 | centers_ = normalize(centers_) 630 | return centers_ 631 | 632 | 633 | def _minimum_df_projection(center, min_value): 634 | center[[idx for idx, v in enumerate(center) if v**2 < min_value]] = 0 635 | return center 636 | -------------------------------------------------------------------------------- /soyclustering/_postprocess.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from sklearn.metrics import pairwise_distances 3 | 4 | def merge_close_clusters(centers, labels, max_dist=0.7): 5 | """ 6 | Arguments 7 | --------- 8 | centers : numpy.ndarray 9 | Shape = (k, p) 10 | k : num of clusters 11 | p : num of features 12 | labels : numpy.ndarray or None 13 | Shape = (n,) 14 | n : num of documents in the dataset 15 | It is used as cluster size weight. If the value is None, 16 | it assumes that all size of clusters are equal. 17 | max_dist : float 18 | Maximum Cosine distance between base cluster and other clusters 19 | The smaller the value, it groups closer clusters to a group. 20 | 21 | Returns 22 | ------- 23 | group_centers : numpy.ndarray 24 | Merged cluster centroid vectors 25 | Shape = (l, p) 26 | l : num of merged clusters. l <= k 27 | p : num of features 28 | groups : list of list of int 29 | The index of first index corresponds the index of merged clusters. 30 | And the value in the inner lists corresponds the index of original clusters. 31 | """ 32 | 33 | n_clusters, n_terms = centers.shape 34 | cluster_size = np.bincount(labels, minlength=n_clusters) 35 | sorted_indices, _ = zip(*sorted(enumerate(cluster_size), key=lambda x:-x[1])) 36 | 37 | groups = _grouping_with_centers(centers, max_dist, sorted_indices) 38 | centers_ = np.dot(np.diag(cluster_size), centers) 39 | 40 | n_groups = len(groups) 41 | group_centers = np.zeros((n_groups, n_terms)) 42 | for g, idxs in enumerate(groups): 43 | sum_ = centers_[idxs].sum(axis=0) 44 | mean = sum_ / cluster_size[idxs].sum() 45 | group_centers[g] = mean 46 | return group_centers, groups 47 | 48 | def _closest_group(groups, c, pdist, max_dist): 49 | """ 50 | It finds the most closest merged clusters with the given cluster c 51 | 52 | Arguments 53 | --------- 54 | groups : list of list of int 55 | The index of first index corresponds the index of merged clusters. 56 | And the value in the inner lists corresponds the index of original clusters. 57 | c : int 58 | Index of the cluster which this function finds the most closest merged group 59 | pdist : numpy.ndarray 60 | Pairwise distance matrix. 61 | Shape is (k, k) where k is num of clusters. 62 | max_dist : float 63 | Maximum Cosine distance between base cluster and other clusters. 64 | The smaller the value, it groups closer clusters to a group. 65 | 66 | Returns 67 | ------- 68 | closest : int or None 69 | The index of most closest merged group. 70 | If the closest one and target cluster c is distants than max_dist, 71 | it returns None 72 | """ 73 | 74 | dist_ = 1 75 | closest = None 76 | for g, idxs in enumerate(groups): 77 | dist = pdist[idxs, c].mean() 78 | if dist > max_dist: 79 | continue 80 | if dist_ > dist: 81 | dist_ = dist 82 | closest = g 83 | return closest 84 | 85 | def _grouping_with_centers(centers, max_dist, sorted_indices): 86 | """ 87 | Arguments 88 | --------- 89 | centers : numpy.ndarray 90 | Shape = (k, p) 91 | k : num of clusters 92 | p : num of features 93 | max_dist : float 94 | Maximum Cosine distance between base cluster and other clusters. 95 | The smaller the value, it groups closer clusters to a group. 96 | sorted_index : list of int 97 | Cluster index sorted by the size of each cluster. 98 | 99 | Returns 100 | ------- 101 | groups : list of list of int 102 | The index of first index corresponds the index of merged clusters. 103 | And the value in the inner lists corresponds the index of original clusters. 104 | """ 105 | 106 | pdist = pairwise_distances(centers, metric='cosine') 107 | return _grouping_with_pdist(pdist, max_dist, sorted_indices) 108 | 109 | def _grouping_with_pdist(pdist, max_dist, sorted_indices): 110 | """ 111 | Arguments 112 | --------- 113 | pdist : numpy.ndarray 114 | Pairwise distance matrix. 115 | Shape is (k, k) where k is num of clusters. 116 | max_dist : float 117 | Maximum Cosine distance between base cluster and other clusters. 118 | The smaller the value, it groups closer clusters to a group. 119 | sorted_index : list of int 120 | Cluster index sorted by the size of each cluster. 121 | 122 | Returns 123 | ------- 124 | groups : list of list of int 125 | The index of first index corresponds the index of merged clusters. 126 | And the value in the inner lists corresponds the index of original clusters. 127 | """ 128 | groups = [[sorted_indices[0]]] 129 | for c in sorted_indices[1:]: 130 | g = _closest_group(groups, c, pdist, max_dist) 131 | # create new group 132 | if g is None: 133 | groups.append([c]) 134 | # assign c to g 135 | else: 136 | groups[g].append(c) 137 | return groups 138 | -------------------------------------------------------------------------------- /soyclustering/_spherical_kmeans_core.pyx: -------------------------------------------------------------------------------- 1 | # cython: profile=True 2 | # Profiling is enabled by default as the overhead does not seem to be measurable 3 | # on this specific use case. 4 | 5 | # Author: Peter Prettenhofer 6 | # Olivier Grisel 7 | # Lars Buitinck 8 | # 9 | # License: BSD 3 clause 10 | 11 | from libc.math cimport sqrt 12 | import numpy as np 13 | import scipy.sparse as sp 14 | cimport numpy as np 15 | cimport cython 16 | from cython cimport floating 17 | 18 | from sklearn.utils.sparsefuncs_fast import assign_rows_csr 19 | 20 | ctypedef np.float64_t DOUBLE 21 | ctypedef np.int32_t INT 22 | 23 | ctypedef floating (*DOT)(int N, floating *X, int incX, floating *Y, 24 | int incY) 25 | 26 | cdef extern from "cblas.h": 27 | double ddot "cblas_ddot"(int N, double *X, int incX, double *Y, int incY) 28 | float sdot "cblas_sdot"(int N, float *X, int incX, float *Y, int incY) 29 | 30 | np.import_array() 31 | 32 | @cython.boundscheck(False) 33 | @cython.wraparound(False) 34 | @cython.cdivision(True) 35 | cpdef DOUBLE _assign_labels_csr(X, np.ndarray[floating, ndim=2] centers, 36 | np.ndarray[INT, ndim=1] labels): 37 | """Compute label assignment and inertia for a CSR input in Spherical k-means 38 | Return the inertia (sum of squared distances to the centers). 39 | """ 40 | cdef: 41 | np.ndarray[floating, ndim=1] X_data = X.data 42 | np.ndarray[INT, ndim=1] X_indices = X.indices 43 | np.ndarray[INT, ndim=1] X_indptr = X.indptr 44 | unsigned int n_clusters = centers.shape[0] 45 | unsigned int n_features = centers.shape[1] 46 | unsigned int n_samples = X.shape[0] 47 | unsigned int store_distances = 0 48 | unsigned int sample_idx, center_idx, feature_idx 49 | unsigned int k 50 | # the following variables are always double cause make them floating 51 | # does not save any memory, but makes the code much bigger 52 | DOUBLE inertia = 0.0 53 | DOUBLE min_dist 54 | DOUBLE dist 55 | DOT dot 56 | 57 | if floating is float: 58 | center_squared_norms = np.zeros(n_clusters, dtype=np.float32) 59 | dot = sdot 60 | else: 61 | center_squared_norms = np.zeros(n_clusters, dtype=np.float64) 62 | dot = ddot 63 | 64 | for sample_idx in range(n_samples): 65 | max_prod = 0 66 | for center_idx in range(n_clusters): 67 | prod = 0.0 68 | # hardcoded: minimize cosine distance to cluster center: 69 | # cos(a,b) = 1 - if a and b are unit vector 70 | for k in range(X_indptr[sample_idx], X_indptr[sample_idx + 1]): 71 | prod += centers[center_idx, X_indices[k]] * X_data[k] 72 | if max_prod == 0 or max_prod < prod: 73 | max_prod = prod 74 | labels[sample_idx] = center_idx 75 | inertia += (1 - max_prod) 76 | 77 | return inertia -------------------------------------------------------------------------------- /soyclustering/_utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from sklearn.utils.extmath import safe_sparse_dot 3 | 4 | def inner_product(X, Y): 5 | """ 6 | Arguments 7 | -------- 8 | X, Y: numpy.ndarray or scipy.sparse.csr_matrix 9 | One of both must be sparse matrix 10 | shape of X = (n,p) 11 | shape of Y = (p,m) 12 | 13 | Returns 14 | ------- 15 | Z : scipy.sparse.csr_matrix 16 | shape of Z = (n,m) 17 | """ 18 | 19 | return safe_sparse_dot(X, Y, dense_output=False) 20 | 21 | def check_sparsity(x): 22 | """ 23 | It calculates sparsity of centroid vectors 24 | 25 | Argument 26 | -------- 27 | x : numpy.ndarray 28 | 29 | Returns 30 | ------- 31 | sparsity : float 32 | 1 - proportion of nonzero elements 33 | """ 34 | n,m = x.shape 35 | return 1-sum(len(np.where(x[c] != 0)[0]) for c in range(n)) / (n*m) 36 | 37 | -------------------------------------------------------------------------------- /soyclustering/_visualize.py: -------------------------------------------------------------------------------- 1 | from sklearn.metrics import pairwise_distances 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | 5 | from ._postprocess import _grouping_with_pdist 6 | 7 | def visualize_pairwise_distance(centers, labels=None, max_dist=0.7, 8 | sort=False, show=True, title=None, figsize=(15,15), cmap='gray', 9 | clim=None, dpi=50, facecolor=None, edgecolor=None, frameon=True): 10 | """ 11 | Arguments 12 | --------- 13 | centers : numpy.ndarray 14 | Shape = (k, p) 15 | k : num of clusters 16 | p : num of features 17 | labels : numpy.ndarray or None 18 | Shape = (n,) 19 | n : num of documents in the dataset 20 | It is used as cluster size weight. If the value is None, 21 | it assumes that all size of clusters are equal. 22 | max_dist : float 23 | Maximum Cosine distance between base cluster and other clusters. 24 | The smaller the value, it groups closer clusters to a group. 25 | sort : Boolean 26 | It True, it first groups nearby clusters into one group 27 | then draw pairwise distance matrix 28 | title : str or None 29 | The title of the figure 30 | figsize : tuple of int 31 | Size of the figure. Default is (15,15) 32 | cmap : str 33 | Color map in matplotlib. Default is gray 34 | clim : tuple of int or None 35 | Color limit in matplotlib. 36 | dpi : int 37 | DPI of the figure 38 | facecolor : tuple of float or None 39 | RBG color of background 40 | For example (0.15, 0.5, 0.5) 41 | edgecolor : tuple of float or None 42 | RBG color of edge for the figure 43 | For example (0.15, 0.5, 0.5) 44 | frameon : Boolean 45 | Ignored 46 | 47 | Returns 48 | ------- 49 | figure : matplotlib.pyplot.figure 50 | Figure of pairwise distance 51 | """ 52 | 53 | n_clusters = centers.shape[0] 54 | 55 | if labels is None: 56 | labels = [i for i in range(n_clusters)] 57 | 58 | pdist = pairwise_distances(centers, metric='cosine') 59 | 60 | if sort: 61 | # sort clusters by cluster size 62 | cluster_size = np.bincount(labels, minlength=n_clusters) 63 | sorted_indices, _ = zip(*sorted(enumerate(cluster_size), key=lambda x:-x[1])) 64 | 65 | # grouping clusters 66 | groups = _grouping_with_pdist(pdist, max_dist, sorted_indices) 67 | 68 | # sort groups by group size 69 | groups = sorted(groups, key=lambda x:-len(x)) 70 | 71 | # create revised index 72 | sorted_indices = [idx for group in groups for idx in group] 73 | indices_revised = np.ix_(sorted_indices, sorted_indices) 74 | 75 | # create origin index 76 | indices_orig = list(range(n_clusters)) 77 | 78 | # revise pairwise distance matrix 79 | pdist_revised = np.empty_like(pdist) 80 | pdist_revised[np.ix_(indices_orig,indices_orig)] = pdist[indices_revised] 81 | 82 | else: 83 | pdist_revised = pdist 84 | 85 | figure = pairwise_distance_to_matplotlib_figure(pdist_revised, title, 86 | figsize, cmap, clim, dpi, facecolor, edgecolor, frameon) 87 | return figure 88 | 89 | def pairwise_distance_to_matplotlib_figure(pdist, title=None, 90 | figsize=(15,15), cmap='gray', clim=None, dpi=50, 91 | facecolor=None, edgecolor=None, frameon=True): 92 | """ 93 | pdist : numpy.ndarray 94 | Pairwise distance matrix. Shape is (k, k) when k is num of clusters 95 | title : str or None 96 | The title of the figure 97 | figsize : tuple of int 98 | Size of the figure. Default is (15,15) 99 | cmap : str 100 | Color map in matplotlib. Default is gray 101 | clim : tuple of int or None 102 | Color limit in matplotlib. 103 | dpi : int 104 | DPI of the figure 105 | facecolor : tuple of float or None 106 | RBG color of background 107 | For example (0.15, 0.5, 0.5) 108 | edgecolor : tuple of float or None 109 | RBG color of edge for the figure 110 | For example (0.15, 0.5, 0.5) 111 | frameon : Boolean 112 | Ignored 113 | 114 | Returns 115 | ------- 116 | figure : matplotlib.pyplot.figure 117 | The figure of pairwise distance matrix 118 | """ 119 | 120 | n_clusters = pdist.shape[0] 121 | 122 | figure = plt.figure( 123 | figsize = figsize, 124 | dpi = dpi, 125 | facecolor = facecolor, 126 | edgecolor = edgecolor, 127 | frameon = frameon 128 | ) 129 | 130 | if title: 131 | plt.title(title) 132 | 133 | plt.xlim((0, n_clusters)) 134 | plt.ylim((0, n_clusters)) 135 | 136 | if clim: 137 | plt.imshow(pdist, cmap=cmap, clim=clim) 138 | else: 139 | plt.imshow(pdist, cmap=cmap) 140 | 141 | return figure 142 | -------------------------------------------------------------------------------- /tests/test_kmeans.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pytest 3 | import sys 4 | root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) 5 | sys.path.insert(0, root) 6 | 7 | from soyclustering import SphericalKMeans 8 | from soyclustering import proportion_keywords 9 | from lovit_textmining_dataset.navernews_10days import get_bow 10 | 11 | 12 | # pytest execution with verbose 13 | # $ pytest tests/test_kmeans.py -s -v 14 | 15 | 16 | @pytest.fixture 17 | def test_data(): 18 | x, idx_to_vocab, vocab_to_idx = get_bow(date='2016-10-20', tokenize='noun') 19 | return {'x': x, 'idx_to_vocab': idx_to_vocab} 20 | 21 | 22 | def test_kmeans(test_data): 23 | x = test_data['x'] 24 | n_features = x.shape[1] 25 | n_clusters = 100 26 | print('\nk-means test with various configuration') 27 | 28 | configs = [('k-means++', None), ('similar_cut', None), ('similar_cut', 'minimum_df')] 29 | for config in configs: 30 | init, sparsity = config 31 | print(f'\nConfig\n - init: {init}\n - sparsity: {sparsity}') 32 | kmeans = SphericalKMeans(n_clusters=n_clusters, init=init, 33 | sparsity=sparsity, max_iter=5, tol=0.0001, verbose = True, random_state=0) 34 | labels = kmeans.fit_predict(x) 35 | centers = kmeans.cluster_centers_ 36 | assert centers.shape == (n_clusters, n_features) 37 | 38 | 39 | def test_transform(test_data): 40 | x = test_data['x'] 41 | n_docs = x.shape[0] 42 | n_clusters = 100 43 | print('\ntransform test') 44 | kmeans = SphericalKMeans(n_clusters=n_clusters, init='similar_cut', 45 | sparsity=None, max_iter=5, tol=0.0001, verbose = True, random_state=0) 46 | kmeans.fit(x) 47 | distances = kmeans.transform(x) 48 | assert (distances.shape == (n_docs, n_clusters)) and (distances.min() >= 0) and (distances.max() <= 1) 49 | 50 | 51 | def test_clustering_labeling(test_data): 52 | x = test_data['x'] 53 | idx_to_vocab = test_data['idx_to_vocab'] 54 | print('\nclustering labeling test') 55 | kmeans = SphericalKMeans( 56 | n_clusters=300, 57 | init='similar_cut', 58 | sparsity=None, 59 | max_iter=10, 60 | tol=0.0001, 61 | verbose = True, 62 | random_state=0 63 | ) 64 | labels = kmeans.fit_predict(x) 65 | keywords = proportion_keywords( 66 | kmeans.cluster_centers_, 67 | labels, 68 | index2word=idx_to_vocab, 69 | topk=30, 70 | candidates_topk=100 71 | ) 72 | for cluster_idx, keyword in enumerate(keywords): 73 | keyword = ' '.join([w for w,_ in keyword]) 74 | if '아이오아이' in keyword: 75 | print('cluster#{} : {}'.format(cluster_idx, keyword)) 76 | -------------------------------------------------------------------------------- /tutorial.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "데이터가 Sparse matrix 일 때 cosine distance 를 이용하면 대부분의 거리가 0.9 ~ 1.0 에 가깝습니다. 그렇기 때문에 bag of words model 을 이용하는 term frequency matrix 에서는 k-means++ 가 큰 의미가 없습니다. \n", 8 | "\n", 9 | "k-means++ 은 distance distribution 이 한쪽에 치우치지 않았을 때 잘 작동합니다. Similar cut initializer 는 term frequency matrix 와 같은 sparse vector 에서 효율적으로 initial points 를 선택하기 위한 방법입니다. 더 자세한 설명은 아래의 블로그를 참고해주세요.\n", 10 | "\n", 11 | "https://lovit.github.io/nlp/machine%20learning/2018/03/19/kmeans_initializer/\n", 12 | "\n", 13 | "실험에 이용하는 데이터는 https://github.com/lovit/textmining_dataset/ 에서 다운받을 수 있습니다." 14 | ] 15 | }, 16 | { 17 | "cell_type": "code", 18 | "execution_count": 1, 19 | "metadata": {}, 20 | "outputs": [ 21 | { 22 | "data": { 23 | "text/plain": [ 24 | "(30091, 9774)" 25 | ] 26 | }, 27 | "execution_count": 1, 28 | "metadata": {}, 29 | "output_type": "execute_result" 30 | } 31 | ], 32 | "source": [ 33 | "from lovit_textmining_dataset.navernews_10days import get_bow\n", 34 | "\n", 35 | "x, idx_to_vocab, vocab_to_idx = get_bow(date='2016-10-20', tokenize='noun')\n", 36 | "x.shape" 37 | ] 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "metadata": {}, 42 | "source": [ 43 | "idx_to_vocab 은 9.774 개의 단어들의 idx 에 해당하는 단어가 저장되어 있습니다. 이는 cluster labeling 에 이용됩니다." 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": 2, 49 | "metadata": {}, 50 | "outputs": [ 51 | { 52 | "name": "stdout", 53 | "output_type": "stream", 54 | "text": [ 55 | "['아이스크림', '아이엠', '아이오아이', '아이콘', '아이템']\n" 56 | ] 57 | } 58 | ], 59 | "source": [ 60 | "print(idx_to_vocab[5535:5540])" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 3, 66 | "metadata": {}, 67 | "outputs": [ 68 | { 69 | "name": "stdout", 70 | "output_type": "stream", 71 | "text": [ 72 | "0.2.0\n" 73 | ] 74 | } 75 | ], 76 | "source": [ 77 | "import time\n", 78 | "import sys\n", 79 | "sys.path.append('../')\n", 80 | "import soyclustering\n", 81 | "\n", 82 | "print(soyclustering.__version__)\n", 83 | "\n", 84 | "n_clusters = 300" 85 | ] 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "metadata": {}, 90 | "source": [ 91 | "## Time comparison\n", 92 | "\n", 93 | "### Initializer: similar cut vs. k-means++\n", 94 | "\n", 95 | "k-means++ 을 이용할 경우 (30091, 9774) 데이터에 대하여 initialization 에 9.462 초를 이용합니다.\n", 96 | "\n", 97 | "similar cut 은 비슷한 점들을 initial points 로 선택하지 않으면서도 0.043 초만에 initialization 이 가능합니다. distance distribution 이 0.9 ~ 1.0 에 치우친 경우에는 k-means++ 은 잘 작동하지 않습니다." 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "execution_count": 4, 103 | "metadata": {}, 104 | "outputs": [ 105 | { 106 | "name": "stdout", 107 | "output_type": "stream", 108 | "text": [ 109 | "initialization_time=9.648999 sec, sparsity=0.00844\n", 110 | "n_iter=1, changed=29952, inertia=16427.832, iter_time=1.990 sec, sparsity=0.164\n", 111 | "n_iter=2, changed=5975, inertia=12413.602, iter_time=1.922 sec, sparsity=0.152\n", 112 | "n_iter=3, changed=2192, inertia=11976.571, iter_time=1.924 sec, sparsity=0.148\n", 113 | "n_iter=4, changed=1128, inertia=11838.584, iter_time=1.942 sec, sparsity=0.147\n", 114 | "n_iter=5, changed=701, inertia=11764.806, iter_time=1.913 sec, sparsity=0.146\n", 115 | "n_iter=6, changed=390, inertia=11726.887, iter_time=1.914 sec, sparsity=0.145\n", 116 | "n_iter=7, changed=299, inertia=11710.406, iter_time=1.899 sec, sparsity=0.145\n", 117 | "n_iter=8, changed=198, inertia=11700.876, iter_time=1.913 sec, sparsity=0.145\n", 118 | "n_iter=9, changed=159, inertia=11694.908, iter_time=1.907 sec, sparsity=0.145\n", 119 | "n_iter=10, changed=139, inertia=11689.538, iter_time=1.914 sec, sparsity=0.145\n", 120 | "process time = 29.074 seconds\n" 121 | ] 122 | } 123 | ], 124 | "source": [ 125 | "import numpy as np\n", 126 | "from soyclustering import SphericalKMeans\n", 127 | "\n", 128 | "kmeans = SphericalKMeans(\n", 129 | " n_clusters=n_clusters,\n", 130 | " init='k-means++',\n", 131 | " sparsity=None,\n", 132 | " max_iter=10,\n", 133 | " tol=0.0001,\n", 134 | " verbose = True,\n", 135 | " random_state=0\n", 136 | ")\n", 137 | "\n", 138 | "t = time.time()\n", 139 | "labels = kmeans.fit_predict(x)\n", 140 | "t = time.time() - t\n", 141 | "\n", 142 | "print('process time = {} seconds'.format('%.3f' % t))" 143 | ] 144 | }, 145 | { 146 | "cell_type": "code", 147 | "execution_count": 5, 148 | "metadata": {}, 149 | "outputs": [ 150 | { 151 | "name": "stdout", 152 | "output_type": "stream", 153 | "text": [ 154 | "initialization_time=0.049929 sec, sparsity=0.00707\n", 155 | "n_iter=1, changed=29951, inertia=16428.435, iter_time=1.945 sec, sparsity=0.161\n", 156 | "n_iter=2, changed=7805, inertia=12947.107, iter_time=1.916 sec, sparsity=0.149\n", 157 | "n_iter=3, changed=3840, inertia=12239.101, iter_time=1.896 sec, sparsity=0.145\n", 158 | "n_iter=4, changed=2191, inertia=11957.270, iter_time=1.927 sec, sparsity=0.142\n", 159 | "n_iter=5, changed=1266, inertia=11826.583, iter_time=1.883 sec, sparsity=0.141\n", 160 | "n_iter=6, changed=827, inertia=11762.833, iter_time=1.905 sec, sparsity=0.141\n", 161 | "n_iter=7, changed=596, inertia=11717.253, iter_time=1.893 sec, sparsity=0.141\n", 162 | "n_iter=8, changed=526, inertia=11689.117, iter_time=1.896 sec, sparsity=0.141\n", 163 | "n_iter=9, changed=451, inertia=11667.402, iter_time=1.906 sec, sparsity=0.14\n", 164 | "n_iter=10, changed=354, inertia=11647.316, iter_time=1.896 sec, sparsity=0.14\n", 165 | "process time = 19.223 seconds\n" 166 | ] 167 | } 168 | ], 169 | "source": [ 170 | "from soyclustering import SphericalKMeans\n", 171 | "\n", 172 | "kmeans = SphericalKMeans(\n", 173 | " n_clusters=n_clusters,\n", 174 | " init='similar_cut',\n", 175 | " sparsity=None,\n", 176 | " max_iter=10,\n", 177 | " tol=0.0001,\n", 178 | " verbose = True,\n", 179 | " random_state=0\n", 180 | ")\n", 181 | "\n", 182 | "t = time.time()\n", 183 | "labels = kmeans.fit_predict(x)\n", 184 | "t = time.time() - t\n", 185 | "\n", 186 | "print('process time = {} seconds'.format('%.3f' % t))" 187 | ] 188 | }, 189 | { 190 | "cell_type": "markdown", 191 | "metadata": {}, 192 | "source": [ 193 | "### soyclustering vs. scikit-learn\n", 194 | "\n", 195 | "각 데이터와 centroids 와의 거리 계산 후, 새로운 cluster 에 데이터를 할당하는 부분이 scikit-learn 과 다르게 구현되어 있습니다. 현재 (version 0.2.0)는 scikit-learn 의 k-means 보다 약 1.9 배 정도 더 빨리 학습됩니다.\n", 196 | "\n", 197 | "scikit-learn 은 Euclidean distance 를 이용합니다. L2 normalized 된 centroids 가 아닌 L1 normalized 이기 때문에 Cosine 과 Euclidean 의 값은 차이가 있습니다." 198 | ] 199 | }, 200 | { 201 | "cell_type": "code", 202 | "execution_count": 6, 203 | "metadata": {}, 204 | "outputs": [ 205 | { 206 | "name": "stdout", 207 | "output_type": "stream", 208 | "text": [ 209 | "0.22.2.post1\n" 210 | ] 211 | } 212 | ], 213 | "source": [ 214 | "import sklearn\n", 215 | "print(sklearn.__version__)\n", 216 | "\n", 217 | "# scikit-learn KMeans use only Euclidean\n", 218 | "from sklearn.preprocessing import normalize\n", 219 | "x_ = normalize(x)" 220 | ] 221 | }, 222 | { 223 | "cell_type": "code", 224 | "execution_count": 7, 225 | "metadata": {}, 226 | "outputs": [ 227 | { 228 | "name": "stdout", 229 | "output_type": "stream", 230 | "text": [ 231 | "Initialization complete\n", 232 | "Iteration 0, inertia 21420.119\n", 233 | "Iteration 1, inertia 18232.433\n", 234 | "Iteration 2, inertia 17830.319\n", 235 | "Iteration 3, inertia 17662.184\n", 236 | "Iteration 4, inertia 17561.343\n", 237 | "Iteration 5, inertia 17484.342\n", 238 | "Iteration 6, inertia 17430.595\n", 239 | "Iteration 7, inertia 17390.316\n", 240 | "Iteration 8, inertia 17365.886\n", 241 | "Iteration 9, inertia 17345.277\n", 242 | "process time = 57.047 seconds\n" 243 | ] 244 | } 245 | ], 246 | "source": [ 247 | "from sklearn.cluster import KMeans\n", 248 | "\n", 249 | "kmeans_sklearn = KMeans(\n", 250 | " n_clusters=n_clusters,\n", 251 | " init='k-means++',\n", 252 | " n_init=1,\n", 253 | " max_iter=10,\n", 254 | " tol=0.0001,\n", 255 | " verbose=1\n", 256 | ")\n", 257 | "\n", 258 | "t = time.time()\n", 259 | "_label = kmeans_sklearn.fit_predict(x_)\n", 260 | "t = time.time() - t\n", 261 | "\n", 262 | "print('process time = {} seconds'.format('%.3f' % t))" 263 | ] 264 | }, 265 | { 266 | "cell_type": "markdown", 267 | "metadata": { 268 | "collapsed": true 269 | }, 270 | "source": [ 271 | "## cluster labeling" 272 | ] 273 | }, 274 | { 275 | "cell_type": "markdown", 276 | "metadata": {}, 277 | "source": [ 278 | "proportion keywords 를 이용하면 cluster centroids 와 vocabulary index 를 이용하여 각 클러스터 별 cluster label 을 찾을 수 있습니다.\n", 279 | "\n", 280 | "각 cluster 별로 weight 가 높은 candidates_topk 개의 후보 중에서 proportion keyword score 가 높은 topk 개의 단어가 cluster labels 로 선택됩니다. \n", 281 | "\n", 282 | "Proportion keywords 의 원리는 아래의 블로그에 설명되어 있습니다.\n", 283 | "\n", 284 | "https://lovit.github.io/nlp/machine%20learning/2018/03/21/kmeans_cluster_labeling/" 285 | ] 286 | }, 287 | { 288 | "cell_type": "code", 289 | "execution_count": 8, 290 | "metadata": {}, 291 | "outputs": [ 292 | { 293 | "name": "stderr", 294 | "output_type": "stream", 295 | "text": [ 296 | "/Users/hyunjoongkim/git/clustering4docs/soyclustering/_keyword.py:42: RuntimeWarning: invalid value encountered in true_divide\n", 297 | " def l1_normalize(x): return x/x.sum()\n", 298 | "/Users/hyunjoongkim/git/clustering4docs/soyclustering/_keyword.py:67: RuntimeWarning: invalid value encountered in greater\n", 299 | " indices = np.where(p_prop > 0)[0]\n" 300 | ] 301 | } 302 | ], 303 | "source": [ 304 | "from soyclustering import proportion_keywords\n", 305 | "\n", 306 | "keywords = proportion_keywords(\n", 307 | " kmeans.cluster_centers_,\n", 308 | " labels,\n", 309 | " index2word=idx_to_vocab,\n", 310 | " topk=30,\n", 311 | " candidates_topk=100\n", 312 | ")" 313 | ] 314 | }, 315 | { 316 | "cell_type": "markdown", 317 | "metadata": {}, 318 | "source": [ 319 | "keywords 는 list of list of tuple 입니다. Tuple 은 (단어, 키워드 점수)로 이뤄져 있습니다." 320 | ] 321 | }, 322 | { 323 | "cell_type": "code", 324 | "execution_count": 9, 325 | "metadata": {}, 326 | "outputs": [ 327 | { 328 | "data": { 329 | "text/plain": [ 330 | "[('빅브레인', 0.9998356991641689),\n", 331 | " ('너무너무너무', 0.999636565607772),\n", 332 | " ('신용재', 0.9996209421673745),\n", 333 | " ('오블리스', 0.9994778748084965),\n", 334 | " ('갓세븐', 0.9992970603778885),\n", 335 | " ('다비치', 0.9991180784713255),\n", 336 | " ('엠카운트다운', 0.9985666150928039),\n", 337 | " ('아이오아이', 0.9982645820718874),\n", 338 | " ('세븐', 0.996996851052826),\n", 339 | " ('박진영', 0.9967750269776107),\n", 340 | " ('방탄소년단', 0.9966473687693944),\n", 341 | " ('트로피', 0.996464966998091),\n", 342 | " ('완전체', 0.996227525576321),\n", 343 | " ('고마워', 0.995881757255629),\n", 344 | " ('산들', 0.9956056841004022),\n", 345 | " ('잠깐', 0.9955334197813145),\n", 346 | " ('중독성', 0.9949229577434185),\n", 347 | " ('펜타곤', 0.9946393121986635),\n", 348 | " ('정국', 0.9936714705659159),\n", 349 | " ('열창', 0.9934191181343699),\n", 350 | " ('그대', 0.9930229656843981),\n", 351 | " ('상큼', 0.9906486052581086),\n", 352 | " ('엠넷', 0.9896207484574001),\n", 353 | " ('타이틀곡', 0.9894943427370902),\n", 354 | " ('코드', 0.9890875408599619),\n", 355 | " ('챔피언', 0.9883417239438613),\n", 356 | " ('보컬', 0.9882745238500189),\n", 357 | " ('곡으로', 0.987120501433232),\n", 358 | " ('엑스', 0.9864101743091659),\n", 359 | " ('1위', 0.9845189730169617)]" 360 | ] 361 | }, 362 | "execution_count": 9, 363 | "metadata": {}, 364 | "output_type": "execute_result" 365 | } 366 | ], 367 | "source": [ 368 | "keywords[233]" 369 | ] 370 | }, 371 | { 372 | "cell_type": "markdown", 373 | "metadata": {}, 374 | "source": [ 375 | "특정 단어가 키워드에 포함된 cluster indices 를 저장하고, 해당 군집의 키워드를 출력합니다." 376 | ] 377 | }, 378 | { 379 | "cell_type": "code", 380 | "execution_count": 10, 381 | "metadata": { 382 | "scrolled": false 383 | }, 384 | "outputs": [ 385 | { 386 | "name": "stdout", 387 | "output_type": "stream", 388 | "text": [ 389 | "cluster#233 : 빅브레인 너무너무너무 신용재 오블리스 갓세븐 다비치 엠카운트다운 아이오아이 세븐 박진영 방탄소년단 트로피 완전체 고마워 산들 잠깐 중독성 펜타곤 정국 열창 그대 상큼 엠넷 타이틀곡 코드 챔피언 보컬 곡으로 엑스 1위\n", 390 | "cluster#298 : 다이아 에브리원 마법 고기 기희현 예능감 음악방송 한우 회식 댄스 대결 완전체 다리 아르바이트 3인 아이오아이 걸고 안무 플레이 6년 혼자 미스 출근 활동 타이틀곡 승리 활발 태양 아이돌 멤버들\n" 391 | ] 392 | } 393 | ], 394 | "source": [ 395 | "cluster_indices = []\n", 396 | "for cluster_idx, keyword in enumerate(keywords):\n", 397 | " keyword = ' '.join([w for w,_ in keyword])\n", 398 | " if '아이오아이' in keyword:\n", 399 | " print('cluster#{} : {}'.format(cluster_idx, keyword))\n", 400 | " cluster_indices.append(cluster_idx)" 401 | ] 402 | }, 403 | { 404 | "cell_type": "markdown", 405 | "metadata": {}, 406 | "source": [ 407 | "특정 단어를 stopwords 에 추가하면 키워드를 추출할 때 해당 단어를 제외하고 키워드를 추출합니다." 408 | ] 409 | }, 410 | { 411 | "cell_type": "code", 412 | "execution_count": 11, 413 | "metadata": {}, 414 | "outputs": [], 415 | "source": [ 416 | "keywords = proportion_keywords(\n", 417 | " kmeans.cluster_centers_,\n", 418 | " labels,\n", 419 | " index2word=idx_to_vocab,\n", 420 | " topk=30,\n", 421 | " candidates_topk=100,\n", 422 | " stopwords = {'아이오아이'}\n", 423 | ")" 424 | ] 425 | }, 426 | { 427 | "cell_type": "code", 428 | "execution_count": 12, 429 | "metadata": {}, 430 | "outputs": [ 431 | { 432 | "name": "stdout", 433 | "output_type": "stream", 434 | "text": [ 435 | "cluster#233 : 빅브레인 너무너무너무 신용재 오블리스 갓세븐 다비치 엠카운트다운 세븐 박진영 방탄소년단 트로피 완전체 고마워 산들 잠깐 중독성 펜타곤 정국 열창 그대 상큼 엠넷 타이틀곡 코드 챔피언 보컬 곡으로 엑스 1위 눈물\n", 436 | "cluster#298 : 다이아 에브리원 마법 고기 기희현 예능감 음악방송 한우 회식 댄스 대결 완전체 다리 아르바이트 3인 걸고 안무 플레이 6년 혼자 미스 출근 활동 타이틀곡 승리 활발 태양 아이돌 멤버들 먹고\n" 437 | ] 438 | } 439 | ], 440 | "source": [ 441 | "for cluster_idx in cluster_indices:\n", 442 | " keyword = keywords[cluster_idx]\n", 443 | " keyword = ' '.join([w for w,_ in keyword])\n", 444 | " print('cluster#{} : {}'.format(cluster_idx, keyword))" 445 | ] 446 | }, 447 | { 448 | "cell_type": "code", 449 | "execution_count": null, 450 | "metadata": {}, 451 | "outputs": [], 452 | "source": [] 453 | } 454 | ], 455 | "metadata": { 456 | "kernelspec": { 457 | "display_name": "Python 3", 458 | "language": "python", 459 | "name": "python3" 460 | }, 461 | "language_info": { 462 | "codemirror_mode": { 463 | "name": "ipython", 464 | "version": 3 465 | }, 466 | "file_extension": ".py", 467 | "mimetype": "text/x-python", 468 | "name": "python", 469 | "nbconvert_exporter": "python", 470 | "pygments_lexer": "ipython3", 471 | "version": "3.7.7" 472 | } 473 | }, 474 | "nbformat": 4, 475 | "nbformat_minor": 2 476 | } 477 | --------------------------------------------------------------------------------