├── .gitignore ├── LICENSE ├── README.md ├── data └── dummy ├── model.py ├── preprocess.py ├── requirements.txt ├── train.py └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | ./data/r52/*.txt 2 | .idea/* 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GraphSEAT: Fusing Global Domain Information and Local Semantic Information to Classify Financial Documents 2 | 3 | The implementation of graphSEAT in our paper: 4 | Mengzhen Fan, Dawei Cheng, Fangzhou Yang, et al. 5 | Fusing Global Domain Information and Local Semantic Information to Classify Financial Documents 6 | 7 | # Require 8 | 9 | python 3.6 10 | torch 0.4.0 11 | 12 | # Reproducing Results 13 | 14 | * Run preprocess.py 15 | * Run train.py 16 | 17 | 18 | # cite 19 | 20 | ``` 21 | @article{Fan2020FusingGD, 22 | title={Fusing Global Domain Information and Local Semantic Information to Classify Financial Documents}, 23 | author={Mengzhen Fan and Dawei Cheng and Fangzhou Yang and S. Luo and Y. Luo and W. Qian and Aoying Zhou}, 24 | journal={Proceedings of the 29th ACM International Conference on Information & Knowledge Management}, 25 | year={2020} 26 | } 27 | ``` 28 | 29 | 30 | -------------------------------------------------------------------------------- /data/dummy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/finint/graphSEAT/548d9d31d42658d203bce78acefc8209eaf97771/data/dummy -------------------------------------------------------------------------------- /model.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import torch 4 | import torch.nn as nn 5 | from torch.nn import init 6 | import torch.nn.functional as F 7 | from torch.autograd import Variable 8 | 9 | import random 10 | 11 | 12 | class SeqAttentionLayer(nn.Module): 13 | """implementation of sequence attention in paper: Hierarchical Attention Networks for Document Classification""" 14 | def __init__(self, input_dimension, attention_size, dropout=0., cuda=True): 15 | super(SeqAttentionLayer, self).__init__() 16 | self.cuda = cuda 17 | self.device = torch.device("cuda" if self.cuda and torch.cuda.is_available() else "cpu") 18 | self.attention_size = attention_size 19 | # sequence attention 20 | self.seq_attention = nn.Linear(input_dimension, attention_size) 21 | self.seq_attention = self.seq_attention.to(self.device) 22 | # context vector 23 | self.seq_context_vector = nn.Linear(attention_size, 1, bias=False).to(self.device) 24 | self.seq_context_vector = self.seq_context_vector.to(self.device) 25 | # self.dropout = nn.Dropout(dropout) 26 | 27 | def forward(self, input_sequence): 28 | assert len(input_sequence.size()) == 3 29 | seq_att = self.seq_attention(input_sequence.to(self.device)) 30 | seq_att = F.tanh(seq_att) 31 | seq_att = self.seq_context_vector(seq_att).squeeze() 32 | seq_weights = F.softmax(seq_att) 33 | weighted_sequence = (input_sequence * seq_weights.unsqueeze(dim=2)) 34 | weighted_sum = weighted_sequence.sum(dim=1) 35 | return weighted_sum, weighted_sequence 36 | 37 | 38 | class MeanAggregator(nn.Module): 39 | """ 40 | Aggregates a node's embeddings using mean of neighbors' embeddings 41 | """ 42 | 43 | def __init__(self, features, features_dim, cuda=False, gcn=False, att_size=100): 44 | """ 45 | Initializes the aggregator for a specific graph. 46 | 47 | features -- function mapping LongTensor of node ids to FloatTensor of feature values. 48 | cuda -- whether to use GPU 49 | gcn --- whether to perform concatenation GraphSAGE-style, or add self-loops GCN-style 50 | """ 51 | 52 | super(MeanAggregator, self).__init__() 53 | self.features = features 54 | self.feature_dim = features_dim 55 | self.gcn = gcn 56 | self.cuda = cuda 57 | self.device = torch.device("cuda" if self.cuda and torch.cuda.is_available() else "cpu") 58 | self.neigh_att = SeqAttentionLayer(input_dimension=features_dim, \ 59 | attention_size=att_size, dropout=0., cuda=cuda) 60 | def forward(self, nodes, to_neighs, num_sample=10): 61 | """ 62 | nodes --- list of nodes in a batch 63 | to_neighs --- list of sets, each set is the set of neighbors for node in batch 64 | num_sample --- number of neighbors to sample. No sampling if None. 65 | """ 66 | # Local pointers to functions (speed hack) 67 | _set = set 68 | if num_sample is not None: 69 | _sample = random.sample 70 | samp_neighs = [_set(_sample(to_neigh, num_sample,)) if len(to_neigh) >= num_sample else to_neigh for to_neigh in to_neighs] 71 | else: 72 | samp_neighs = to_neighs 73 | 74 | if self.gcn: 75 | samp_neighs = [samp_neigh + set([nodes[i]]) for i, samp_neigh in enumerate(samp_neighs)] 76 | unique_nodes_list = list(set.union(*samp_neighs)) 77 | unique_nodes = {n: i for i, n in enumerate(unique_nodes_list)} 78 | mask = Variable(torch.zeros(len(samp_neighs), len(unique_nodes))) 79 | column_indices = [unique_nodes[n] for samp_neigh in samp_neighs for n in samp_neigh] 80 | row_indices = [i for i in range(len(samp_neighs)) for j in range(len(samp_neighs[i]))] 81 | mask[row_indices, column_indices] = 1 82 | if self.cuda: 83 | mask = mask.cuda() 84 | num_neigh = mask.sum(1, keepdim=True) 85 | mask = mask.div(num_neigh) # 可以加权重在这里 86 | if self.cuda: 87 | embed_matrix = self.features(torch.LongTensor(unique_nodes_list)).cuda() 88 | else: 89 | embed_matrix = self.features(torch.LongTensor(unique_nodes_list)) 90 | neigh_unique_index = [[unique_nodes[i] for i in samp] for samp in samp_neighs] 91 | seq_neigh = Variable(torch.zeros(len(samp_neighs), num_sample, self.feature_dim)) 92 | for i, neigh in enumerate(neigh_unique_index): 93 | seq_neigh[i, :len(neigh)] = embed_matrix[neigh] 94 | weighted_sum, weighted_sequence = self.neigh_att(seq_neigh.to(self.device)) 95 | to_feats = F.relu(weighted_sum.div(num_neigh)) 96 | return F.dropout(to_feats, p =0.5) 97 | 98 | 99 | class Encoder(nn.Module): 100 | """ 101 | Encodes a node's using 'convolutional' GraphSage approach 102 | """ 103 | def __init__(self, features, feature_dim, 104 | embed_dim, adj_lists, aggregator, 105 | num_sample=10, 106 | base_model=None, gcn=False, cuda=False): 107 | super(Encoder, self).__init__() 108 | 109 | self.features = features 110 | self.feat_dim = feature_dim 111 | self.adj_lists = adj_lists 112 | self.aggregator = aggregator 113 | self.num_sample = num_sample 114 | if base_model != None: 115 | self.base_model = base_model 116 | 117 | self.gcn = gcn 118 | self.embed_dim = embed_dim 119 | self.cuda = cuda 120 | self.device = torch.device("cuda" if self.cuda and torch.cuda.is_available() else "cpu") 121 | self.aggregator.cuda = cuda 122 | self.weight = nn.Parameter(torch.FloatTensor(\ 123 | embed_dim, self.feat_dim if self.gcn else 2 * self.feat_dim).to(self.device), requires_grad=True) 124 | init.xavier_uniform(self.weight) 125 | 126 | def forward(self, nodes): 127 | """ 128 | Generates embeddings for a batch of nodes. 129 | nodes -- list of nodes 130 | """ 131 | neigh_feats = self.aggregator.forward(nodes, [self.adj_lists[int(node)] for node in nodes], 132 | self.num_sample) 133 | if not self.gcn: 134 | if self.cuda: 135 | self_feats = self.features(torch.LongTensor(nodes)).to(self.device) 136 | else: 137 | self_feats = self.features(torch.LongTensor(nodes)) 138 | combined = torch.cat([self_feats, neigh_feats], dim=1) 139 | else: 140 | combined = neigh_feats 141 | combined = F.relu(self.weight.mm(combined.t())) 142 | return combined 143 | 144 | 145 | class SequenceGraphAtt(nn.Module): 146 | def __init__(self, features_layer, adj_lists, num_classes, enc1_hidden, enc2_hidden, rnn_hidden,\ 147 | num_sample1, num_sample2, embedding_layer, cuda=False, dropout=0.5, gcn=True, att_size=64): 148 | super(SequenceGraphAtt, self).__init__() 149 | agg1 = MeanAggregator(features_layer, features_dim=features_layer.embedding_dim, cuda=cuda, att_size=att_size) 150 | enc1 = Encoder(features=features_layer, feature_dim=features_layer.embedding_dim, embed_dim=enc1_hidden, 151 | adj_lists=adj_lists, aggregator=agg1, gcn=gcn, cuda=cuda) 152 | agg2 = MeanAggregator(lambda nodes: enc1(nodes).t(), features_dim=enc1.embed_dim, cuda=cuda, att_size=att_size) 153 | enc2 = Encoder(lambda nodes: enc1(nodes).t(), feature_dim=enc1.embed_dim, embed_dim=enc2_hidden, 154 | adj_lists=adj_lists, aggregator=agg2, base_model=enc1, gcn=gcn, cuda=cuda) 155 | enc1.num_sample = num_sample1 156 | enc2.num_sample = num_sample2 157 | 158 | self.cuda = cuda 159 | self.device = torch.device("cuda" if self.cuda and torch.cuda.is_available() else "cpu") 160 | 161 | # layers 162 | self.embedding_layer = embedding_layer 163 | self.enc = enc2 164 | self.rnn_hidden = rnn_hidden 165 | self.rnn_layer = nn.GRU(input_size=features_layer.embedding_dim, hidden_size=rnn_hidden, num_layers=2, 166 | batch_first=True, bidirectional=True, dropout=dropout) 167 | self.att = SeqAttentionLayer(input_dimension=self.enc.embed_dim, attention_size=att_size, dropout=0.5, cuda=cuda) 168 | self.rnn_layer = self.rnn_layer.to(self.device) 169 | 170 | # weights 171 | self.weight1 = nn.Parameter(torch.FloatTensor(self.rnn_layer.hidden_size*2, self.enc.embed_dim).to(self.device),\ 172 | requires_grad=True) 173 | init.xavier_uniform(self.weight1) 174 | self.weight2 = nn.Parameter(torch.FloatTensor(self.enc.embed_dim, num_classes).to(self.device), requires_grad=True) 175 | init.xavier_uniform(self.weight2) 176 | 177 | def forward(self, nodes, seq_input): 178 | input_embedded = self.embedding_layer(seq_input.to(self.device)) 179 | rnn_output, rnn_hidden = self.rnn_layer(input_embedded) 180 | # concatenate normal RNN's last time step(-1) output and reverse RNN's last time step(0) output 181 | rnn_embeds = torch.cat([rnn_output[:, -1, :self.rnn_hidden], rnn_output[:, 0, self.rnn_hidden:]], dim=1) 182 | rnn_embeds = F.dropout(rnn_embeds, p=0.5) #.mm(self.weight1) 183 | graph_embeds = self.enc(nodes) 184 | combined_embeds, _ = self.att(torch.cat([rnn_embeds.unsqueeze(dim=1), graph_embeds.t().unsqueeze(dim=1)], dim=1)) 185 | 186 | scores = combined_embeds.mm(self.weight2) 187 | return scores 188 | 189 | -------------------------------------------------------------------------------- /preprocess.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import nltk 4 | import re 5 | import pickle 6 | from nltk.corpus import stopwords 7 | from nltk.wsd import lesk 8 | from nltk.corpus import wordnet as wn 9 | import sys 10 | 11 | import os 12 | import random 13 | import numpy as np 14 | import pickle as pkl 15 | # import networkx as nx 16 | import scipy.sparse as sp 17 | from math import log 18 | from sklearn import svm 19 | from nltk.corpus import wordnet as wn 20 | from sklearn.feature_extraction.text import TfidfVectorizer 21 | from scipy.spatial.distance import cosine 22 | from utils import * 23 | 24 | # sys.path.append('../') 25 | nltk.download('stopwords') 26 | stop_words = set(stopwords.words('english')) 27 | 28 | """ 29 | Original taken from https://github.com/yao8839836/text_gcn.git 30 | """ 31 | 32 | source_data_dir = './data/' 33 | dataset = "R52" 34 | doc_content_list = [] 35 | with open(source_data_dir + "corpus/" + dataset +'.txt', 'rb') as f: 36 | for line in f.readlines(): 37 | doc_content_list.append(line.strip().decode('latin1')) 38 | 39 | word_freq = {} # to remove rare words 40 | for doc_content in doc_content_list: 41 | temp = clean_str(doc_content) 42 | words = temp.split() 43 | for word in words: 44 | if word in word_freq: 45 | word_freq[word] += 1 46 | else: 47 | word_freq[word] = 1 48 | 49 | clean_docs = [] 50 | for doc_content in doc_content_list: 51 | temp = clean_str(doc_content) 52 | words = temp.split() 53 | doc_words = [] 54 | for word in words: 55 | # word not in stop_words and word_freq[word] >= 5 56 | if dataset == 'mr': 57 | doc_words.append(word) 58 | elif word not in stop_words and word_freq[word] >= 5: 59 | doc_words.append(word) 60 | 61 | doc_str = ' '.join(doc_words).strip() 62 | #if doc_str == '': 63 | #doc_str = temp 64 | clean_docs.append(doc_str) 65 | 66 | clean_corpus_str = '\n'.join(clean_docs) 67 | with open(source_data_dir + dataset + '.clean.txt', 'w') as f: 68 | f.write(clean_corpus_str) 69 | 70 | min_len = 10000 71 | aver_len = 0 72 | max_len = 0 73 | 74 | #with open('../data/wiki_long_abstracts_en_text.txt', 'r') as f: 75 | with open(source_data_dir + dataset + '.clean.txt', 'rb') as f: 76 | lines = f.readlines() 77 | for line in lines: 78 | line = line.strip() 79 | temp = line.split() 80 | aver_len = aver_len + len(temp) 81 | if len(temp) < min_len: 82 | min_len = len(temp) 83 | if len(temp) > max_len: 84 | max_len = len(temp) 85 | 86 | aver_len = 1.0 * aver_len / len(lines) 87 | print('Min_len : ' + str(min_len)) 88 | print('Max_len : ' + str(max_len)) 89 | print('Average_len : ' + str(aver_len)) 90 | 91 | word_embeddings_dim = 300 92 | word_vector_map = {} 93 | 94 | # shulffing 95 | doc_name_list = [] 96 | doc_train_list = [] 97 | doc_test_list = [] 98 | 99 | with open(source_data_dir + dataset + '.txt', 'r') as f: 100 | lines = f.readlines() 101 | for line in lines: 102 | doc_name_list.append(line.strip()) 103 | temp = line.split("\t") 104 | if temp[1].find('test') != -1: 105 | doc_test_list.append(line.strip()) 106 | elif temp[1].find('train') != -1: 107 | doc_train_list.append(line.strip()) 108 | 109 | 110 | doc_content_list = [] 111 | with open(source_data_dir + dataset + '.clean.txt', 'r') as f: 112 | lines = f.readlines() 113 | for line in lines: 114 | doc_content_list.append(line.strip()) 115 | 116 | train_ids = [] 117 | for train_name in doc_train_list: 118 | train_id = doc_name_list.index(train_name) 119 | train_ids.append(train_id) 120 | # random.shuffle(train_ids) 121 | 122 | train_ids_str = '\n'.join(str(index) for index in train_ids) 123 | with open(source_data_dir + dataset + '.train.index', 'w') as f: 124 | f.write(train_ids_str) 125 | 126 | 127 | test_ids = [] 128 | for test_name in doc_test_list: 129 | test_id = doc_name_list.index(test_name) 130 | test_ids.append(test_id) 131 | # random.shuffle(test_ids) 132 | 133 | test_ids_str = '\n'.join(str(index) for index in test_ids) 134 | with open(source_data_dir + dataset + '.test.index', 'w') as f: 135 | f.write(test_ids_str) 136 | 137 | ids = train_ids + test_ids 138 | print(len(ids)) 139 | 140 | shuffle_doc_name_list = [] 141 | shuffle_doc_words_list = [] 142 | for id in ids: 143 | shuffle_doc_name_list.append(doc_name_list[int(id)]) 144 | shuffle_doc_words_list.append(doc_content_list[int(id)]) 145 | shuffle_doc_name_str = '\n'.join(shuffle_doc_name_list) 146 | shuffle_doc_words_str = '\n'.join(shuffle_doc_words_list) 147 | 148 | # build vocab 149 | word_freq = {} 150 | word_set = set() 151 | for doc_words in shuffle_doc_words_list: 152 | words = doc_words.split() 153 | for word in words: 154 | word_set.add(word) 155 | if word in word_freq: 156 | word_freq[word] += 1 157 | else: 158 | word_freq[word] = 1 159 | 160 | vocab = list(word_set) 161 | vocab_size = len(vocab) 162 | 163 | word_doc_list = {} 164 | 165 | for i in range(len(shuffle_doc_words_list)): 166 | doc_words = shuffle_doc_words_list[i] 167 | words = doc_words.split() 168 | appeared = set() 169 | for word in words: 170 | if word in appeared: 171 | continue 172 | if word in word_doc_list: 173 | doc_list = word_doc_list[word] 174 | doc_list.append(i) 175 | word_doc_list[word] = doc_list 176 | else: 177 | word_doc_list[word] = [i] 178 | appeared.add(word) 179 | 180 | word_doc_freq = {} 181 | for word, doc_list in word_doc_list.items(): 182 | word_doc_freq[word] = len(doc_list) 183 | 184 | word_id_map = {} 185 | for i in range(vocab_size): 186 | word_id_map[vocab[i]] = i 187 | 188 | vocab_str = '\n'.join(vocab) 189 | 190 | with open(source_data_dir + 'corpus/' + dataset + '_vocab.txt', 'w') as f: 191 | f.write(vocab_str) 192 | 193 | # label list 194 | label_set = set() 195 | for doc_meta in shuffle_doc_name_list: 196 | temp = doc_meta.split('\t') 197 | label_set.add(temp[2]) 198 | label_list = list(label_set) 199 | 200 | label_list_str = '\n'.join(label_list) 201 | with open(source_data_dir + 'corpus/' + dataset + '_labels.txt', 'w') as f: 202 | f.write(label_list_str) 203 | 204 | 205 | # x: feature vectors of training docs, no initial features 206 | # slect 90% training set 207 | train_size = len(train_ids) 208 | val_size = int(0.1 * train_size) 209 | real_train_size = train_size - val_size # - int(0.5 * train_size) 210 | # different training rates 211 | 212 | real_train_doc_names = shuffle_doc_name_list[:real_train_size] 213 | real_train_doc_names_str = '\n'.join(real_train_doc_names) 214 | 215 | with open(source_data_dir + dataset + '.real_train.name', 'w') as f: 216 | f.write(real_train_doc_names_str) 217 | 218 | 219 | row_x = [] 220 | col_x = [] 221 | data_x = [] 222 | for i in range(real_train_size): 223 | doc_vec = np.array([0.0 for k in range(word_embeddings_dim)]) 224 | doc_words = shuffle_doc_words_list[i] 225 | words = doc_words.split() 226 | doc_len = len(words) 227 | for word in words: 228 | if word in word_vector_map: 229 | word_vector = word_vector_map[word] 230 | # print(doc_vec) 231 | # print(np.array(word_vector)) 232 | doc_vec = doc_vec + np.array(word_vector) 233 | 234 | for j in range(word_embeddings_dim): 235 | row_x.append(i) 236 | col_x.append(j) 237 | # np.random.uniform(-0.25, 0.25) 238 | data_x.append(doc_vec[j] / doc_len) # doc_vec[j]/ doc_len 239 | 240 | 241 | # x = sp.csr_matrix((real_train_size, word_embeddings_dim), dtype=np.float32) 242 | x = sp.csr_matrix((data_x, (row_x, col_x)), shape=( 243 | real_train_size, word_embeddings_dim)) 244 | 245 | y = [] 246 | for i in range(real_train_size): 247 | doc_meta = shuffle_doc_name_list[i] 248 | temp = doc_meta.split('\t') 249 | label = temp[2] 250 | one_hot = [0 for l in range(len(label_list))] 251 | label_index = label_list.index(label) 252 | one_hot[label_index] = 1 253 | y.append(one_hot) 254 | y = np.array(y) 255 | print(y) 256 | 257 | # tx: feature vectors of test docs, no initial features 258 | test_size = len(test_ids) 259 | 260 | row_tx = [] 261 | col_tx = [] 262 | data_tx = [] 263 | for i in range(test_size): 264 | doc_vec = np.array([0.0 for k in range(word_embeddings_dim)]) 265 | doc_words = shuffle_doc_words_list[i + train_size] 266 | words = doc_words.split() 267 | doc_len = len(words) 268 | for word in words: 269 | if word in word_vector_map: 270 | word_vector = word_vector_map[word] 271 | doc_vec = doc_vec + np.array(word_vector) 272 | 273 | for j in range(word_embeddings_dim): 274 | row_tx.append(i) 275 | col_tx.append(j) 276 | # np.random.uniform(-0.25, 0.25) 277 | data_tx.append(doc_vec[j] / doc_len) # doc_vec[j] / doc_len 278 | 279 | # tx = sp.csr_matrix((test_size, word_embeddings_dim), dtype=np.float32) 280 | tx = sp.csr_matrix((data_tx, (row_tx, col_tx)), 281 | shape=(test_size, word_embeddings_dim)) 282 | 283 | ty = [] 284 | for i in range(test_size): 285 | doc_meta = shuffle_doc_name_list[i + train_size] 286 | temp = doc_meta.split('\t') 287 | label = temp[2] 288 | one_hot = [0 for l in range(len(label_list))] 289 | label_index = label_list.index(label) 290 | one_hot[label_index] = 1 291 | ty.append(one_hot) 292 | ty = np.array(ty) 293 | print(ty) 294 | 295 | # allx: the the feature vectors of both labeled and unlabeled training instances 296 | # (a superset of x) 297 | # unlabeled training instances -> words 298 | 299 | word_vectors = np.random.uniform(-0.01, 0.01, 300 | (vocab_size, word_embeddings_dim)) 301 | 302 | for i in range(len(vocab)): 303 | word = vocab[i] 304 | if word in word_vector_map: 305 | vector = word_vector_map[word] 306 | word_vectors[i] = vector 307 | 308 | row_allx = [] 309 | col_allx = [] 310 | data_allx = [] 311 | 312 | for i in range(train_size): 313 | doc_vec = np.array([0.0 for k in range(word_embeddings_dim)]) 314 | doc_words = shuffle_doc_words_list[i] 315 | words = doc_words.split() 316 | doc_len = len(words) 317 | for word in words: 318 | if word in word_vector_map: 319 | word_vector = word_vector_map[word] 320 | doc_vec = doc_vec + np.array(word_vector) 321 | 322 | for j in range(word_embeddings_dim): 323 | row_allx.append(int(i)) 324 | col_allx.append(j) 325 | # np.random.uniform(-0.25, 0.25) 326 | data_allx.append(doc_vec[j] / doc_len) # doc_vec[j]/doc_len 327 | for i in range(vocab_size): 328 | for j in range(word_embeddings_dim): 329 | row_allx.append(int(i + train_size)) 330 | col_allx.append(j) 331 | data_allx.append(word_vectors.item((i, j))) 332 | 333 | 334 | row_allx = np.array(row_allx) 335 | col_allx = np.array(col_allx) 336 | data_allx = np.array(data_allx) 337 | 338 | allx = sp.csr_matrix( 339 | (data_allx, (row_allx, col_allx)), shape=(train_size + vocab_size, word_embeddings_dim)) 340 | 341 | ally = [] 342 | for i in range(train_size): 343 | doc_meta = shuffle_doc_name_list[i] 344 | temp = doc_meta.split('\t') 345 | label = temp[2] 346 | one_hot = [0 for l in range(len(label_list))] 347 | label_index = label_list.index(label) 348 | one_hot[label_index] = 1 349 | ally.append(one_hot) 350 | 351 | for i in range(vocab_size): 352 | one_hot = [0 for l in range(len(label_list))] 353 | ally.append(one_hot) 354 | 355 | ally = np.array(ally) 356 | 357 | print(x.shape, y.shape, tx.shape, ty.shape, allx.shape, ally.shape) 358 | 359 | 360 | ''' 361 | Doc word heterogeneous graph 362 | ''' 363 | 364 | # word co-occurence with context windows 365 | window_size = 20 366 | windows = [] 367 | 368 | for doc_words in shuffle_doc_words_list: 369 | words = doc_words.split() 370 | length = len(words) 371 | if length <= window_size: 372 | windows.append(words) 373 | else: 374 | # print(length, length - window_size + 1) 375 | for j in range(length - window_size + 1): 376 | window = words[j: j + window_size] 377 | windows.append(window) 378 | # print(window) 379 | 380 | 381 | word_window_freq = {} 382 | for window in windows: 383 | appeared = set() 384 | for i in range(len(window)): 385 | if window[i] in appeared: 386 | continue 387 | if window[i] in word_window_freq: 388 | word_window_freq[window[i]] += 1 389 | else: 390 | word_window_freq[window[i]] = 1 391 | appeared.add(window[i]) 392 | 393 | word_pair_count = {} 394 | for window in windows: 395 | for i in range(1, len(window)): 396 | for j in range(0, i): 397 | word_i = window[i] 398 | word_i_id = word_id_map[word_i] 399 | word_j = window[j] 400 | word_j_id = word_id_map[word_j] 401 | if word_i_id == word_j_id: 402 | continue 403 | word_pair_str = str(word_i_id) + ',' + str(word_j_id) 404 | if word_pair_str in word_pair_count: 405 | word_pair_count[word_pair_str] += 1 406 | else: 407 | word_pair_count[word_pair_str] = 1 408 | # two orders 409 | word_pair_str = str(word_j_id) + ',' + str(word_i_id) 410 | if word_pair_str in word_pair_count: 411 | word_pair_count[word_pair_str] += 1 412 | else: 413 | word_pair_count[word_pair_str] = 1 414 | 415 | row = [] 416 | col = [] 417 | weight = [] 418 | 419 | # pmi as weights 420 | 421 | num_window = len(windows) 422 | 423 | for key in word_pair_count: 424 | temp = key.split(',') 425 | i = int(temp[0]) 426 | j = int(temp[1]) 427 | count = word_pair_count[key] 428 | word_freq_i = word_window_freq[vocab[i]] 429 | word_freq_j = word_window_freq[vocab[j]] 430 | pmi = log((1.0 * count / num_window) / 431 | (1.0 * word_freq_i * word_freq_j/(num_window * num_window))) 432 | if pmi <= 0: 433 | continue 434 | row.append(train_size + i) 435 | col.append(train_size + j) 436 | weight.append(pmi) 437 | 438 | 439 | # word vector cosine similarity as weights 440 | 441 | ''' 442 | for i in range(vocab_size): 443 | for j in range(vocab_size): 444 | if vocab[i] in word_vector_map and vocab[j] in word_vector_map: 445 | vector_i = np.array(word_vector_map[vocab[i]]) 446 | vector_j = np.array(word_vector_map[vocab[j]]) 447 | similarity = 1.0 - cosine(vector_i, vector_j) 448 | if similarity > 0.9: 449 | print(vocab[i], vocab[j], similarity) 450 | row.append(train_size + i) 451 | col.append(train_size + j) 452 | weight.append(similarity) 453 | ''' 454 | # doc word frequency 455 | doc_word_freq = {} 456 | 457 | for doc_id in range(len(shuffle_doc_words_list)): 458 | doc_words = shuffle_doc_words_list[doc_id] 459 | words = doc_words.split() 460 | for word in words: 461 | word_id = word_id_map[word] 462 | doc_word_str = str(doc_id) + ',' + str(word_id) 463 | if doc_word_str in doc_word_freq: 464 | doc_word_freq[doc_word_str] += 1 465 | else: 466 | doc_word_freq[doc_word_str] = 1 467 | 468 | for i in range(len(shuffle_doc_words_list)): 469 | doc_words = shuffle_doc_words_list[i] 470 | words = doc_words.split() 471 | doc_word_set = set() 472 | for word in words: 473 | if word in doc_word_set: 474 | continue 475 | j = word_id_map[word] 476 | key = str(i) + ',' + str(j) 477 | freq = doc_word_freq[key] 478 | if i < train_size: 479 | row.append(i) 480 | else: 481 | row.append(i + vocab_size) 482 | col.append(train_size + j) 483 | idf = log(1.0 * len(shuffle_doc_words_list) / 484 | word_doc_freq[vocab[j]]) 485 | weight.append(freq * idf) 486 | doc_word_set.add(word) 487 | 488 | node_size = train_size + vocab_size + test_size 489 | adj = sp.csr_matrix( 490 | (weight, (row, col)), shape=(node_size, node_size)) 491 | 492 | # dump objects 493 | with open(source_data_dir + "ind.{}.x".format(dataset), 'wb') as f: 494 | pkl.dump(x, f) 495 | 496 | with open(source_data_dir + "ind.{}.y".format(dataset), 'wb') as f: 497 | pkl.dump(y, f) 498 | 499 | with open(source_data_dir + "ind.{}.tx".format(dataset), 'wb') as f: 500 | pkl.dump(tx, f) 501 | 502 | with open(source_data_dir + "ind.{}.ty".format(dataset), 'wb') as f: 503 | pkl.dump(ty, f) 504 | 505 | with open(source_data_dir + "ind.{}.allx".format(dataset), 'wb') as f: 506 | pkl.dump(allx, f) 507 | 508 | with open(source_data_dir + "ind.{}.ally".format(dataset), 'wb') as f: 509 | pkl.dump(ally, f) 510 | 511 | with open(source_data_dir + "ind.{}.adj".format(dataset), 'wb') as f: 512 | pkl.dump(adj, f) 513 | 514 | print("build finish") 515 | 516 | with open("./data/model_glove300d.pkl", "rb") as f: 517 | model = pickle.load(f) 518 | 519 | X_corpus = shuffle_doc_words_list 520 | # 构造embedding matrix 521 | from keras.preprocessing.text import Tokenizer 522 | tokenizer = Tokenizer(char_level=True, num_words=50000, lower=False) 523 | 524 | data = [text.split() for text in X_corpus] 525 | tokenizer.fit_on_texts(texts=data) 526 | X_idx = texts_to_idx(data, tokenizer, max_sentence_length=150) 527 | embedding_matrix = get_embedding_matrix(model, tokenizer) 528 | X_idx = np.concatenate([X_idx[:train_size], np.zeros(shape=(vocab_size, 150)), X_idx[train_size:]]) 529 | 530 | adj, _, labels, idx_train, idx_test, train_size, test_size = load_corpus("R52") 531 | 532 | cnt = 0 533 | def get_w2v(word , model): 534 | global cnt 535 | vec = np.zeros(model.vector_size) 536 | if word in model.vocab: 537 | return np.array(model[word]) 538 | else: 539 | cnt += 1 540 | return vec 541 | 542 | def get_w2v_avg(words_list, model): 543 | cnt = 0 544 | vector = np.zeros(model.vector_size) 545 | for word in words_list: 546 | if word in model.vocab: 547 | vector += model[word] 548 | cnt += 1 549 | if cnt == 0: 550 | return vector 551 | else: 552 | return vector/cnt 553 | 554 | vector_vocab = np.array([get_w2v(word, model) for word in vocab]) 555 | vector_text = np.array([get_w2v_avg(word.split(), model) for word in X_corpus]) 556 | features = np.concatenate([vector_text[:train_size], vector_vocab, vector_text[train_size:]]) 557 | 558 | with open("./data/r52/r52_input_base.pkl", "wb") as f: 559 | pkg = (adj, features, labels, idx_train, idx_test) 560 | pickle.dump(pkg, f) 561 | 562 | with open("./data/r52/r52_sequence.pkl", "wb") as f: 563 | pickle.dump((X_idx, embedding_matrix), f) 564 | 565 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | alembic==1.0.8 2 | async-generator==1.10 3 | attrs==19.3.0 4 | Automat==20.2.0 5 | backcall==0.1.0 6 | bleach==2.1.3 7 | certifi==2019.3.9 8 | certipy==0.1.3 9 | cffi==1.14.0 10 | chardet==3.0.4 11 | constantly==15.1.0 12 | cryptography==2.8 13 | cssselect==1.1.0 14 | decorator==4.4.0 15 | defusedxml==0.6.0 16 | elasticsearch==7.9.1 17 | entrypoints==0.2.3 18 | html5lib==1.0.1 19 | hyperlink==20.0.1 20 | idna==2.8 21 | importlib-metadata==1.5.0 22 | incremental==17.5.0 23 | ipykernel==5.1.0 24 | ipython==7.4.0 25 | ipython-genutils==0.2.0 26 | ipywidgets==7.4.2 27 | itemadapter==0.1.0 28 | itemloaders==1.0.3 29 | jedi==0.13.3 30 | Jinja2==2.10 31 | jmespath==0.10.0 32 | json5==0.9.1 33 | jsonschema==3.2.0 34 | jupyter==1.0.0 35 | jupyter-client==6.0.0 36 | jupyter-console==6.0.0 37 | jupyter-contrib-core==0.3.3 38 | jupyter-contrib-nbextensions==0.5.1 39 | jupyter-core==4.6.3 40 | jupyter-highlight-selected-word==0.2.0 41 | jupyter-latex-envs==1.4.6 42 | jupyter-nbextensions-configurator==0.4.1 43 | jupyter-server==0.1.1 44 | jupyter-telemetry==0.0.5 45 | jupyterhub==1.1.0 46 | jupyterhub-systemdspawner==0.13 47 | jupyterlab==1.2.0 48 | jupyterlab-pygments==0.1.0 49 | jupyterlab-server==1.0.6 50 | lxml==4.2.5 51 | Mako==1.0.8 52 | MarkupSafe==1.1.1 53 | mistune==0.8.3 54 | nbconvert==5.6.1 55 | nbformat==4.4.0 56 | notebook==5.7.7 57 | numpy==1.18.4 58 | oauthlib==3.1.0 59 | pamela==1.0.0 60 | pandas==1.0.3 61 | pandocfilters==1.4.2 62 | parsel==1.6.0 63 | parso==0.3.4 64 | pexpect==4.6.0 65 | pickleshare==0.7.5 66 | prometheus-client==0.6.0 67 | prompt-toolkit==2.0.9 68 | Protego==0.1.16 69 | ptyprocess==0.6.0 70 | pyasn1==0.4.8 71 | pyasn1-modules==0.2.8 72 | pycparser==2.20 73 | PyDispatcher==2.0.5 74 | pyflakes==2.0.0 75 | Pygments==2.5.2 76 | PyHamcrest==2.0.2 77 | pyOpenSSL==19.1.0 78 | pyrsistent==0.15.7 79 | python-dateutil==2.8.0 80 | python-editor==1.0.4 81 | python-json-logger==0.1.11 82 | python-oauth2==1.1.0 83 | pytz==2020.1 84 | PyYAML==3.13 85 | pyzmq==18.0.1 86 | qtconsole==4.4.3 87 | queuelib==1.5.0 88 | redis==2.10.6 89 | requests==2.21.0 90 | ruamel.yaml==0.16.10 91 | ruamel.yaml.clib==0.2.0 92 | scikit-learn==0.20.1 93 | scipy==1.5.2 94 | Scrapy==2.3.0 95 | Send2Trash==1.5.0 96 | service-identity==18.1.0 97 | simhash==1.11.0 98 | simplegeneric==0.8.1 99 | six==1.12.0 100 | SQLAlchemy==1.3.1 101 | terminado==0.8.1 102 | testpath==0.3.1 103 | tornado==5.1.1 104 | traitlets==4.3.2 105 | Twisted==20.3.0 106 | urllib3==1.24.1 107 | voila==0.1.20 108 | w3lib==1.22.0 109 | wcwidth==0.1.7 110 | webencodings==0.5.1 111 | widgetsnbextension==3.4.2 112 | xgboost==1.2.0 113 | zipp==3.0.0 114 | zope.interface==5.1.0 115 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from utils import * 4 | import os 5 | import time 6 | import random 7 | 8 | import torch 9 | import torch.nn as nn 10 | import torch.optim as optim 11 | from model import SequenceGraphAtt 12 | 13 | 14 | class CONFIG_PARAS(): 15 | def __init__(self): 16 | # 参数等常量存放 17 | self.data_dir = "./data/r52" 18 | self.data_graph_path = self.data_dir + "/r52_input_base.pkl" 19 | self.data_seqence_path = self.data_dir + "/r52_sequence.pkl" 20 | self.data_reduce_size = 1. # 训练数据占总训练集合比例 21 | 22 | self.random_seed = 42 23 | self.hidden_enc1 = 100 24 | self.hidden_enc2 = 200 25 | self.num_sample1 = 20 26 | self.num_sample2 = 20 27 | self.hidden_graph = None 28 | self.hidden_rnn = 100 29 | self.att_size = 100 # graph attention size 30 | 31 | self.epochs = 64 32 | self.lr = 0.005 33 | self.weight_decay = 0.0 34 | self.batch_size = 64 35 | 36 | self.cuda = True 37 | self.device = torch.device("cuda" if self.cuda and torch.cuda.is_available() else "cpu") 38 | 39 | 40 | if __name__ == "__main__": 41 | os.environ["CUDA_VISIBLE_DEVICES"] = "0" 42 | args = CONFIG_PARAS() 43 | 44 | # load features 45 | adj, features, labels, idx_train, idx_test = load_file(data_path=args.data_graph_path) 46 | X_idx, embedding_matrix = load_file(data_path=args.data_seqence_path) 47 | 48 | # random.seed(10) 49 | idx_val = np.array(random.sample(idx_train, int(len(idx_train) * 0.1))) 50 | idx_train = np.array(list(set(idx_train) - set(idx_val))) 51 | idx_test = idx_test 52 | 53 | # 邻接矩阵 处理 54 | # adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj) 55 | adj_lists = get_adj_list(preprocess_adj(adj)) 56 | args.feature_dim = features.shape[1] 57 | args.num_classes = labels.shape[1] 58 | features_layer = torch.nn.Embedding(num_embeddings=features.shape[0], embedding_dim=args.feature_dim) 59 | features_layer.weight = nn.Parameter(torch.FloatTensor(features), requires_grad=False) 60 | embedding_matrix = torch.FloatTensor(embedding_matrix) 61 | embedding_layer = nn.Embedding(embedding_matrix.shape[0], embedding_matrix.shape[1]) 62 | embedding_layer.weight = nn.Parameter(embedding_matrix.to(args.device), requires_grad=False) 63 | X_idx = torch.LongTensor(X_idx) 64 | labels = torch.FloatTensor(labels).to(args.device) 65 | 66 | best_acc_list = [] 67 | for i in range(10): 68 | model = SequenceGraphAtt(features_layer, adj_lists, num_classes=args.num_classes, enc1_hidden=args.hidden_enc1, \ 69 | enc2_hidden=args.hidden_enc2, rnn_hidden=args.hidden_rnn, num_sample1=args.num_sample1, \ 70 | num_sample2=args.num_sample2, embedding_layer=embedding_layer, cuda=args.cuda, 71 | dropout=0.5, att_size=64) 72 | optimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr, 73 | weight_decay=args.weight_decay) 74 | # 学习率下降 75 | # scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=1) 76 | scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.5, verbose=True, 77 | patience=3) 78 | # to tensor 79 | best_hist = (np.inf, 0) 80 | stop_count, patient = 0, 5 81 | for epoch in range(1, args.epochs + 1): 82 | t = time.time() 83 | loss_train, acc_train = train(model, optimizer, X_idx, labels, idx_train, \ 84 | batch_size=args.batch_size) 85 | loss_val, acc_val = test_on_batch(model, X_idx, idx_val) 86 | loss_test, acc_test = test_on_batch(model, X_idx, idx_test) 87 | scheduler.step(loss_val) 88 | if loss_val <= best_hist[0]: 89 | best_hist = (loss_val, acc_val) 90 | # model, optimizer, path, epoch, loss 91 | model_save_path = args.data_dir + "/ckpt/seq_dual_att" 92 | save_model(model=model, optimizer=optimizer, path=model_save_path, epoch=epoch, loss=loss_val) 93 | stop_count = 0 94 | else: 95 | stop_count += 1 96 | 97 | print('Epoch: {:04d}'.format(epoch), 98 | 'loss_train: {:.4f}'.format(loss_train), 99 | 'acc_train: {:.4f}'.format(acc_train), 100 | 'loss_val: {:.4f}'.format(loss_val), 101 | 'acc_val: {:.4f}'.format(acc_val), 102 | 'loss_test: {:.4f}'.format(loss_test), 103 | 'acc_test: {:.4f}'.format(acc_test), 104 | 'time: {:.4f}s'.format(time.time() - t)) 105 | if stop_count > patient: 106 | break 107 | 108 | epoch, loss, path, model, optimizer = load_model(model_save_path + "_ckpt.pt", model, optimizer) 109 | data_loader = DataLoader(idx_test, batch_size=64, shuffle=False) 110 | with torch.no_grad(): 111 | model.eval() 112 | output_test = [] 113 | for idx_batch in data_loader: 114 | output = model(idx_batch, X_idx[idx_batch]) 115 | output_test.append(output) 116 | output_test = torch.cat(output_test, dim=0) 117 | preds_test = torch.sigmoid(output_test) 118 | loss_test = F.binary_cross_entropy(preds_test, labels[idx_test]) 119 | acc_test = accuracy(preds_test, labels[idx_test], detail=True) 120 | print("best model result on test\n loss:{:.4f} acc{:.4f}".format(loss_test, acc_test)) 121 | 122 | best_acc_list.append(acc_test) -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import re 4 | import sys 5 | import pickle as pkl 6 | import numpy as np 7 | 8 | import torch 9 | import scipy.sparse as sp 10 | from torch.utils.data import DataLoader 11 | import torch.nn.functional as F 12 | from sklearn.metrics import pairwise_distances 13 | from sklearn import metrics 14 | 15 | from sklearn.model_selection import train_test_split 16 | 17 | 18 | def clean_str(string): 19 | """ 20 | Tokenization/string cleaning for all datasets. 21 | Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py 22 | """ 23 | string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) 24 | string = re.sub(r"\'s", " \'s", string) 25 | string = re.sub(r"\'ve", " \'ve", string) 26 | string = re.sub(r"n\'t", " n\'t", string) 27 | string = re.sub(r"\'re", " \'re", string) 28 | string = re.sub(r"\'d", " \'d", string) 29 | string = re.sub(r"\'ll", " \'ll", string) 30 | string = re.sub(r",", " , ", string) 31 | string = re.sub(r"!", " ! ", string) 32 | string = re.sub(r"\(", " \( ", string) 33 | string = re.sub(r"\)", " \) ", string) 34 | string = re.sub(r"\?", " \? ", string) 35 | string = re.sub(r"\s{2,}", " ", string) 36 | return string.strip().lower() 37 | 38 | 39 | def get_embedding_matrix(vec_model, tokenizer): 40 | # values of word_index range from 1 to len 41 | # embedding_matrix = np.random.random((len(tokenizer.word_index) + 1, vec_model.dim)) 42 | # model.vector_size 43 | embedding_matrix = np.random.random((len(tokenizer.word_index) + 1, vec_model.vector_size)) 44 | for word, i in tokenizer.word_index.items(): 45 | word = str(word) 46 | if word.isspace(): 47 | embedding_vector = vec_model['blank'] 48 | elif word not in vec_model.vocab: 49 | embedding_vector = vec_model['unk'] 50 | else: 51 | embedding_vector = vec_model[word] 52 | embedding_matrix[i] = embedding_vector 53 | return embedding_matrix 54 | 55 | 56 | def texts_to_idx(texts, tokenizer, max_sentence_length): 57 | data = np.zeros((len(texts), max_sentence_length), dtype='int32') 58 | for i, wordTokens in enumerate(texts): 59 | k = 0 60 | for _, word in enumerate(wordTokens): 61 | try: 62 | if k < max_sentence_length and tokenizer.word_index[word] < tokenizer.num_words: 63 | data[i, k] = tokenizer.word_index[word] 64 | k = k + 1 65 | except: 66 | if k < max_sentence_length: 67 | data[i, k] = 0 68 | k = k + 1 69 | return data 70 | 71 | 72 | def parse_index_file(filename): 73 | """Parse index file.""" 74 | index = [] 75 | for line in open(filename): 76 | index.append(int(line.strip())) 77 | return index 78 | 79 | 80 | def sample_mask(idx, l): 81 | """Create mask.""" 82 | mask = np.zeros(l) 83 | mask[idx] = 1 84 | return np.array(mask, dtype=np.bool) 85 | 86 | 87 | def load_corpus(dataset_str, source_data_dir="./data/"): 88 | """ 89 | Loads input corpus from gcn/data directory 90 | 91 | ind.dataset_str.x => the feature vectors of the training docs as scipy.sparse.csr.csr_matrix object; 92 | ind.dataset_str.tx => the feature vectors of the test docs as scipy.sparse.csr.csr_matrix object; 93 | ind.dataset_str.allx => the feature vectors of both labeled and unlabeled training docs/words 94 | (a superset of ind.dataset_str.x) as scipy.sparse.csr.csr_matrix object; 95 | ind.dataset_str.y => the one-hot labels of the labeled training docs as numpy.ndarray object; 96 | ind.dataset_str.ty => the one-hot labels of the test docs as numpy.ndarray object; 97 | ind.dataset_str.ally => the labels for instances in ind.dataset_str.allx as numpy.ndarray object; 98 | ind.dataset_str.adj => adjacency matrix of word/doc nodes as scipy.sparse.csr.csr_matrix object; 99 | ind.dataset_str.train.index => the indices of training docs in original doc list. 100 | All objects above must be saved using python pickle module. 101 | :param dataset_str: Dataset name 102 | :return: All data input files loaded (as well the training/test data). 103 | """ 104 | names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'adj'] 105 | objects = [] 106 | for i in range(len(names)): 107 | with open(source_data_dir + "ind.{}.{}".format(dataset_str, names[i]), 'rb') as f: 108 | if sys.version_info > (3, 0): 109 | objects.append(pkl.load(f, encoding='latin1')) 110 | else: 111 | objects.append(pkl.load(f)) 112 | 113 | x, y, tx, ty, allx, ally, adj = tuple(objects) 114 | 115 | features = sp.vstack((allx, tx)).tolil() 116 | labels = np.vstack((ally, ty)) 117 | 118 | train_idx_orig = parse_index_file( 119 | source_data_dir + "{}.train.index".format(dataset_str)) 120 | train_size = len(train_idx_orig) 121 | 122 | val_size = train_size - x.shape[0] 123 | test_size = tx.shape[0] 124 | 125 | idx_train = range(len(y)) 126 | idx_val = range(len(y), len(y) + val_size) 127 | idx_test = range(allx.shape[0], allx.shape[0] + test_size) 128 | 129 | train_mask = sample_mask(idx_train, labels.shape[0]) 130 | val_mask = sample_mask(idx_val, labels.shape[0]) 131 | test_mask = sample_mask(idx_test, labels.shape[0]) 132 | 133 | y_train = np.zeros(labels.shape) 134 | y_val = np.zeros(labels.shape) 135 | y_test = np.zeros(labels.shape) 136 | y_train[train_mask, :] = labels[train_mask, :] 137 | y_val[val_mask, :] = labels[val_mask, :] 138 | y_test[test_mask, :] = labels[test_mask, :] 139 | 140 | adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj) 141 | return adj, features, labels, list(idx_train) + list(idx_val), list(idx_test), train_size, test_size 142 | 143 | 144 | def data_train_split(Y_train, split_size=1.0): 145 | """ 146 | 按照标签分层抽样 147 | :param Y_train: 数据标签 148 | :param split_size: 选取的数据的比例 149 | :return: index_choose 划分出数据的index 150 | """ 151 | if len(Y_train[0]) > 1: # one hot representation 152 | Y = [np.argmax(y) for y in Y_train] 153 | else: 154 | Y = Y_train # index representation 155 | Y_choose, _, index_choose, _ = train_test_split(Y, range(0, len(Y)), train_size=split_size, stratify=Y, \ 156 | random_state=42) 157 | return sorted(index_choose) 158 | 159 | 160 | def train(model, optimizer, X_idx, labels, idx_train, batch_size): 161 | data_loader = DataLoader(idx_train, batch_size=batch_size, shuffle=True) 162 | model.train() 163 | for idx_batch in data_loader: 164 | optimizer.zero_grad() 165 | output = model(idx_batch, X_idx[idx_batch]) 166 | preds = torch.sigmoid(output) 167 | loss_train = F.binary_cross_entropy(preds, labels[idx_batch]) 168 | loss_train.backward() 169 | optimizer.step() 170 | 171 | loss_train, acc_train = test_on_batch(model, X_idx, idx_train) 172 | return loss_train, acc_train 173 | 174 | 175 | def test_on_batch(model, X_idx, idx_test, labels, batch_size=128): 176 | data_loader = DataLoader(idx_test, batch_size=batch_size, shuffle=False) 177 | 178 | with torch.no_grad(): 179 | model.eval() 180 | output_test = [] 181 | for idx_batch in data_loader: 182 | output = model(idx_batch, X_idx[idx_batch]) 183 | output_test.append(output) 184 | output_test = torch.cat(output_test, dim=0) 185 | preds_test = torch.sigmoid(output_test) 186 | loss_test = F.binary_cross_entropy(preds_test, labels[idx_test]) 187 | acc_test = accuracy(preds_test, labels[idx_test]) 188 | 189 | return loss_test.item(), acc_test 190 | 191 | 192 | def compute_adj_matrix(input): 193 | """ 194 | 计算邻接矩阵,有不同的计算方式: 195 | 方法1:1 - 词向量均值的similarity(满足:对角线为1,两个结点相似性越高,值越大) 196 | :param input: 197 | :return: 198 | """ 199 | sim_matrix = pairwise_distances(input.tolist(), metric="cosine", n_jobs=6) 200 | return 1 - sim_matrix 201 | 202 | 203 | def normalize_adj(adj, tocoo=True): 204 | """Symmetrically normalize adjacency matrix.""" 205 | adj = sp.coo_matrix(adj) 206 | rowsum = np.array(adj.sum(1)) 207 | d_inv_sqrt = np.power(rowsum, -0.5).flatten() 208 | d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0. 209 | d_mat_inv_sqrt = sp.diags(d_inv_sqrt) 210 | if tocoo: 211 | return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo() 212 | else: 213 | return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt) 214 | 215 | 216 | def preprocess_adj(adj, to_dense=True, tocoo=True): 217 | """Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation.""" 218 | adj_normalized = normalize_adj(adj + sp.eye(adj.shape[0]), tocoo=tocoo) 219 | # return sparse_to_tuple(adj_normalized) 220 | if to_dense: 221 | return adj_normalized.A 222 | else: 223 | return adj_normalized 224 | 225 | 226 | def accuracy(preds, target, detail=False): 227 | preds = preds.max(1)[1] 228 | target = target.max(1)[1].long() 229 | correct = preds.eq(target).double() 230 | # correct = [1 if target[i][int(p)] == 1 else 0 for i, p in enumerate(preds)] 231 | if detail: 232 | print("Test Precision, Recall and F1-Score...") 233 | print(metrics.classification_report(np.array(target), np.array(preds), digits=4)) 234 | print("Macro average Test Precision, Recall and F1-Score...") 235 | print(metrics.precision_recall_fscore_support(np.array(target), np.array(preds), average='macro')) 236 | print("Micro average Test Precision, Recall and F1-Score...") 237 | print(metrics.precision_recall_fscore_support(np.array(target), np.array(preds), average='micro')) 238 | 239 | return sum(correct) / len(target) 240 | 241 | 242 | def preprocess_features(features): 243 | """Row-normalize feature matrix and convert to tuple representation""" 244 | rowsum = np.array(features.sum(1)) 245 | r_inv = np.power(rowsum, -1).flatten() 246 | r_inv[np.isinf(r_inv)] = 0. 247 | r_mat_inv = sp.diags(r_inv) 248 | features = r_mat_inv.dot(features) 249 | # return sparse_to_tuple(features) 250 | if isinstance(features, np.ndarray): 251 | return features 252 | else: 253 | return features.A 254 | 255 | 256 | def save_model(model, optimizer, path, epoch, loss): 257 | torch.save({ 258 | 'model_state_dict': model.state_dict(), 259 | 'optimizer_state_dict': optimizer.state_dict(), 260 | 'loss': loss, 261 | 'epoch': epoch 262 | }, path + "_ckpt.pt", pickle_protocol=4) 263 | print("model saved", path + "_ckpt.pt") 264 | 265 | 266 | def load_model(path, model, optimizer): 267 | checkpoint = torch.load(path) 268 | model.load_state_dict(checkpoint['model_state_dict']) 269 | optimizer.load_state_dict(checkpoint['optimizer_state_dict']) 270 | epoch = checkpoint['epoch'] 271 | loss = checkpoint['loss'] 272 | model.eval() # 防止预测时修改模型 273 | return epoch, loss, path, model, optimizer 274 | 275 | 276 | def get_adj_list(adj): 277 | adj_lists = dict() 278 | for i in range(adj.shape[0]): 279 | adj_lists[i] = set(np.where(adj[i])[0]) 280 | assert len(adj_lists) == adj.shape[0], "adj_lists num != node num" 281 | return adj_lists 282 | 283 | 284 | def load_file(data_path): 285 | with open(data_path, "rb") as f: 286 | data = pkl.load(f) 287 | return data 288 | --------------------------------------------------------------------------------