├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── Makefile ├── README.md ├── analysis ├── correlation.go └── utils.go ├── docs ├── analysis.md ├── encoders.md ├── engine.md ├── evaluation.md ├── ideas.md ├── online.md ├── recos.md └── textos.md ├── encoders ├── config.go ├── encoder.go ├── float_exact.go ├── float_reducer.go ├── float_reducer_test.go ├── input.go ├── scanner.go ├── string_dictionary.go ├── string_ngrams.go ├── string_split_dictionary.go └── utils.go ├── engine ├── config.go ├── engine.go └── train.go ├── evaluation ├── evaluation.go ├── metrics.go └── print.go ├── examples ├── README.md ├── dictionary │ ├── README.md │ └── main.go ├── float-reducer │ ├── README.md │ └── main.go ├── ngram │ ├── README.md │ └── main.go ├── online-generator │ ├── README.md │ └── main.go ├── online-sonar │ ├── README.md │ └── main.go ├── sonar │ ├── README.md │ └── main.go └── wine-quality │ ├── README.md │ └── main.go ├── learn ├── learn.go ├── samples.go └── set.go ├── net ├── activation_func.go ├── activation_function_test.go ├── enter.go ├── layer.go ├── layer_test.go ├── network.go ├── neuron.go ├── neuron_test.go ├── synapse.go └── type.go ├── online ├── config.go ├── online.go └── train.go └── persist ├── encoder.go ├── network.go ├── online.go └── set.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | 17 | # specific 18 | todo 19 | *.phrase 20 | *.json 21 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 | # Change Log 3 | All notable changes to this project will be documented in this file. 4 | 5 | ## [0.3.0] 2021-06-07 6 | 7 | This version introduces a persitence layer for encoders. 8 | 9 | ### Added 10 | - Serialization for encoders 11 | 12 | ### Changed 13 | - Interface of encoders 14 | - Minor things in the library 15 | 16 | ### Fixed 17 | - Some issues with serialization of online, network 18 | 19 | 20 | ## [0.2.5] 2021-06-06 21 | 22 | With this version we introduce encoders (automatic encoders) to gopher-learn. 23 | You now can reduce large float slice inputs or encode your string input right away. 24 | 25 | ### Added 26 | - Encoders for float slices and string input. 27 | - With encoders large float input can be reduced using Spearman. 28 | - Also with encoders strings can be encoded as ngrams and dictionary (Topic modelling to come soon) 29 | 30 | ### Changed 31 | - Relocated the neural net from neural package into an own package called net 32 | 33 | ### Fixed 34 | - Nothing here 35 | 36 | 37 | ## [0.2] - 2021-05-09 38 | 39 | Introducing online learning. 40 | 41 | ### Added 42 | - Config for online learner to control learning behavior - easily inject your own config 43 | - Config for engine learner to control learning behavior - easily inject your own config 44 | - Wrote Comments to every function to make everything easier to understand 45 | - Online learner can now be serialized to disk using persist.OnlineToFile() and load using persist.OnlineFromFile() 46 | 47 | ### Changed 48 | - Refactoring of Criterion handling. It is now part of the neural package (usage e.g.: neural.Distance) 49 | - Reworked some of the examples 50 | 51 | ### Fixed 52 | - Fixed regression example, did not work correctly 53 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | test: test_neural test_persist test_learn test_engine test_evaluation 2 | 3 | test_persist: 4 | @( go test ./persist/ ) 5 | 6 | test_neural: 7 | @( go test ) 8 | 9 | test_learn: 10 | @( go test ./learn/ ) 11 | 12 | test_engine: 13 | @( go test ./engine/ ) 14 | 15 | test_engine: 16 | @( go test ./evaluation/ ) 17 | 18 | goget: 19 | @( \ 20 | go get github.com/breskos/gopher-learn; \ 21 | go get github.com/breskos/gopher-learn/persist; \ 22 | go get github.com/breskos/gopher-learn/learn; \ 23 | go get github.com/breskos/gopher-learn/engine; \ 24 | go get github.com/breskos/gopher-learn/evaluation; \ 25 | ) 26 | 27 | gogetu: 28 | @( \ 29 | go get github.com/breskos/gopher-learn; \ 30 | go get github.com/breskos/gopher-learn/persist; \ 31 | go get github.com/breskos/gopher-learn/learn; \ 32 | go get github.com/breskos/gopher-learn/engine; \ 33 | go get github.com/breskos/gopher-learn/evaluation; \ 34 | ) 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gopher-learn 2 | 3 | ![gopher-learn-logo](http://alexander.bre.sk/x/gopher-neural-small.png " The Gopher Neural logo ") 4 | 5 | ## Quickstart 6 | 7 | - See examples here: https://github.com/breskos/gopher-learn/tree/master/examples 8 | 9 | ## What is gopher-learn? 10 | 11 | - Artificial neural network written in Golang with training / testing framework 12 | - Rich measurement mechanisms to control the training 13 | - Examples for fast understanding 14 | - Can also be used for iterative online learning (using online module) for autonomous agents 15 | - Encoders can be used to encoder string data or massive float slices 16 | 17 | ## Install 18 | 19 | ``` 20 | go get github.com/breskos/gopher-learn/... 21 | ``` 22 | 23 | ## Examples 24 | 25 | Find the examples in the examples folder. 26 | All the data to run the examples [can be found here](https://github.com/breskos/gopher-learn-data). 27 | 28 | ## The gopher-learn engine 29 | 30 | The engine helps you with optimizing the learning process. 31 | Basically it starts with a high learning rate to make fast progress in the beginning. 32 | After some rounds of learning (epochs) the learning rate declines (decay). 33 | During the process the best network is saved. 34 | After engine finished training you receive the ready to go network. 35 | 36 | ## Modes 37 | 38 | Gopher-neural can be used to perform classification and regression. This sections helps to set up both modes. In general, you have to take care about the differences between both modes during these parts: read training data from file, start engine, use evaluation modes and perform in production. 39 | 40 | ### Classification 41 | 42 | #### Read training data from file 43 | 44 | ```go 45 | data := learn.NewSet(neural.Classification) 46 | ok, err := data.LoadFromCSV(dataFile) 47 | ``` 48 | 49 | #### Start engine 50 | 51 | This uses the standard config of the engine. 52 | For finetuning use e.SetConfig() to set your own config. 53 | 54 | ```go 55 | e := engine.NewEngine(neural.Classification, []int{hiddenNeurons}, data) 56 | e.SetVerbose(true) 57 | e.Start(neural.Distance) 58 | ``` 59 | 60 | #### Use evalation mode 61 | 62 | ```go 63 | evaluation.PrintSummary("name of class1") 64 | evaluation.PrintSummary("name of class2") 65 | evaluation.PrintConfusionMatrix() 66 | ``` 67 | 68 | #### Perform in production 69 | 70 | ```go 71 | x := net.CalculateWinnerLabel(vector) 72 | ``` 73 | 74 | ### Regression 75 | 76 | Important note: Use regression just with a target value between 0 and 1. 77 | 78 | #### Read training data from file 79 | 80 | ```go 81 | data := learn.NewSet(neural.Regression) 82 | ok, err := data.LoadFromCSV(dataFile) 83 | ``` 84 | 85 | #### Start engine 86 | 87 | This uses the standard config of the engine. 88 | For finetuning use e.SetConfig() to set your own config. 89 | 90 | ```go 91 | e := engine.NewEngine(neural.Regression, []int{hiddenNeurons}, data) 92 | e.SetVerbose(true) 93 | e.Start(neural.Distance) 94 | ``` 95 | 96 | #### Use evalation mode 97 | 98 | ```go 99 | evaluation.GetRegressionSummary() 100 | ``` 101 | 102 | #### Perform in production 103 | 104 | ```go 105 | x := net.Calculate(vector) 106 | ``` 107 | 108 | ## Criterions 109 | 110 | To let the engine decide for the best model, a few criterias were implemented. They are listed below together with a short regarding their application: 111 | 112 | - **Accuracy** - uses simple accuracy calculation to decide the best model. Not suitable with unbalanced data sets. 113 | - **BalancedAccuracy** - uses balanced accuracy. Suitable for unbalanced data sets. 114 | - **FMeasure** - uses F1 score. Suitable for unbalanced data sets. 115 | - **Simple** - uses simple correct classified divided by all classified samples. Suitable for regression with thresholding. 116 | - **Distance** - uses distance between ideal output and current output. Suitable for regression. 117 | 118 | ```go 119 | ... 120 | e := engine.NewEngine(neural.Classification, []int{100}, data) 121 | e.Start(neural.Distance, tries, epochs, trainingSplit, learningRate, decay) 122 | ... 123 | ``` 124 | 125 | ## Some more basics 126 | 127 | ### Train a network using engine 128 | 129 | Using the engine makes sense for you if you want to fully use the training framework that gopher-learn offers you. 130 | With engine package the network is learned using learning rate, decay, epochs. 131 | Also in the engine you can choose between the criteria options to find the best network. 132 | 133 | ```go 134 | import ( 135 | "fmt" 136 | 137 | "github.com/breskos/gopher-learn" 138 | "github.com/breskos/gopher-learn/engine" 139 | "github.com/breskos/gopher-learn/learn" 140 | "github.com/breskos/gopher-learn/persist" 141 | ) 142 | 143 | const ( 144 | dataFile = "data.csv" 145 | networkFile = "network.json" 146 | tries = 1 147 | epochs = 100 148 | trainingSplit = 0.7 149 | learningRate = 0.6 150 | decay = 0.005 151 | hiddenNeurons = 20 152 | ) 153 | 154 | func main() { 155 | data := learn.NewSet(neural.Classification) 156 | ok, err := data.LoadFromCSV(dataFile) 157 | if !ok || nil != err { 158 | fmt.Printf("something went wrong -> %v", err) 159 | } 160 | e := engine.NewEngine(neural.Classification, []int{hiddenNeurons}, data) 161 | e.SetVerbose(true) 162 | e.SetConfig(&engine.Config{ 163 | Tries: tries, 164 | Epochs: epochs, 165 | TrainingSplit: trainingSplit, 166 | LearningRate: learningRate, 167 | Decay: decay, 168 | }) 169 | e.Start(neural.Distance) 170 | network, evaluation := e.GetWinner() 171 | 172 | evaluation.PrintSummary("name of class1") 173 | evaluation.PrintSummary("name of class2") 174 | 175 | err = persist.ToFile(networkFile, network) 176 | if err != nil { 177 | fmt.Printf("error while saving network: %v\n", err) 178 | } 179 | network2, err := persist.FromFile(networkFile) 180 | if err != nil { 181 | fmt.Printf("error while loading network: %v\n", err) 182 | } 183 | // check the network with the first sample 184 | w := network2.CalculateWinnerLabel(data.Samples[0].Vector) 185 | fmt.Printf("%v -> %v\n", data.Samples[0].Label, w) 186 | 187 | fmt.Println(" * Confusion Matrix *") 188 | evaluation.PrintConfusionMatrix() 189 | } 190 | 191 | ``` 192 | 193 | ### Create simple network for classification 194 | 195 | ```go 196 | 197 | import "github.com/breskos/gopher-learn/net" 198 | // Network has 9 enters and 3 layers 199 | // ( 9 neurons, 9 neurons and 2 neurons). 200 | // Last layer is network output (2 neurons). 201 | // For these last neurons we need labels (like: spam, nospam, positive, negative) 202 | labels := make(map[int]string) 203 | labels[0] = "positive" 204 | labels[1] = "negative" 205 | n := net.NewNetwork(9, []int{9,9,2}, map[int]) 206 | // Randomize sypaseses weights 207 | n.RandomizeSynapses() 208 | 209 | // now you can calculate on this network (of course it is not trained yet) 210 | // (for the training you can use then engine) 211 | result := n.Calculate([]float64{0,1,0,1,1,1,0,1,0}) 212 | 213 | ``` 214 | -------------------------------------------------------------------------------- /analysis/correlation.go: -------------------------------------------------------------------------------- 1 | package analysis 2 | 3 | import ( 4 | "math" 5 | "sort" 6 | ) 7 | 8 | // Spearman returns the rank correlation coefficient between data1 and data2, and the associated p-value 9 | func Spearman(data1, data2 []float64) (rs float64, p float64) { 10 | n := len(data1) 11 | wksp1, wksp2 := make([]float64, n), make([]float64, n) 12 | copy(wksp1, data1) 13 | copy(wksp2, data2) 14 | 15 | sort.Sort(sorter{wksp1, wksp2}) 16 | sf := overwrite(wksp1) 17 | sort.Sort(sorter{wksp2, wksp1}) 18 | sg := overwrite(wksp2) 19 | d := 0.0 20 | for j := 0; j < n; j++ { 21 | sq := wksp1[j] - wksp2[j] 22 | d += (sq * sq) 23 | } 24 | 25 | en := float64(n) 26 | en3n := en*en*en - en 27 | 28 | fac := (1.0 - sf/en3n) * (1.0 - sg/en3n) 29 | rs = (1.0 - (6.0/en3n)*(d+(sf+sg)/12.0)) / math.Sqrt(fac) 30 | 31 | if fac = (rs + 1.0) * (1.0 - rs); fac > 0 { 32 | t := rs * math.Sqrt((en-2.0)/fac) 33 | df := en - 2.0 34 | p = betaIncomplete(df/(df+t*t), 0.5*df, 0.5) 35 | } 36 | 37 | return rs, p 38 | } 39 | 40 | func overwrite(w []float64) float64 { 41 | j, ji, jt, n := 1, 0, 0, len(w) 42 | var rank, s float64 43 | for j < n { 44 | if w[j] != w[j-1] { 45 | w[j-1] = float64(j) 46 | j++ 47 | } else { 48 | for jt = j + 1; jt <= n && w[jt-1] == w[j-1]; jt++ { 49 | } 50 | rank = 0.5 * (float64(j) + float64(jt) - 1) 51 | for ji = j; ji <= (jt - 1); ji++ { 52 | w[ji-1] = rank 53 | } 54 | t := float64(jt - j) 55 | s += (t*t*t - t) 56 | j = jt 57 | } 58 | } 59 | if j == n { 60 | w[n-1] = float64(n) 61 | } 62 | return s 63 | } 64 | 65 | // betaIncomplete 66 | func betaIncomplete(x, a, b float64) float64 { 67 | if x < 0 || x > 1 { 68 | return math.NaN() 69 | } 70 | bt := 0.0 71 | if 0 < x && x < 1 { 72 | bt = math.Exp(lgamma(a+b) - lgamma(a) - lgamma(b) + 73 | a*math.Log(x) + b*math.Log(1-x)) 74 | } 75 | if x < (a+1)/(a+b+2) { 76 | return bt * betaContinuedFractionComponent(x, a, b) / a 77 | } else { 78 | return 1 - bt*betaContinuedFractionComponent(1-x, b, a)/b 79 | } 80 | } 81 | 82 | func betaContinuedFractionComponent(x, a, b float64) float64 { 83 | const maxIterations = 200 84 | const epsilon = 3e-14 85 | raiseZero := func(z float64) float64 { 86 | if math.Abs(z) < math.SmallestNonzeroFloat64 { 87 | return math.SmallestNonzeroFloat64 88 | } 89 | return z 90 | } 91 | c := 1.0 92 | d := 1 / raiseZero(1-(a+b)*x/(a+1)) 93 | h := d 94 | for m := 1; m <= maxIterations; m++ { 95 | mf := float64(m) 96 | numer := mf * (b - mf) * x / ((a + 2*mf - 1) * (a + 2*mf)) 97 | d = 1 / raiseZero(1+numer*d) 98 | c = raiseZero(1 + numer/c) 99 | h *= d * c 100 | numer = -(a + mf) * (a + b + mf) * x / ((a + 2*mf) * (a + 2*mf + 1)) 101 | d = 1 / raiseZero(1+numer*d) 102 | c = raiseZero(1 + numer/c) 103 | hfac := d * c 104 | h *= hfac 105 | 106 | if math.Abs(hfac-1) < epsilon { 107 | return h 108 | } 109 | } 110 | panic("betainc: a or b too big; failed to converge") 111 | } 112 | 113 | func lgamma(x float64) float64 { 114 | y, _ := math.Lgamma(x) 115 | return y 116 | } 117 | -------------------------------------------------------------------------------- /analysis/utils.go: -------------------------------------------------------------------------------- 1 | package analysis 2 | 3 | type sorter struct { 4 | x []float64 5 | y []float64 6 | } 7 | 8 | func (s sorter) Len() int { return len(s.x) } 9 | func (s sorter) Less(i, j int) bool { return s.x[i] < s.x[j] } 10 | func (s sorter) Swap(i, j int) { 11 | s.x[i], s.x[j] = s.x[j], s.x[i] 12 | s.y[i], s.y[j] = s.y[j], s.y[i] 13 | } 14 | -------------------------------------------------------------------------------- /docs/analysis.md: -------------------------------------------------------------------------------- 1 | # Analysis 2 | 3 | *State: In concept* 4 | 5 | This module acts as helper for the encoders and the for the evaluation of a data set. 6 | 7 | ## Functionalities (planned) 8 | 9 | - Correlation, *Similarities* between vectors, frames and matrixes 10 | - Statistical measures on vectors and matrixes 11 | - Information gain, entropy 12 | - Bucketization of dimensions to determine how well a feature helps with classification -------------------------------------------------------------------------------- /docs/encoders.md: -------------------------------------------------------------------------------- 1 | # Encoders (experimental) 2 | 3 | ## Overview 4 | 5 | **Attention:** Encoders are currently not able to serialize 6 | 7 | Encoders means that the incoming data is automatically put into a data vector (processable for the neural net.) 8 | Encoding of your data into processable feature vectors is very important, because strings are initially not suitable as feature vector. 9 | This module helps to find a representation of your data set without your intervention. 10 | Although the encoders can be controlled using by Config parameters in EncoderConfig. 11 | 12 | ## EncoderConfig 13 | 14 | The encoder performs decisions during its runtime. 15 | For that reason a DefaultConfig is applied. 16 | It is possible to get the DefaultConfig, overwrite specific parameters and apply it again to the encoder. 17 | 18 | ```go 19 | e := encoders.NewEncoder("test encoder") 20 | cfg := encoders.DefaultConfig() 21 | cfg.DictionaryMaxEntries = 300 22 | e.Config = cfg 23 | ``` 24 | You can find all possible options for editting the encoder config in encoders/config.go. 25 | 26 | ## Example 27 | Below you can find an example for the encoder. 28 | 29 | ```go 30 | // generating the encoder, the encoder can hold different input types and dimensions 31 | e := encoders.NewEncoder("test encoder") 32 | cfg := encoders.DefaultConfig() 33 | cfg.DictionaryMaxEntries = 300 34 | e.Config = cfg 35 | inputName := "language-classification" 36 | set := encoders.NewInput(inputName, encoders.String) 37 | for _, v := range data { 38 | // add your strings here 39 | set.AddString(someStringSample) 40 | } 41 | // scan takes the set and decides (if it is: encoders.Automatic) which encoding to apply 42 | e.Scan(inputName, set, encoders.Automatic) 43 | // transform brings the input into the choosen encoding 44 | e.Transform(inputName, set) 45 | // explain can be used to see what the encoder has done 46 | e.Explain() 47 | // using encode() and an Unified (can be string or float slice) you get the corresponding vector 48 | vector := e.Encode(inputName, encoders.Unified{String: "Hello whats up with you?", Type: encoders.String}) 49 | ``` 50 | 51 | 52 | ## Workflow 53 | This is the workflow. An Encoder can contain different models for encoding. In the workflow below, (namespace) means that you perform an action on a namespace within the encoder. For example, if you have a mixed input vector with strings and floats, you an put all floats together in one namespace as well as the string. 54 | 55 | 1. Collect data - The encoder needs the samples from the test or a similar set of data points to optimally fit and decide. 56 | 1. Create Encoder - create an encoder with the config (the Encoder itself can encode different inputs) 57 | 2. Scanner - (namespace) decides which Encoder to select if you choose encoders.Automatic, if not, the given Encoder will be applied 58 | 3. Transform - (namespace) After scanning the set and deciding the data is tranformed into the new vector space 59 | 4. After transformation is done, you are ready to go with your new vector representation 60 | 5. Using - Encode() (namespace) method of the encoder the encode your input. 61 | 62 | ## Encoders 63 | If you have no specific idea which encoder to use you can also run using encoders.Automatic. 64 | Using this the encoder will figure out by itself which encoding is applicable. 65 | 66 | The encoders work for different data types: 67 | 68 | 1. N-Grams (strings), encoders.StringNGrams 69 | 2. Splitted Dictionary (string), encoders.StringSplitDictionary 70 | 3. Dictionary (strings), encoders.StringDictionary 71 | 4. FloatExact (numbers), encoders.FloatExact 72 | 5. FloatReducer (numbers), encoders.FloatReducer 73 | 6. Topic Modelling coming soon (strings) - not implemented yet 74 | 75 | 76 | ## Representation (experimental) 77 | 78 | Out of the encoder activity the network generates a representation of the input space. 79 | This representation can be persisted and loaded to continue working on the network. 80 | This representation looks like this: 81 | 82 | 1. Number of feature vectors 83 | 2. Mapping of value to neuron values 84 | -------------------------------------------------------------------------------- /docs/engine.md: -------------------------------------------------------------------------------- 1 | # Engine 2 | 3 | ## Overview 4 | 5 | Engine triggers the training of the neural network and returns the winner network. 6 | With engine you can use a training set to train the network. 7 | 8 | ## Why using an engine? 9 | 10 | If you want to successfully train a neural network you need a lot of parameters doing the right things. 11 | Engine was defined to bake your neural network based on your given data. 12 | Instead of fine tuning parameters and split data sets on your own, you can use the engine for that. 13 | 14 | See examples **sonar** and **wine-quality** for more insights on the engine. 15 | 16 | ## Config in Engine 17 | Engine comes with a default config. 18 | For classification tasks the default configuration should fit. 19 | On the other hand for regression you should set Config that fits your data set. 20 | Handling of the config is shown in the examples. 21 | 22 | ## Rough pseudo code description 23 | 24 | ```go 25 | // one epoch is defined as one forward pass and one backward pass of all the training examples 26 | for number of #try (tries) 27 | for learningRate minus decay if decay is not 0 28 | for num of #epochs the network sees the training set 29 | ``` 30 | -------------------------------------------------------------------------------- /docs/evaluation.md: -------------------------------------------------------------------------------- 1 | # Evaluation 2 | 3 | This document provides an overview of all the used meaures and the evaluation. 4 | 5 | ## Measures 6 | -------------------------------------------------------------------------------- /docs/ideas.md: -------------------------------------------------------------------------------- 1 | # Future ideas 2 | 3 | ## Rename and batching in learning 4 | 5 | - Use term **batch** size = the number of training examples in one forward/backward pass. 6 | - Use term **iterations** = number of passes, each pass using [batch size] number of examples. 7 | - Random application of samples 8 | -------------------------------------------------------------------------------- /docs/online.md: -------------------------------------------------------------------------------- 1 | # Online Learning 2 | 3 | ## Overview 4 | 5 | Online learning is a mechanism in gopher-learn that help to train neural networks on the fly. 6 | With the Online Learning module one can add more data points step by step and the neural net is able to adjust. 7 | 8 | ## Iterative learning 9 | 10 | The `Inject function` forwards new data points to the network. 11 | So the `Iterate function` basically uses a sampled set of know data points and iterates the training process of the neural net. 12 | After that the evaluation kicks in and looks whether the new point was sucessfully learned by the network. 13 | 14 | ## Usage 15 | 16 | ```golang 17 | // we need to define the numer of input neurons we have 18 | inputNeurons = 30 19 | // we also need to define the number of hidden neurons we need (we are using one layer here) 20 | hiddenNeurons = 100 21 | // data from file that we want to stream in 22 | // we create an empty set with correct number of inputs and classes 23 | set := learn.NewSet(neural.Classification) 24 | // we know that our data points will have 2 classes R and M 25 | set.AddClass("R") 26 | set.AddClass("M") 27 | 28 | // our onlineSet is still empty but we need to defined it 29 | o := online.NewOnline(neural.Classification, inputNeurons, []int{hiddenNeurons}, set) 30 | // we set verbose = true because we want to see the progress 31 | o.SetVerbose(true) 32 | // in case we already started with a not empty data set we run 33 | fMeasure := o.init() 34 | // this will run the previously given data to init the network 35 | // here the network tries to reach a specific overall fMeasure 36 | fmt.Printf("init fMeasure: &f\n", fMeasure) 37 | ``` 38 | 39 | After this set up you can start injecting data points to the network. 40 | Dont forget to call iterate at some points to force the learning process. 41 | The `Inject()` function just runs **hot shot** which means that it tries to force the injection without retraining the network. 42 | This is kind of a tradeoff between learning speed and repeating everything in the data set. 43 | 44 | ```golang 45 | // here we get a new vector for the network 46 | vector := []float64{1.0, 3.0, 10.5, 5.0, 4.0, 3.3, 5.2} 47 | // now we apply this vector and generate a valid output vector for this class label 48 | // using: GenerateOutputVector(classLabel) function of Set 49 | sample := learn.NewClassificationSample(vector, set.GenerateOutputVector("R"), "R") 50 | // create a sample with input vector and class label 51 | // if a sample of this exists do not override it (force = false) 52 | o.Inject(sample, false) 53 | // after inserting a few points you have to iterate 54 | // Iterate returns the current fMeasure which you can use to observe the quality of the network 55 | fMeasure = o.Iterate() 56 | ``` 57 | 58 | 59 | ## Config in Online 60 | Online comes with a default config. 61 | For classification tasks the default configuration should fit. 62 | On the other hand for regression you should set Config that fits your data set. 63 | Handling of the config is shown in the examples. -------------------------------------------------------------------------------- /docs/recos.md: -------------------------------------------------------------------------------- 1 | # Recos 2 | 3 | *State: In concept* -------------------------------------------------------------------------------- /docs/textos.md: -------------------------------------------------------------------------------- 1 | # Textos Extractor 2 | 3 | *State: In concept* 4 | 5 | 6 | This extractor can be used to extract strings and topics. 7 | In this document the nature of Textos is described. 8 | 9 | ## Analysis 10 | - Occurence of tokens 11 | 12 | ## Layers 13 | 14 | ### Structural learner 15 | The stuctural learner uses the data from the corpus to decide which part of the text is structural and which one is topic related. 16 | 17 | 18 | ### Topic Modelling -------------------------------------------------------------------------------- /encoders/config.go: -------------------------------------------------------------------------------- 1 | package encoders 2 | 3 | type EncoderConfig struct { 4 | DelimiterToken string 5 | DimToSamplesRatio float64 6 | // Decision heuristics 7 | FloatReducerThreshold int 8 | TopicModelMinDelimiters int 9 | NGramsMaxTokens int 10 | DictionaryMaxEntries int 11 | DictionaryMaxDelimiters int 12 | SplitDictionaryMaxEntries int 13 | // Application settings 14 | FloatReducerSpearman float64 15 | FloatReducerSkewness float64 16 | FloatReducerZeroValues bool 17 | NGramMaxGrams int 18 | NGramMaxCapacity int 19 | NGramCropRatio float64 20 | DefaultStringEncoder EncoderType 21 | } 22 | 23 | func DefaultConfig() *EncoderConfig { 24 | return &EncoderConfig{ 25 | DelimiterToken: " ", 26 | DimToSamplesRatio: 0.8, 27 | FloatReducerThreshold: 40, 28 | TopicModelMinDelimiters: 5, 29 | NGramsMaxTokens: 20, 30 | DictionaryMaxEntries: 50, 31 | DictionaryMaxDelimiters: 5, 32 | SplitDictionaryMaxEntries: 100, 33 | FloatReducerSpearman: 0.90, 34 | FloatReducerSkewness: 0.90, 35 | FloatReducerZeroValues: true, 36 | NGramMaxGrams: 3, 37 | NGramMaxCapacity: 100, 38 | NGramCropRatio: 0.05, 39 | DefaultStringEncoder: StringNGrams, 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /encoders/encoder.go: -------------------------------------------------------------------------------- 1 | package encoders 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | ) 7 | 8 | type EncoderType int 9 | 10 | const ( 11 | // Automatic means that the encoder decides based on heuristics what to do 12 | Automatic EncoderType = iota 13 | // StringDictionary uses exact matches on strings as dictionary approach 14 | StringDictionary 15 | // StringSplittedDictionary 16 | StringSplitDictionary 17 | // StringTopics uses topic modelling on strings 18 | StringTopics 19 | // StringNGrams uses N-Gram modelling on strings 20 | StringNGrams 21 | // FloatExact just uses the float value it gets from input 22 | FloatExact 23 | // FloatReducer reduces a large number of floats to a smaller input space 24 | FloatReducer 25 | ) 26 | 27 | func (e EncoderType) String() string { 28 | return [...]string{ 29 | "Automatic", 30 | "StringDictionary", 31 | "StringSplitDictionary", 32 | "StringTopics", 33 | "StringNGrams", 34 | "FloatExact", 35 | "FloatReducer", 36 | }[e] 37 | } 38 | 39 | type EncoderModel interface { 40 | Fit(*Input, *EncoderConfig) 41 | CalculateString(string) []float64 42 | CalculateFloats([]float64) []float64 43 | GetDimensions() int 44 | GetQuality() float64 45 | Name() string 46 | ToDump() ([]byte, error) 47 | FromDump([]byte) error 48 | } 49 | 50 | type Encoder struct { 51 | // Name of the encoder 52 | Name string 53 | // Dimensions hold the EncoderModel for the dimensions 54 | Models map[string]*Dimension 55 | // Config of the Encoder 56 | Config *EncoderConfig 57 | // Scanned determines if scan was executed 58 | Scanned bool 59 | } 60 | 61 | type Dimension struct { 62 | Inputs int 63 | InputType InputType 64 | Type EncoderType 65 | Model EncoderModel 66 | } 67 | 68 | func NewEncoder(name string) *Encoder { 69 | return &Encoder{ 70 | Name: name, 71 | Models: make(map[string]*Dimension), 72 | Config: DefaultConfig(), 73 | } 74 | } 75 | 76 | func (e *Encoder) Encode(name string, input Unified) []float64 { 77 | vector := make([]float64, 0) 78 | if _, ok := e.Models[name]; !ok { 79 | log.Fatalf("Model %s is not part of encoder %s", name, e.Name) 80 | } 81 | switch e.Models[name].InputType { 82 | case String: 83 | vector = append(vector, e.Models[name].Model.CalculateString(input.String)...) 84 | case Floats: 85 | vector = append(vector, e.Models[name].Model.CalculateFloats(input.Float)...) 86 | } 87 | return vector 88 | } 89 | 90 | func (e *Encoder) Scan(name string, input *Input, encoder EncoderType) { 91 | samples := len(input.Values) 92 | if samples == 0 { 93 | log.Fatalf("no data samples loaded") 94 | return 95 | } 96 | // if encoder != automatic we execute here 97 | if encoder != Automatic { 98 | e.Models[name] = &Dimension{ 99 | InputType: input.Type, 100 | Type: encoder, 101 | } 102 | e.Scanned = true 103 | return 104 | } 105 | if input.Type == Floats { 106 | dims := len(input.Values[0].Float) 107 | if e.Config.FloatReducerThreshold <= dims { 108 | log.Printf("experimental (not executed): we would apply float reducer here") 109 | } 110 | e.Models[name] = &Dimension{ 111 | Type: FloatExact, 112 | InputType: Floats, 113 | } 114 | 115 | } else { 116 | // input.Type == String 117 | e.Models[name] = &Dimension{ 118 | InputType: String, 119 | Type: evaluateStrings(e.Config, input), 120 | } 121 | } 122 | e.Scanned = true 123 | } 124 | 125 | func (e *Encoder) Transform(name string, set *Input) { 126 | if !e.Scanned { 127 | log.Printf("no set was scanned before, running scan()") 128 | e.Scan(name, set, Automatic) 129 | } 130 | if _, ok := e.Models[name]; !ok { 131 | log.Fatalf("no model: %s available to transform", name) 132 | } 133 | model := e.Models[name] 134 | switch model.Type { 135 | case StringDictionary: 136 | model.Model = NewDictionaryModel() 137 | model.Model.Fit(set, e.Config) 138 | case StringSplitDictionary: 139 | model.Model = NewSplitDictionaryModel() 140 | model.Model.Fit(set, e.Config) 141 | case StringNGrams: 142 | model.Model = NewNGramModel() 143 | model.Model.Fit(set, e.Config) 144 | case StringTopics: 145 | log.Fatal("not implemented") 146 | case FloatReducer: 147 | model.Model = NewFloatReducerModel() 148 | model.Model.Fit(set, e.Config) 149 | case FloatExact: 150 | model.Model = NewFloatExactModel() 151 | model.Model.Fit(set, e.Config) 152 | } 153 | } 154 | 155 | // reporting of what the encoder did 156 | func (e *Encoder) Explain() { 157 | for k, v := range e.Models { 158 | fmt.Printf("[%s] => %s, %s, to: %d dimensions", k, v.InputType.String(), v.Type.String(), v.Model.GetDimensions()) 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /encoders/float_exact.go: -------------------------------------------------------------------------------- 1 | package encoders 2 | 3 | import "encoding/json" 4 | 5 | type FloatExactModel struct { 6 | Dimensions int 7 | Quality float64 8 | } 9 | 10 | func NewFloatExactModel() *FloatExactModel { 11 | return &FloatExactModel{} 12 | } 13 | 14 | func (m *FloatExactModel) Fit(set *Input, config *EncoderConfig) { 15 | m.Dimensions = len(set.Values[0].Float) 16 | } 17 | 18 | func (m *FloatExactModel) CalculateString(s string) []float64 { 19 | return make([]float64, m.Dimensions) 20 | } 21 | 22 | func (m *FloatExactModel) GetDimensions() int { 23 | return m.Dimensions 24 | } 25 | 26 | func (m *FloatExactModel) CalculateFloats(value []float64) []float64 { 27 | return value 28 | } 29 | 30 | func (m *FloatExactModel) ToDump() ([]byte, error) { 31 | return json.Marshal(m) 32 | } 33 | 34 | func (m *FloatExactModel) FromDump(dump []byte) error { 35 | return json.Unmarshal(dump, m) 36 | } 37 | 38 | func (m *FloatExactModel) Name() string { 39 | return "float_exact" 40 | } 41 | 42 | func (m *FloatExactModel) GetQuality() float64 { 43 | return m.Quality 44 | } 45 | -------------------------------------------------------------------------------- /encoders/float_reducer.go: -------------------------------------------------------------------------------- 1 | package encoders 2 | 3 | import ( 4 | "encoding/json" 5 | "log" 6 | "math" 7 | 8 | "github.com/breskos/gopher-learn/analysis" 9 | ) 10 | 11 | /* 12 | FloatReducer contains of threee parts. 13 | It first runs Spearman correlation. If the correlcation of two dimensions is equal or 14 | higher than the defined threshold (in config) on of the dimensions is cut away. 15 | This can be beneficial but also cause problems (in the case that a variable is despite 16 | the high correlation highly important). 17 | Also the FloatrReducer cuts away dimensions that just have one value (and therefore add no information gain). 18 | */ 19 | 20 | type FloatReducerModel struct { 21 | Model map[int]bool 22 | Dimensions int 23 | Quality float64 24 | } 25 | 26 | func NewFloatReducerModel() *FloatReducerModel { 27 | return &FloatReducerModel{ 28 | Model: make(map[int]bool), 29 | } 30 | } 31 | 32 | func (m *FloatReducerModel) Fit(set *Input, config *EncoderConfig) { 33 | if len(set.Values) < 1 { 34 | log.Fatalf("no values delivered for fit") 35 | } 36 | m.Model = make(map[int]bool) 37 | spearman := make(map[int]map[int]float64) 38 | dimensions := make([][]float64, len(set.Values[0].Float)) 39 | for _, sample := range set.Values { 40 | for i, x := range sample.Float { 41 | dimensions[i] = append(dimensions[i], x) 42 | } 43 | } 44 | for i := range dimensions { 45 | spearman[i] = make(map[int]float64) 46 | for j := range dimensions { 47 | if i != j { 48 | rs, _ := analysis.Spearman(dimensions[i], dimensions[j]) 49 | spearman[i][j] = rs 50 | if math.Abs(rs) > math.Abs(config.FloatReducerSpearman) { 51 | m.Model[i] = false 52 | } 53 | } 54 | } 55 | m.Model[i] = true 56 | if similarValues(dimensions[i]) { 57 | m.Model[i] = false 58 | } 59 | } 60 | for i := range spearman { 61 | for j := range spearman[i] { 62 | if spearman[i][j] >= config.FloatReducerSpearman && m.Model[i] && m.Model[j] { 63 | m.Model[i] = false 64 | } 65 | } 66 | } 67 | m.Dimensions = 0 68 | for i := range m.Model { 69 | if m.Model[i] { 70 | m.Dimensions++ 71 | } 72 | } 73 | } 74 | 75 | func (m *FloatReducerModel) GetDimensions() int { 76 | return m.Dimensions 77 | } 78 | 79 | func (m *FloatReducerModel) CalculateFloats(value []float64) []float64 { 80 | vector := make([]float64, 0) 81 | for i := range m.Model { 82 | if m.Model[i] { 83 | vector = append(vector, value[i]) 84 | } 85 | } 86 | return vector 87 | } 88 | 89 | func (m *FloatReducerModel) Name() string { 90 | return "float_reducer" 91 | } 92 | 93 | func (m *FloatReducerModel) CalculateString(s string) []float64 { 94 | return []float64{} 95 | } 96 | 97 | func (m *FloatReducerModel) GetQuality() float64 { 98 | return m.Quality 99 | } 100 | 101 | func (m *FloatReducerModel) ToDump() ([]byte, error) { 102 | return json.Marshal(m) 103 | } 104 | 105 | func (m *FloatReducerModel) FromDump(dump []byte) error { 106 | return json.Unmarshal(dump, m) 107 | } 108 | 109 | func similarValues(values []float64) bool { 110 | len := len(values) 111 | for i, v := range values { 112 | if i < len-1 { 113 | if v != values[i+1] { 114 | return false 115 | } 116 | } 117 | } 118 | return true 119 | } 120 | -------------------------------------------------------------------------------- /encoders/float_reducer_test.go: -------------------------------------------------------------------------------- 1 | package encoders 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestFloatReder(t *testing.T) { 9 | model := "test" 10 | e := NewEncoder("float reducer test") 11 | input := NewInput(model, Floats) 12 | input.AddFloats([]float64{1.0, 0.0, 3.7}) 13 | input.AddFloats([]float64{2.0, 0.9, 0.3}) 14 | input.AddFloats([]float64{3.0, 1.6, 1.3}) 15 | input.AddFloats([]float64{4.0, 2.9, 4.2}) 16 | e.Scan(model, input, FloatReducer) 17 | e.Transform(model, input) 18 | e.Explain() 19 | vector := e.Encode(model, Unified{Float: []float64{1.0, 0.0, 3.7}, Type: Floats}) 20 | if len(vector) != 2 { 21 | t.Errorf("len: %d != 2", len(vector)) 22 | } 23 | fmt.Printf("encoded vector: %v", vector) 24 | } 25 | -------------------------------------------------------------------------------- /encoders/input.go: -------------------------------------------------------------------------------- 1 | package encoders 2 | 3 | type InputType int 4 | 5 | const ( 6 | String InputType = iota 7 | Floats 8 | ) 9 | 10 | func (e InputType) String() string { 11 | return [...]string{"String", "Floats"}[e] 12 | } 13 | 14 | type Inputs struct { 15 | Inputs []*Input 16 | } 17 | 18 | type Input struct { 19 | Name string 20 | Values []*Unified 21 | Type InputType 22 | } 23 | 24 | type Unified struct { 25 | String string 26 | Float []float64 27 | Type InputType 28 | Label string 29 | Target float64 30 | } 31 | 32 | func NewInputs() *Inputs { 33 | return &Inputs{ 34 | Inputs: make([]*Input, 0), 35 | } 36 | } 37 | 38 | func (i *Inputs) Add(input *Input) { 39 | i.Inputs = append(i.Inputs, input) 40 | } 41 | 42 | func NewInput(name string, t InputType) *Input { 43 | return &Input{ 44 | Name: name, 45 | Type: t, 46 | Values: make([]*Unified, 0), 47 | } 48 | } 49 | 50 | func (i *Input) Add(unified *Unified) { 51 | i.Values = append(i.Values, unified) 52 | } 53 | 54 | func (i *Input) AddFloats(sample []float64) { 55 | i.Values = append(i.Values, &Unified{Float: sample, Type: Floats}) 56 | } 57 | 58 | func (i *Input) AddString(sample string) { 59 | i.Values = append(i.Values, &Unified{String: sample, Type: String}) 60 | } 61 | -------------------------------------------------------------------------------- /encoders/scanner.go: -------------------------------------------------------------------------------- 1 | package encoders 2 | 3 | import ( 4 | "strings" 5 | ) 6 | 7 | // The scanner functions are used to determine whether a set is likely to fit and how many dimensions are 8 | // suitable for this set of data. Here also the decision is made for a string encoder. 9 | 10 | // Here the decision for an string encoder is made based on the provided configuration file. 11 | func evaluateStrings(config *EncoderConfig, values *Input) EncoderType { 12 | maxDelimiters := 0 13 | maxStringLength := 0 14 | samples := 0 15 | uniques := make([]string, 0) 16 | uniqueTokens := make(map[string]int) 17 | for _, v := range values.Values { 18 | tokens := strings.Split(v.String, config.DelimiterToken) 19 | for _, v := range tokens { 20 | if _, ok := uniqueTokens[v]; ok { 21 | uniqueTokens[v]++ 22 | } else { 23 | uniqueTokens[v] = 1 24 | } 25 | } 26 | l := len(tokens) 27 | if l > maxDelimiters { 28 | maxDelimiters = l 29 | } 30 | l = len(v.String) 31 | if l > maxStringLength { 32 | maxStringLength = l 33 | } 34 | samples++ 35 | if !contains(uniques, v.String) { 36 | uniques = append(uniques, v.String) 37 | } 38 | } 39 | uniqueEntries := len(uniques) 40 | // Dictionary makes sense if you have something like string states of something. 41 | // In this case the dictionary assignes 0,1 for each dictionary entry shown. 42 | if uniqueEntries <= config.DictionaryMaxEntries && maxDelimiters <= config.DictionaryMaxDelimiters { 43 | return StringDictionary 44 | } 45 | // SplittedDictionary make sense if there are not that much symbols but not just one token. 46 | // Also sentences in a small space are possible. 47 | if len(uniqueTokens) < config.SplitDictionaryMaxEntries { 48 | return StringSplitDictionary 49 | } 50 | // If there are too much entries to use it as a dictionary, we try to make NGrams out of it. 51 | if maxStringLength <= config.NGramsMaxTokens { 52 | return StringNGrams 53 | } 54 | // If nothing matches we default to NGrams. 55 | return config.DefaultStringEncoder 56 | } 57 | 58 | func contains(s []string, str string) bool { 59 | for _, v := range s { 60 | if v == str { 61 | return true 62 | } 63 | } 64 | return false 65 | } 66 | -------------------------------------------------------------------------------- /encoders/string_dictionary.go: -------------------------------------------------------------------------------- 1 | package encoders 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | type DictionaryModel struct { 9 | Dimensions int 10 | Dictionary []string 11 | Quality float64 12 | } 13 | 14 | func NewDictionaryModel() *DictionaryModel { 15 | return &DictionaryModel{} 16 | } 17 | 18 | func (m *DictionaryModel) Fit(set *Input, config *EncoderConfig) { 19 | for _, sample := range set.Values { 20 | value := normalizeString(sample.String) 21 | fmt.Printf("%s", value) 22 | if !contains(m.Dictionary, value) { 23 | m.Dictionary = append(m.Dictionary, value) 24 | } 25 | } 26 | fmt.Printf("%v", m.Dictionary) 27 | m.Dimensions = len(m.Dictionary) 28 | } 29 | 30 | func (m *DictionaryModel) CalculateString(s string) []float64 { 31 | vector := make([]float64, m.Dimensions) 32 | idx := getIndex(m.Dictionary, s) 33 | if idx != -1 { 34 | vector[idx] = 1.0 35 | } 36 | return vector 37 | } 38 | 39 | func (m *DictionaryModel) GetDimensions() int { 40 | return m.Dimensions 41 | } 42 | 43 | func (m *DictionaryModel) CalculateFloats([]float64) []float64 { 44 | return []float64{} 45 | } 46 | 47 | func (m *DictionaryModel) Name() string { 48 | return "dictionary" 49 | } 50 | 51 | func (m *DictionaryModel) GetQuality() float64 { 52 | return m.Quality 53 | } 54 | 55 | func (m *DictionaryModel) ToDump() ([]byte, error) { 56 | return json.Marshal(m) 57 | } 58 | 59 | func (m *DictionaryModel) FromDump(dump []byte) error { 60 | return json.Unmarshal(dump, m) 61 | } 62 | 63 | func getIndex(s []string, value string) int { 64 | for k, v := range s { 65 | if v == value { 66 | return k 67 | } 68 | } 69 | return -1 70 | } 71 | -------------------------------------------------------------------------------- /encoders/string_ngrams.go: -------------------------------------------------------------------------------- 1 | package encoders 2 | 3 | import ( 4 | "encoding/json" 5 | "sort" 6 | ) 7 | 8 | const ( 9 | DefaultGram = 3 10 | ) 11 | 12 | type NGramModel struct { 13 | Dimensions int 14 | // Grams to index in vector 15 | GramsLookup map[string]int 16 | // Grams to number of appearances 17 | Grams map[string]int 18 | Samples int 19 | Quality float64 20 | } 21 | 22 | func NewNGramModel() *NGramModel { 23 | return &NGramModel{ 24 | Grams: make(map[string]int, 0), 25 | GramsLookup: make(map[string]int), 26 | } 27 | } 28 | 29 | func (m *NGramModel) Fit(set *Input, config *EncoderConfig) { 30 | modelIndex := 0 31 | for _, sample := range set.Values { 32 | m.Samples++ 33 | value := normalizeString(sample.String) 34 | l := len(value) 35 | for k := range value { 36 | if k <= l-DefaultGram { 37 | gram := value[k : k+DefaultGram] 38 | if _, ok := m.GramsLookup[gram]; !ok { 39 | m.GramsLookup[gram] = modelIndex 40 | modelIndex++ 41 | m.Grams[gram] = 1 42 | } else { 43 | m.Grams[gram]++ 44 | } 45 | } 46 | } 47 | } 48 | m.Dimensions = len(m.Grams) 49 | m.optimize(config.NGramMaxCapacity, config.NGramCropRatio) 50 | } 51 | 52 | func (m *NGramModel) CalculateString(s string) []float64 { 53 | vector := make([]float64, m.Dimensions) 54 | value := normalizeString(s) 55 | ngrams := ngramize(value, DefaultGram) 56 | for _, gram := range ngrams { 57 | if index, ok := m.GramsLookup[gram]; ok { 58 | vector[index] = 1.0 59 | } 60 | } 61 | return vector 62 | } 63 | 64 | func (m *NGramModel) GetDimensions() int { 65 | return m.Dimensions 66 | } 67 | 68 | func (m *NGramModel) CalculateFloats([]float64) []float64 { 69 | return []float64{} 70 | } 71 | 72 | func (m *NGramModel) ToDump() ([]byte, error) { 73 | return json.Marshal(m) 74 | } 75 | 76 | func (m *NGramModel) FromDump(dump []byte) error { 77 | return json.Unmarshal(dump, m) 78 | } 79 | 80 | func (m *NGramModel) Name() string { 81 | return "ngrams" 82 | } 83 | 84 | func (m *NGramModel) GetQuality() float64 { 85 | return m.Quality 86 | } 87 | 88 | func (m *NGramModel) optimize(maxCapacity int, cropRatio float64) { 89 | if maxCapacity >= m.Dimensions { 90 | return 91 | } 92 | 93 | for gram, appearance := range m.Grams { 94 | if float64(appearance)/float64(m.Samples) < cropRatio { 95 | delete(m.Grams, gram) 96 | } 97 | } 98 | // reindex cropped to vector index 99 | m.GramsLookup = make(map[string]int) 100 | index := 0 101 | for gram := range m.Grams { 102 | m.GramsLookup[gram] = index 103 | index++ 104 | } 105 | m.Dimensions = len(m.Grams) 106 | } 107 | 108 | func sortByValue(m map[string]int) map[string]int { 109 | type pair struct { 110 | Key string 111 | Value int 112 | } 113 | var ps []pair 114 | for k, v := range m { 115 | ps = append(ps, pair{k, v}) 116 | } 117 | sort.Slice(ps, func(i, j int) bool { 118 | return ps[i].Value > ps[j].Value 119 | }) 120 | sorted := make(map[string]int) 121 | for _, kv := range ps { 122 | sorted[kv.Key] = kv.Value 123 | } 124 | return sorted 125 | } 126 | 127 | func ngramize(value string, n int) []string { 128 | l := len(value) 129 | grams := make([]string, 0) 130 | for k := range value { 131 | if k <= l-n { 132 | gram := value[k : k+n] 133 | grams = append(grams, gram) 134 | } 135 | } 136 | return grams 137 | } 138 | -------------------------------------------------------------------------------- /encoders/string_split_dictionary.go: -------------------------------------------------------------------------------- 1 | package encoders 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | const ( 10 | splitDictionaryDelimiter = " " 11 | ) 12 | 13 | type SplitDictionaryModel struct { 14 | Dimensions int 15 | Dictionary []string 16 | Quality float64 17 | } 18 | 19 | func NewSplitDictionaryModel() *SplitDictionaryModel { 20 | return &SplitDictionaryModel{} 21 | } 22 | 23 | func (m *SplitDictionaryModel) Fit(set *Input, config *EncoderConfig) { 24 | delimiter := config.DelimiterToken 25 | for _, sample := range set.Values { 26 | value := normalizeString(sample.String) 27 | fmt.Printf("%s", value) 28 | values := strings.Split(value, delimiter) 29 | for _, v := range values { 30 | if !contains(m.Dictionary, v) { 31 | m.Dictionary = append(m.Dictionary, v) 32 | } 33 | } 34 | } 35 | fmt.Printf("%v", m.Dictionary) 36 | m.Dimensions = len(m.Dictionary) 37 | } 38 | 39 | func (m *SplitDictionaryModel) CalculateString(s string) []float64 { 40 | vector := make([]float64, m.Dimensions) 41 | idx := getIndex(m.Dictionary, s) 42 | if idx != -1 { 43 | vector[idx] = 1.0 44 | } 45 | return vector 46 | } 47 | 48 | func (m *SplitDictionaryModel) GetDimensions() int { 49 | return m.Dimensions 50 | } 51 | 52 | func (m *SplitDictionaryModel) CalculateFloats([]float64) []float64 { 53 | return []float64{} 54 | } 55 | 56 | func (m *SplitDictionaryModel) ToDump() ([]byte, error) { 57 | return json.Marshal(m) 58 | } 59 | 60 | func (m *SplitDictionaryModel) FromDump(dump []byte) error { 61 | return json.Unmarshal(dump, m) 62 | } 63 | 64 | func (m *SplitDictionaryModel) Name() string { 65 | return "splitted_dictionary" 66 | } 67 | 68 | func (m *SplitDictionaryModel) GetQuality() float64 { 69 | return m.Quality 70 | } 71 | -------------------------------------------------------------------------------- /encoders/utils.go: -------------------------------------------------------------------------------- 1 | package encoders 2 | 3 | import ( 4 | "log" 5 | "regexp" 6 | "strings" 7 | ) 8 | 9 | func normalizeString(value string) string { 10 | value = strings.ToLower(value) 11 | reg, err := regexp.Compile("[^a-zA-Z0-9]+") 12 | if err != nil { 13 | log.Fatal(err) 14 | } 15 | value = reg.ReplaceAllString(value, "") 16 | return value 17 | } 18 | -------------------------------------------------------------------------------- /engine/config.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | const ( 4 | dTries = 1 5 | dEpochs = 100 6 | dTrainingSplit = 0.7 7 | dLearningRate = 0.4 8 | dDecay = 0.005 9 | dRegressionThreshold = 0.05 10 | ) 11 | 12 | // Config has all the learning configurations necessary to learn the netowrk in the engine 13 | type Config struct { 14 | Tries int 15 | Epochs int 16 | TrainingSplit float64 17 | LearningRate float64 18 | Decay float64 19 | RegressionThreshold float64 20 | } 21 | 22 | // DefaultConfig returns the default config for the engine learner 23 | func DefaultConfig() *Config { 24 | return &Config{ 25 | Tries: dTries, 26 | Epochs: dEpochs, 27 | TrainingSplit: dTrainingSplit, 28 | LearningRate: dLearningRate, 29 | Decay: dDecay, 30 | RegressionThreshold: dRegressionThreshold, 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /engine/engine.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/breskos/gopher-learn/evaluation" 7 | "github.com/breskos/gopher-learn/learn" 8 | neural "github.com/breskos/gopher-learn/net" 9 | ) 10 | 11 | const ( 12 | runToken = "," 13 | epochToken = "." 14 | tryToken = "*" 15 | ) 16 | 17 | // Engine contains every necessary for starting the engine 18 | type Engine struct { 19 | NetworkInput int 20 | NetworkLayer []int 21 | NetworkOutput int 22 | Data *learn.Set 23 | WinnerNetwork *neural.Network 24 | WinnerEvaluation evaluation.Evaluation 25 | Verbose bool 26 | Usage neural.NetworkType 27 | Config *Config 28 | } 29 | 30 | // NewEngine creates a new Engine object 31 | func NewEngine(usage neural.NetworkType, hiddenLayer []int, data *learn.Set) *Engine { 32 | var outputLength int 33 | if neural.Regression == usage { 34 | outputLength = 1 35 | } else { 36 | outputLength = len(data.Samples[0].Output) 37 | } 38 | return &Engine{ 39 | NetworkInput: len(data.Samples[0].Vector), 40 | NetworkOutput: outputLength, 41 | NetworkLayer: hiddenLayer, 42 | Data: data, 43 | WinnerNetwork: neural.BuildNetwork(usage, len(data.Samples[0].Vector), hiddenLayer, data.ClassToLabel), 44 | WinnerEvaluation: *evaluation.NewEvaluation(usage, data.GetClasses()), 45 | Verbose: false, 46 | Usage: usage, 47 | Config: DefaultConfig(), 48 | } 49 | } 50 | 51 | // SetVerbose set verbose mode default = false 52 | func (e *Engine) SetVerbose(verbose bool) { 53 | e.Verbose = verbose 54 | } 55 | 56 | // SetRegressionThreshold sets the evaluation threshold for the regression 57 | func (e *Engine) SetRegressionThreshold(threshold float64) { 58 | e.Config.RegressionThreshold = threshold 59 | } 60 | 61 | // GetWinner returns the winner network from training 62 | func (e *Engine) GetWinner() (*neural.Network, *evaluation.Evaluation) { 63 | return e.WinnerNetwork, &e.WinnerEvaluation 64 | } 65 | 66 | // Start takes the paramter to start the engine and run it 67 | func (e *Engine) Start(criterion neural.Criterion) { 68 | network := neural.BuildNetwork(e.Usage, e.NetworkInput, e.NetworkLayer, e.Data.ClassToLabel) 69 | training, validation := split(e.Usage, e.Data, e.Config.TrainingSplit) 70 | for try := 0; try < e.Config.Tries; try++ { 71 | learning := e.Config.LearningRate 72 | if e.Verbose { 73 | fmt.Printf("\n> start try %v. training / test: %v / %v (%v)\n", (try + 1), len(training.Samples), len(validation.Samples), e.Config.TrainingSplit) 74 | } 75 | for ; learning > 0.0; learning -= e.Config.Decay { 76 | train(network, training, learning, e.Config.Epochs, e.Verbose) 77 | evaluation := evaluate(e.Usage, network, validation, training, e.Config.RegressionThreshold) 78 | if compare(e.Usage, criterion, &e.WinnerEvaluation, evaluation) { 79 | e.WinnerNetwork = copy(network) 80 | e.WinnerEvaluation = *evaluation 81 | if e.Verbose { 82 | print(&e.WinnerEvaluation) 83 | } 84 | } 85 | } 86 | if e.Verbose { 87 | fmt.Print(tryToken + "\n") 88 | } 89 | } 90 | } 91 | 92 | // SetConfig sets a new config from outside for the engine learner 93 | func (e *Engine) SetConfig(cfg *Config) { 94 | e.Config = cfg 95 | } 96 | 97 | // GetConfig returns the current engine learner configuration 98 | func (e *Engine) GetConfig() *Config { 99 | return e.Config 100 | } 101 | 102 | // Prints the current evaluation 103 | func print(e *evaluation.Evaluation) { 104 | fmt.Printf("\n [Best] acc: %.2f / bacc: %.2f / f1: %.2f / correct: %.2f / distance: %.2f\n", e.GetOverallAccuracy(), e.GetOverallBalancedAccuracy(), e.GetOverallFMeasure(), e.GetCorrectRatio(), e.GetDistance()) 105 | } 106 | -------------------------------------------------------------------------------- /engine/train.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | 7 | "github.com/breskos/gopher-learn/evaluation" 8 | "github.com/breskos/gopher-learn/learn" 9 | neural "github.com/breskos/gopher-learn/net" 10 | "github.com/breskos/gopher-learn/persist" 11 | ) 12 | 13 | // Splits a given data set by a given ratio into training and evaluation 14 | func split(usage neural.NetworkType, set *learn.Set, ratio float64) (*learn.Set, *learn.Set) { 15 | multiplier := 100 16 | normalizedRatio := int(ratio * float64(multiplier)) 17 | var training, evaluation learn.Set 18 | training.ClassToLabel = set.ClassToLabel 19 | evaluation.ClassToLabel = set.ClassToLabel 20 | for i := range set.Samples { 21 | if rand.Intn(multiplier) <= normalizedRatio { 22 | training.Samples = append(training.Samples, set.Samples[i]) 23 | } else { 24 | evaluation.Samples = append(evaluation.Samples, set.Samples[i]) 25 | } 26 | } 27 | return &training, &evaluation 28 | } 29 | 30 | // Trains the neural network with the vgiven samples for a given epoch of time and and learning rate 31 | func train(network *neural.Network, data *learn.Set, learning float64, epochs int, verbose bool) { 32 | for e := 0; e < epochs; e++ { 33 | for sample := range data.Samples { 34 | learn.Learn(network, data.Samples[sample].Vector, data.Samples[sample].Output, learning) 35 | } 36 | if verbose { 37 | fmt.Print(epochToken) 38 | } 39 | } 40 | if verbose { 41 | fmt.Print(runToken) 42 | } 43 | 44 | } 45 | 46 | // Evaluates the neural network using the current trained versions of it by a given criterion 47 | func evaluate(usage neural.NetworkType, network *neural.Network, test *learn.Set, train *learn.Set, regressionThreshold float64) *evaluation.Evaluation { 48 | evaluation := evaluation.NewEvaluation(usage, train.GetClasses()) 49 | evaluation.SetRegressionThreshold(regressionThreshold) 50 | for sample := range test.Samples { 51 | evaluation.AddDistance(network, test.Samples[sample].Vector, test.Samples[sample].Output) 52 | if neural.Classification == usage { 53 | winner := network.CalculateWinnerLabel(test.Samples[sample].Vector) 54 | evaluation.Add(test.Samples[sample].Label, winner) 55 | } else { 56 | prediction := network.Calculate(test.Samples[sample].Vector) 57 | evaluation.AddRegression(test.Samples[sample].Value, prediction[0]) 58 | } 59 | } 60 | return evaluation 61 | } 62 | 63 | // Compares two networks by a their evaluation and a given criterion 64 | func compare(usage neural.NetworkType, criterion neural.Criterion, current *evaluation.Evaluation, try *evaluation.Evaluation) bool { 65 | if current.Correct+current.Wrong == 0 { 66 | return true 67 | } 68 | switch criterion { 69 | case neural.Accuracy: 70 | if current.GetOverallAccuracy() < try.GetOverallAccuracy() { 71 | return true 72 | } 73 | case neural.BalancedAccuracy: 74 | if current.GetOverallBalancedAccuracy() < try.GetOverallBalancedAccuracy() { 75 | return true 76 | } 77 | case neural.FMeasure: 78 | if current.GetOverallFMeasure() < try.GetOverallFMeasure() { 79 | return true 80 | } 81 | case neural.Simple: 82 | if current.GetCorrectRatio() < try.GetCorrectRatio() { 83 | return true 84 | } 85 | case neural.Distance: 86 | if current.GetDistance() > try.GetDistance() { 87 | return true 88 | } 89 | } 90 | return false 91 | } 92 | 93 | // Copies a neural network from another 94 | // This function is very costly. 95 | func copy(from *neural.Network) *neural.Network { 96 | return persist.FromDump(persist.ToDump(from)) 97 | } 98 | -------------------------------------------------------------------------------- /evaluation/evaluation.go: -------------------------------------------------------------------------------- 1 | package evaluation 2 | 3 | import ( 4 | "math" 5 | 6 | neural "github.com/breskos/gopher-learn/net" 7 | ) 8 | 9 | // Evaluation contains all the structures necessary for the evaluation 10 | type Evaluation struct { 11 | Confusion map[string]map[string]int 12 | Correct int 13 | Wrong int 14 | OverallDistance float64 15 | Usage neural.NetworkType 16 | Threshold float64 17 | } 18 | 19 | // NewEvaluation creates a new evaluation object 20 | func NewEvaluation(usage neural.NetworkType, classes []string) *Evaluation { 21 | evaluation := &Evaluation{ 22 | Usage: usage, 23 | Confusion: make(map[string]map[string]int), 24 | } 25 | for i := range classes { 26 | evaluation.Confusion[classes[i]] = make(map[string]int) 27 | for j := range classes { 28 | evaluation.Confusion[classes[i]][classes[j]] = 0 29 | } 30 | } 31 | return evaluation 32 | } 33 | 34 | // SetRegressionThreshold sets the threshold if you are trying to do Pos / Neg with a regressor 35 | func (e *Evaluation) SetRegressionThreshold(threshold float64) { 36 | e.Threshold = threshold 37 | } 38 | 39 | // Add adds a new data point to the evaluation 40 | func (e *Evaluation) Add(labeledClass, predictedClass string) { 41 | if _, ok := e.Confusion[labeledClass]; ok { 42 | if _, ok := e.Confusion[labeledClass][predictedClass]; ok { 43 | e.Confusion[labeledClass][predictedClass]++ 44 | } else { 45 | e.Confusion[labeledClass][predictedClass] = 1 46 | } 47 | } else { 48 | e.Confusion[labeledClass] = make(map[string]int) 49 | e.Confusion[labeledClass][predictedClass] = 1 50 | } 51 | if labeledClass == predictedClass { 52 | e.Correct++ 53 | } else { 54 | e.Wrong++ 55 | } 56 | } 57 | 58 | // AddRegression add a predicted regresssion value to tht set 59 | func (e *Evaluation) AddRegression(label, predicted float64) { 60 | if math.Abs(label-predicted) >= e.Threshold { 61 | e.Wrong++ 62 | } else { 63 | e.Correct++ 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /evaluation/metrics.go: -------------------------------------------------------------------------------- 1 | package evaluation 2 | 3 | import ( 4 | "math" 5 | 6 | neural "github.com/breskos/gopher-learn/net" 7 | ) 8 | 9 | // GetTruePositives returns TP 10 | func (e *Evaluation) GetTruePositives(label string) int { 11 | return e.Confusion[label][label] 12 | } 13 | 14 | // GetFalsePositives returns FP 15 | func (e *Evaluation) GetFalsePositives(label string) int { 16 | s := 0 17 | for l := range e.Confusion { 18 | if l != label { 19 | s += e.Confusion[l][label] 20 | } 21 | } 22 | return s 23 | } 24 | 25 | // GetTrueNegatives returns TN 26 | func (e *Evaluation) GetTrueNegatives(label string) int { 27 | s := 0 28 | for la := range e.Confusion { 29 | if la != label { 30 | for l := range e.Confusion[la] { 31 | if l != label { 32 | s += e.Confusion[la][l] 33 | } 34 | } 35 | } 36 | } 37 | return s 38 | } 39 | 40 | // GetFalseNegatives returns FNs 41 | func (e *Evaluation) GetFalseNegatives(label string) int { 42 | s := 0 43 | for la := range e.Confusion[label] { 44 | for l := range e.Confusion[la] { 45 | if l != label && la == label { 46 | s += e.Confusion[la][l] 47 | } 48 | } 49 | } 50 | return s 51 | } 52 | 53 | // GetPositives TP + FN 54 | func (e *Evaluation) GetPositives(label string) int { 55 | return e.GetTruePositives(label) + e.GetFalseNegatives(label) 56 | } 57 | 58 | // GetNegatives FP + TN 59 | func (e *Evaluation) GetNegatives(label string) int { 60 | return e.GetFalsePositives(label) + e.GetTrueNegatives(label) 61 | } 62 | 63 | // GetAccuracy (TP+TN) / (P+N) 64 | func (e *Evaluation) GetAccuracy(label string) float64 { 65 | if float64(e.GetPositives(label)+e.GetNegatives(label)) == 0.0 { 66 | return 0.0 67 | } 68 | return float64(e.GetTruePositives(label)+e.GetTrueNegatives(label)) / float64(e.GetPositives(label)+e.GetNegatives(label)) 69 | } 70 | 71 | // GetRecall TP/P, TP/(TP + FN) 72 | func (e *Evaluation) GetRecall(label string) float64 { 73 | if float64(e.GetPositives(label)) == 0.0 { 74 | return 0.0 75 | } 76 | return float64(e.GetTruePositives(label)) / float64(e.GetPositives(label)) 77 | } 78 | 79 | // GetSensitivity like recall 80 | func (e *Evaluation) GetSensitivity(label string) float64 { 81 | return e.GetRecall(label) 82 | } 83 | 84 | // GetSpecificity TN / N, TN/(FP+TN) 85 | func (e *Evaluation) GetSpecificity(label string) float64 { 86 | if float64(e.GetNegatives(label)) == 0.0 { 87 | return 0.0 88 | } 89 | return float64(e.GetTrueNegatives(label)) / float64(e.GetNegatives(label)) 90 | } 91 | 92 | // GetPrecision TP/(TP+FP) 93 | func (e *Evaluation) GetPrecision(label string) float64 { 94 | if float64(e.GetTruePositives(label)+e.GetFalsePositives(label)) == 0.0 { 95 | return 0.0 96 | } 97 | return float64(e.GetTruePositives(label)) / float64(e.GetTruePositives(label)+e.GetFalsePositives(label)) 98 | } 99 | 100 | // GetFallout FP / N 101 | func (e *Evaluation) GetFallout(label string) float64 { 102 | if float64(e.GetNegatives(label)) == 0.0 { 103 | return 0.0 104 | } 105 | return float64(e.GetFalsePositives(label)) / float64(e.GetNegatives(label)) 106 | } 107 | 108 | // GetFalsePositiveRate same as fallout 109 | func (e *Evaluation) GetFalsePositiveRate(label string) float64 { 110 | return e.GetFallout(label) 111 | } 112 | 113 | // GetFalseDiscoveryRate FP / (FP+TP) 114 | func (e *Evaluation) GetFalseDiscoveryRate(label string) float64 { 115 | if float64(e.GetFalsePositives(label)+e.GetTruePositives(label)) == 0.0 { 116 | return 0.0 117 | } 118 | return float64(e.GetFalsePositives(label)) / float64(e.GetFalsePositives(label)+e.GetTruePositives(label)) 119 | } 120 | 121 | // GetNegativePredictionValue TN/(TN+FN) 122 | func (e *Evaluation) GetNegativePredictionValue(label string) float64 { 123 | if float64(e.GetTrueNegatives(label)+e.GetFalseNegatives(label)) == 0.0 { 124 | return 0.0 125 | } 126 | return float64(e.GetTrueNegatives(label)) / float64(e.GetTrueNegatives(label)+e.GetFalseNegatives(label)) 127 | } 128 | 129 | // GetFMeasure 2TP/(2TP+FP+FN) 130 | func (e *Evaluation) GetFMeasure(label string) float64 { 131 | if float64(2*e.GetTruePositives(label)+e.GetFalsePositives(label)+e.GetFalseNegatives(label)) == 0.0 { 132 | return 0.0 133 | } 134 | return 2.0 * float64(e.GetTruePositives(label)) / float64(2*e.GetTruePositives(label)+e.GetFalsePositives(label)+e.GetFalseNegatives(label)) 135 | } 136 | 137 | // GetBalancedAccuracy (TP/P + TN/N) / 2 138 | func (e *Evaluation) GetBalancedAccuracy(label string) float64 { 139 | var positives, negatives float64 140 | if float64(e.GetPositives(label)) == 0.0 { 141 | positives = 0.0 142 | } else { 143 | positives = float64(e.GetTruePositives(label)) / float64(e.GetPositives(label)) 144 | } 145 | if float64(e.GetNegatives(label)) == 0.0 { 146 | negatives = 0.0 147 | } else { 148 | negatives = float64(e.GetTrueNegatives(label)) / float64(e.GetNegatives(label)) 149 | } 150 | return (positives + negatives) / 2.0 151 | } 152 | 153 | // GetOverallBalancedAccuracy calculates for the training evaluation 154 | func (e *Evaluation) GetOverallBalancedAccuracy() float64 { 155 | classes := float64(len(e.Confusion)) 156 | sum := 0.0 157 | for k := range e.Confusion { 158 | sum += e.GetBalancedAccuracy(k) 159 | } 160 | return sum / classes 161 | } 162 | 163 | // GetOverallAccuracy calculates for the training evaluation 164 | func (e *Evaluation) GetOverallAccuracy() float64 { 165 | classes := float64(len(e.Confusion)) 166 | sum := 0.0 167 | for k := range e.Confusion { 168 | sum += e.GetAccuracy(k) 169 | } 170 | return sum / classes 171 | } 172 | 173 | // GetOverallFMeasure calculates for the training evaluation 174 | func (e *Evaluation) GetOverallFMeasure() float64 { 175 | classes := float64(len(e.Confusion)) 176 | sum := 0.0 177 | for k := range e.Confusion { 178 | sum += e.GetFMeasure(k) 179 | } 180 | return sum / classes 181 | } 182 | 183 | // GetInformedness = Sensitivity + Specificity − 1 184 | func (e *Evaluation) GetInformedness(label string) float64 { 185 | return e.GetSensitivity(label) + e.GetSpecificity(label) - 1.0 186 | } 187 | 188 | // GetMarkedness = Precision + NegativePredictionValue − 1 189 | func (e *Evaluation) GetMarkedness(label string) float64 { 190 | return e.GetPrecision(label) + e.GetNegativePredictionValue(label) - 1 191 | } 192 | 193 | // AddDistance adds distance between ideal output and output of the network 194 | func (e *Evaluation) AddDistance(n *neural.Network, in, ideal []float64) float64 { 195 | // This function was part of the former go-neural and moved to this package. 196 | out := n.Calculate(in) 197 | var d float64 198 | for i := range out { 199 | d += math.Pow(out[i]-ideal[i], 2) 200 | } 201 | e.OverallDistance += d / 2.0 202 | return d / 2.0 203 | } 204 | 205 | // GetDistance returns the distance from the evaluation 206 | func (e *Evaluation) GetDistance() float64 { 207 | return e.OverallDistance 208 | } 209 | 210 | // GetCorrectRatio returns correct classified samples ratio 211 | func (e *Evaluation) GetCorrectRatio() float64 { 212 | return float64(e.Correct) / float64(e.Wrong+e.Correct) 213 | } 214 | -------------------------------------------------------------------------------- /evaluation/print.go: -------------------------------------------------------------------------------- 1 | package evaluation 2 | 3 | import "fmt" 4 | 5 | // PrintConfusionMatrix prints the confusion matrix of the evaluation 6 | func (e *Evaluation) PrintConfusionMatrix() { 7 | fmt.Printf("\t|") 8 | for k := range e.Confusion { 9 | fmt.Printf("%v\t|", k) 10 | } 11 | fmt.Print("\n") 12 | for cl := range e.Confusion { 13 | fmt.Printf("%v\t|", cl) 14 | for c := range e.Confusion[cl] { 15 | fmt.Printf("%v\t|", e.Confusion[cl][c]) 16 | } 17 | fmt.Printf("\n") 18 | } 19 | 20 | } 21 | 22 | // PrintSummaries prints the summaries of all classes 23 | func (e *Evaluation) PrintSummaries() { 24 | for class := range e.Confusion { 25 | e.PrintSummary(class) 26 | } 27 | } 28 | 29 | // PrintRegressionSummary returns a summary of the evaluated regression 30 | func (e *Evaluation) PrintRegressionSummary() { 31 | fmt.Println("summary") 32 | fmt.Printf("correct: %v\n", e.Correct) 33 | fmt.Printf("wrong: %v\n", e.Wrong) 34 | fmt.Printf("ratio: %v\n", float64(e.Correct)/float64(e.Correct+e.Wrong)) 35 | } 36 | 37 | // PrintSummary returns a summary 38 | func (e *Evaluation) PrintSummary(label string) { 39 | fmt.Printf("summary for class %v\n", label) 40 | fmt.Printf(" * TP: %v TN: %v FP: %v FN: %v\n", e.GetTruePositives(label), e.GetTrueNegatives(label), e.GetFalsePositives(label), e.GetFalseNegatives(label)) 41 | fmt.Printf(" * Recall/Sensitivity: %.3f\n", e.GetRecall(label)) 42 | fmt.Printf(" * Precision: %.3f\n", e.GetPrecision(label)) 43 | fmt.Printf(" * Fallout/FalsePosRate: %.3f\n", e.GetFallout(label)) 44 | fmt.Printf(" * False Discovey Rate: %.3f\n", e.GetFalseDiscoveryRate(label)) 45 | fmt.Printf(" * Negative Prediction Rate: %.3f\n", e.GetNegativePredictionValue(label)) 46 | fmt.Println("--") 47 | fmt.Printf(" * Accuracy: %.3f\n", e.GetAccuracy(label)) 48 | fmt.Printf(" * F-Measure: %.3f\n", e.GetFMeasure(label)) 49 | fmt.Printf(" * Balanced Accuracy: %.3f\n", e.GetBalancedAccuracy(label)) 50 | fmt.Printf(" * Informedness: %.3f\n", e.GetInformedness(label)) 51 | fmt.Printf(" * Markedness: %.3f\n", e.GetMarkedness(label)) 52 | 53 | } 54 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Examples for gopher-learn 2 | 3 | ![gopher-learn-logo](http://alexander.bre.sk/x/gopher-neural-small.png " The Gopher Neural logo ") 4 | 5 | ## Important 6 | All the data needed for the examples can be found at [gopher-learn-data](https://github.com/breskos/gopher-learn-data). 7 | 8 | ## Sonar 9 | 10 | Basic example that uses the engine of gopher-neural to train a small neural network with basic parameters. 11 | More information in sonar ReadMe file. 12 | Data from: https://archive.ics.uci.edu/ml/datasets/Connectionist+Bench+%28Sonar%2C+Mines+vs.+Rocks%29 13 | 14 | ## Wine quality 15 | 16 | In this example we train a regressor (we don't have classes but real value to determine). 17 | The quality of the wine is very important because wine is tasty (or should be). 18 | So here we have some criteria we can use to determine good from bad wine. 19 | Data from: http://archive.ics.uci.edu/ml/datasets/Wine+Quality 20 | 21 | ## Dictionary (Encoder) 22 | 23 | This example shows the encoder to a dictionary approach. 24 | The data was collected by Alexander Bresk. 25 | 26 | ## NGram (Encoder) 27 | 28 | This example shows how to encode strings via ngram encoder. 29 | The data was collected by Alexander Bresk. 30 | 31 | ## Online Generator (Online) 32 | 33 | This example shows the online learning part of gopher-learn. 34 | It shows you how to apply this functionality. 35 | 36 | ## Online Sonar (Online) 37 | 38 | Using the data from the Sonar example, this example shows you how to use it in online mode. 39 | -------------------------------------------------------------------------------- /examples/dictionary/README.md: -------------------------------------------------------------------------------- 1 | # Dictionary 2 | 3 | This example shows how to use the encoder for strings to dictionaries. 4 | If you need more information on this encoder check: docs/encoders.md -------------------------------------------------------------------------------- /examples/dictionary/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "strings" 9 | 10 | "github.com/breskos/gopher-learn/encoders" 11 | "github.com/breskos/gopher-learn/engine" 12 | "github.com/breskos/gopher-learn/learn" 13 | neural "github.com/breskos/gopher-learn/net" 14 | ) 15 | 16 | const ( 17 | dataFile = "data.phrase" 18 | delimiter = "," 19 | tries = 1 20 | epochs = 100 21 | trainingSplit = 0.7 22 | learningRate = 0.4 23 | decay = 0.005 24 | model = "onoff" 25 | ) 26 | 27 | func main() { 28 | e := encoders.NewEncoder("answer-representation") 29 | input := encoders.NewInput(model, encoders.String) 30 | input.AddString("ON,OFF") 31 | input.AddString("OFF,ON") 32 | input.AddString("OFF,OFF") 33 | input.AddString("ON,ON") 34 | e.Scan(model, input, encoders.Automatic) 35 | e.Transform(model, input) 36 | e.Explain() 37 | 38 | // TODO(abresk) here I noticed that Sample, Set in learn are not optimized to be used in this manner 39 | // They were designed to load samples from file. 40 | // Get vectors for training 41 | output := make(map[string]int) 42 | output["ON"] = 0 43 | output["OFF"] = 1 44 | learningSet := learn.NewSet(neural.Classification) 45 | learningSet.AddClass("ON") // 0 46 | learningSet.AddClass("OFF") // 1 47 | data := []string{"ON,OFF,ON", "OFF,ON,ON", "OFF,OFF,OFF", "ON,ON,ON"} 48 | for i := 0; i < 50; i++ { 49 | for _, v := range data { 50 | splitted := strings.Split(v, delimiter) 51 | input := fmt.Sprintf("%s,%s", splitted[0], splitted[1]) 52 | vector := e.Encode(model, encoders.Unified{String: input}) 53 | outVec := []float64{0.0, 0.0} 54 | outVec[output[splitted[1]]] = 1.0 55 | learningSet.AddSample(learn.NewClassificationSample(vector, outVec, splitted[2])) 56 | } 57 | } 58 | 59 | // training the network 60 | en := engine.NewEngine(neural.Classification, []int{3}, learningSet) 61 | en.SetVerbose(true) 62 | en.SetConfig(&engine.Config{ 63 | Tries: tries, 64 | Epochs: epochs, 65 | TrainingSplit: trainingSplit, 66 | LearningRate: learningRate, 67 | Decay: decay, 68 | }) 69 | en.Start(neural.Distance) 70 | network, evaluation := en.GetWinner() 71 | evaluation.PrintSummary("ON") 72 | fmt.Println() 73 | evaluation.PrintSummary("OFF") 74 | 75 | // testing with own example 76 | for _, v := range data { 77 | splitted := strings.Split(v, delimiter) 78 | input := fmt.Sprintf("%s,%s", splitted[0], splitted[1]) 79 | vector := e.Encode(model, encoders.Unified{String: input}) 80 | w := network.CalculateWinnerLabel(vector) 81 | fmt.Printf("%v -> %v\n", splitted[2], w) 82 | } 83 | } 84 | 85 | func getData() []string { 86 | file, err := os.Open("data.phrase") 87 | 88 | if err != nil { 89 | log.Fatalf("failed to open") 90 | 91 | } 92 | scanner := bufio.NewScanner(file) 93 | scanner.Split(bufio.ScanLines) 94 | var text []string 95 | for scanner.Scan() { 96 | text = append(text, scanner.Text()) 97 | } 98 | file.Close() 99 | return text 100 | } 101 | -------------------------------------------------------------------------------- /examples/float-reducer/README.md: -------------------------------------------------------------------------------- 1 | # Float Reducer 2 | 3 | The FloatReducer examples shows how the encoder works for float slices. 4 | If you need more information on the FloatReducer see docs/encoders.md. 5 | -------------------------------------------------------------------------------- /examples/float-reducer/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/breskos/gopher-learn/encoders" 7 | ) 8 | 9 | const ( 10 | model = "floatreducer" 11 | ) 12 | 13 | func main() { 14 | e := encoders.NewEncoder("float reducer test") 15 | input := encoders.NewInput(model, encoders.Floats) 16 | // here we create some data points. 17 | // As you can see dimension 0 and 1 are very much correlated. 18 | // From these data points the float reducer strips one of the dimensions of 0 and 1. 19 | // This FloatReducer is very interesting if you have large float spaces. 20 | // It also erases dimensions that are not necessary because they just deliver one value or no information gain. 21 | input.AddFloats([]float64{1.0, 0.0, 3.7}) 22 | input.AddFloats([]float64{2.0, 0.9, 0.3}) 23 | input.AddFloats([]float64{3.0, 1.6, 1.3}) 24 | input.AddFloats([]float64{4.0, 2.9, 4.2}) 25 | e.Scan(model, input, encoders.FloatReducer) 26 | e.Transform(model, input) 27 | e.Explain() 28 | vector := e.Encode(model, encoders.Unified{Float: []float64{1.0, 0.0, 3.7}, Type: encoders.Floats}) 29 | fmt.Printf("encoded vector: %v", vector) 30 | 31 | } 32 | -------------------------------------------------------------------------------- /examples/ngram/README.md: -------------------------------------------------------------------------------- 1 | # NGram 2 | 3 | This example shows you how to use the NGram encoder for srings. 4 | If you need more information on the encoders, visit: docs/encoders.md. -------------------------------------------------------------------------------- /examples/ngram/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "strings" 9 | 10 | "github.com/breskos/gopher-learn/encoders" 11 | "github.com/breskos/gopher-learn/engine" 12 | "github.com/breskos/gopher-learn/learn" 13 | neural "github.com/breskos/gopher-learn/net" 14 | "github.com/breskos/gopher-learn/persist" 15 | ) 16 | 17 | const ( 18 | dataFile = "data.phrase" 19 | delimiter = "#" 20 | tries = 1 21 | epochs = 100 22 | trainingSplit = 0.7 23 | learningRate = 0.4 24 | decay = 0.005 25 | modelName = "answer-type" 26 | ) 27 | 28 | /* 29 | Different states to test dictionary 30 | 31 | */ 32 | func main() { 33 | data := getData() 34 | e := encoders.NewEncoder("dictionary") 35 | set := encoders.NewInput(modelName, encoders.String) 36 | for _, v := range data { 37 | splitted := strings.Split(v, delimiter) 38 | set.AddString(splitted[0]) 39 | } 40 | e.Scan(modelName, set, encoders.Automatic) 41 | e.Transform(modelName, set) 42 | e.Explain() 43 | 44 | // this is just an example how to persist the encoders 45 | persist.EncoderToFile("encoder.json", e) 46 | e2, err := persist.EncoderFromFile("encoder.json") 47 | if err != nil { 48 | log.Fatalf("error persisting encoder: %v", err) 49 | } 50 | fmt.Println("after persisting") 51 | e2.Explain() 52 | 53 | // TODO(abresk) here I noticed that Sample, Set in learn are not optimized to be used in this manner 54 | // They were designed to load samples from file. 55 | // Get vectors for training 56 | output := make(map[string]int) 57 | output["FACT"] = 0 58 | output["PARAGRAPH"] = 1 59 | output["LIST"] = 2 60 | learningSet := learn.NewSet(neural.Classification) 61 | learningSet.AddClass("FACT") // 0 62 | learningSet.AddClass("PARAGRAPH") // 1 63 | learningSet.AddClass("LIST") // 2 64 | 65 | for _, v := range data { 66 | splitted := strings.Split(v, delimiter) 67 | input := encoders.Unified{String: splitted[0]} 68 | vector := e.Encode(modelName, input) 69 | outVec := []float64{0.0, 0.0, 0.0} 70 | outVec[output[splitted[1]]] = 1.0 71 | learningSet.AddSample(learn.NewClassificationSample(vector, outVec, splitted[1])) 72 | } 73 | 74 | // training the network 75 | en := engine.NewEngine(neural.Classification, []int{80}, learningSet) 76 | en.SetVerbose(true) 77 | en.SetConfig(&engine.Config{ 78 | Tries: tries, 79 | Epochs: epochs, 80 | TrainingSplit: trainingSplit, 81 | LearningRate: learningRate, 82 | Decay: decay, 83 | }) 84 | en.Start(neural.Distance) 85 | network, evaluation := en.GetWinner() 86 | evaluation.PrintSummary("FACT") 87 | fmt.Println() 88 | evaluation.PrintSummary("PARAGRAPH") 89 | fmt.Println() 90 | evaluation.PrintSummary("LIST") 91 | 92 | // testing with own example 93 | vector := e2.Encode(modelName, encoders.Unified{String: "Wieviel Saft ist drin?"}) 94 | w := network.CalculateWinnerLabel(vector) 95 | fmt.Printf("%v -> %v\n", "FACT", w) 96 | 97 | vector = e2.Encode(modelName, encoders.Unified{String: "Welche Optionen gibt es um einen Org zu besiegen?"}) 98 | w = network.CalculateWinnerLabel(vector) 99 | fmt.Printf("%v -> %v\n", "LIST", w) 100 | 101 | vector = e2.Encode(modelName, encoders.Unified{String: "Was ist ein Haus?"}) 102 | w = network.CalculateWinnerLabel(vector) 103 | fmt.Printf("%v -> %v\n", "PARAGRAPH", w) 104 | 105 | vector = e2.Encode(modelName, encoders.Unified{String: "Woraus besteht ein Garten?"}) 106 | w = network.CalculateWinnerLabel(vector) 107 | fmt.Printf("%v -> %v\n", "LIST", w) 108 | 109 | } 110 | 111 | func getData() []string { 112 | file, err := os.Open("data.phrase") 113 | 114 | if err != nil { 115 | log.Fatalf("failed to open") 116 | 117 | } 118 | scanner := bufio.NewScanner(file) 119 | scanner.Split(bufio.ScanLines) 120 | var text []string 121 | for scanner.Scan() { 122 | text = append(text, scanner.Text()) 123 | } 124 | file.Close() 125 | return text 126 | } 127 | -------------------------------------------------------------------------------- /examples/online-generator/README.md: -------------------------------------------------------------------------------- 1 | # Input generator for online Learning 2 | 3 | Abstract: In this task a generator generates random data points but with data that can easily be discriminated by the network. 4 | 5 | ## Example 6 | 7 | After starting the example, the generator runs and produces data points for a 2-class problem. 8 | With this we want to show that the network is able to learn from stream data with adapting itself. 9 | 10 | Execute the example using the following command: 11 | 12 | ``` 13 | > go run main.go 14 | ``` 15 | -------------------------------------------------------------------------------- /examples/online-generator/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "time" 7 | 8 | "github.com/breskos/gopher-learn/learn" 9 | neural "github.com/breskos/gopher-learn/net" 10 | "github.com/breskos/gopher-learn/online" 11 | ) 12 | 13 | const ( 14 | classLabelY = "Y" 15 | classLabelN = "N" 16 | numberOfInputs = 7 17 | hiddenNeurons = 30 18 | onlineFile = "online_learner.json" 19 | ) 20 | 21 | func main() { 22 | rand.Seed(time.Now().UnixNano()) 23 | set := learn.NewSet(neural.Classification) 24 | set.AddClass(classLabelY) // class on index 0 25 | set.AddClass(classLabelN) // class on index 1 26 | classes := []string{classLabelY, classLabelN} 27 | o := online.NewOnline(neural.Classification, numberOfInputs, []int{hiddenNeurons}, set) 28 | // o.SetConfig(&online.Config{}) you can also make use of the Config to fine tune the internals 29 | // you can set Verbose to true to gain more insights 30 | o.SetVerbose(true) 31 | fmt.Printf("set: %v\n", set) 32 | for i := 0; i < 2000; i++ { 33 | class := rand.Intn(2) 34 | classLabel := classes[class] 35 | vector, target := createFeatureVector(classLabel) 36 | // target could also be replaced with: set.GenerateOutputVector(classLabel) 37 | sample := learn.NewClassificationSample(vector, target, classLabel) 38 | // sample := learn.NewClassificationSample(vector, target, classLabel) 39 | // here we inject a new sample from the generator 40 | // if the data points already exists in the set (we are not forcing to override it) 41 | o.Inject(sample, false) 42 | if i%20 == 0 { 43 | o.Iterate() // this function returns the F-Measure of the current state 44 | } 45 | } 46 | // The functions below allow you to save the state of the Online learner to and to read them from file 47 | // in order to continue with the work. 48 | // persist.OnlineToFile(onlineFile, o) 49 | // o, err := persist.OnlineFromFile(onlineFile) 50 | } 51 | 52 | func createFeatureVector(class string) ([]float64, []float64) { 53 | featuresY := []float64{1.0, 3.0, 10.5, 5.0, 4.0, 3.3, 5.2} 54 | featuresN := []float64{1.0, 8.7, 1.3, 3.3, 4.0, 10.1, 5.1} 55 | target := []float64{0.0, 0.0} 56 | var vector []float64 57 | if "Y" == class { 58 | for _, v := range featuresY { 59 | vector = append(vector, (v-1)+rand.Float64()*(v+1)) 60 | 61 | } 62 | target[0] = 1.0 63 | } else { 64 | for _, v := range featuresN { 65 | vector = append(vector, (v-1)+rand.Float64()*(v+1)) 66 | } 67 | target[1] = 1.0 68 | } 69 | return vector, target 70 | } 71 | -------------------------------------------------------------------------------- /examples/online-sonar/README.md: -------------------------------------------------------------------------------- 1 | # Sonar Data Set for Online Learning 2 | 3 | Abstract: The task is to train a network to discriminate between sonar signals bounced off a metal cylinder and those bounced off a roughly cylindrical rock. 4 | 5 | Connectionist Bench (Sonar, Mines vs. Rocks) Data Set 6 | 7 | Found here: https://archive.ics.uci.edu/ml/datasets/Connectionist+Bench+%28Sonar%2C+Mines+vs.+Rocks%29 8 | 9 | ## Example 10 | 11 | The data set was also used for the simple sonar example where a basic Multi Layer Perceptron was built. 12 | This example explains the use of the Gopher-Learn online mode. 13 | In contrast to the simple example, where the data was initially given to the network, the data was given piece by piece to the network. 14 | This can be seen as the stream approach. 15 | Data is constantly flowing in and the network has to adapt. 16 | 17 | Execute the example using the following command: 18 | 19 | ``` 20 | > go run main.go 21 | ``` 22 | -------------------------------------------------------------------------------- /examples/online-sonar/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/breskos/gopher-learn/learn" 7 | neural "github.com/breskos/gopher-learn/net" 8 | "github.com/breskos/gopher-learn/online" 9 | "github.com/breskos/gopher-learn/persist" 10 | ) 11 | 12 | const ( 13 | dataFile = "data.csv" 14 | networkFile = "network.json" 15 | dataSetFile = "set.json" 16 | hiddenNeurons = 30 17 | ) 18 | 19 | func main() { 20 | // data from file that we want to stream in 21 | data := learn.NewSet(neural.Classification) 22 | ok, err := data.LoadFromCSV(dataFile) 23 | if !ok || nil != err { 24 | fmt.Printf("something went wrong -> %v", err) 25 | } 26 | // we create an empty set with correct number of inputs and classes 27 | onlineSet := learn.NewSet(neural.Classification) 28 | onlineSet.AddClass("R") 29 | onlineSet.AddClass("M") 30 | 31 | o := online.NewOnline(neural.Classification, len(data.Samples[0].Vector), []int{hiddenNeurons}, onlineSet) 32 | // o.SetConfig(&online.Config{}) you can also make use of the Config to fine tune the internals 33 | o.SetVerbose(true) 34 | 35 | l := len(data.Samples) 36 | for i := 0; i < l; i++ { 37 | o.Inject(data.Samples[i], false) 38 | if i%5 == 0 { 39 | fmt.Printf("\n\nAFTER INJECTING %d samples\n", i) 40 | o.Iterate() // this function also returns the F-Measure 41 | 42 | } 43 | } 44 | 45 | err = persist.SetToFile(dataSetFile, o.Data) 46 | if err != nil { 47 | fmt.Printf("error while saving data set: %v\n", err) 48 | } 49 | err = persist.ToFile(networkFile, o.Network) 50 | if err != nil { 51 | fmt.Printf("error while saving network: %v\n", err) 52 | } 53 | 54 | network2, err := persist.FromFile(networkFile) 55 | if err != nil { 56 | fmt.Printf("error while loading network: %v\n", err) 57 | } 58 | 59 | w := network2.CalculateWinnerLabel(data.Samples[0].Vector) 60 | fmt.Printf("%v -> %v\n", data.Samples[0].Label, w) 61 | w = network2.CalculateWinnerLabel(data.Samples[70].Vector) 62 | fmt.Printf("%v -> %v\n", data.Samples[70].Label, w) 63 | w = network2.CalculateWinnerLabel(data.Samples[120].Vector) 64 | fmt.Printf("%v -> %v\n", data.Samples[120].Label, w) 65 | } 66 | -------------------------------------------------------------------------------- /examples/sonar/README.md: -------------------------------------------------------------------------------- 1 | # Sonar Data Set 2 | 3 | Abstract: The task is to train a network to discriminate between sonar signals bounced off a metal cylinder and those bounced off a roughly cylindrical rock. 4 | 5 | Connectionist Bench (Sonar, Mines vs. Rocks) Data Set 6 | 7 | Found here: https://archive.ics.uci.edu/ml/datasets/Connectionist+Bench+%28Sonar%2C+Mines+vs.+Rocks%29 8 | 9 | ## Example 10 | 11 | In this example a data set was used to demonstrate 12 | * a MLP with 100 hidden neurons 13 | * that uses CriterionDistance to decide for the best model 14 | * gives a summary of the training 15 | * and persists the file 16 | 17 | Below the command line output can be seen. 18 | ``` 19 | > go run main.go 20 | 21 | ... 22 | 23 | summary for class R 24 | * TP: 23 TN: 30 FP: 0 FN: 8 25 | * Recall/Sensitivity: 0.7419354838709677 26 | * Precision: 1 27 | * Fallout/FalsePosRate: 0 28 | * False Discovey Rate: 0 29 | * Negative Prediction Rate: 0.7894736842105263 30 | -- 31 | * Accuracy: 0.8688524590163934 32 | * F-Measure: 0.8518518518518519 33 | * Balanced Accuracy: 0.8709677419354839 34 | * Informedness: 0.7419354838709677 35 | * Markedness: 0.7894736842105263 36 | 37 | summary for class M 38 | * TP: 30 TN: 23 FP: 8 FN: 0 39 | * Recall/Sensitivity: 1 40 | * Precision: 0.7894736842105263 41 | * Fallout/FalsePosRate: 0.25806451612903225 42 | * False Discovey Rate: 0.21052631578947367 43 | * Negative Prediction Rate: 1 44 | -- 45 | * Accuracy: 0.8688524590163934 46 | * F-Measure: 0.8823529411764706 47 | * Balanced Accuracy: 0.8709677419354839 48 | * Informedness: 0.7419354838709677 49 | * Markedness: 0.7894736842105263 50 | ``` 51 | -------------------------------------------------------------------------------- /examples/sonar/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/breskos/gopher-learn/engine" 7 | "github.com/breskos/gopher-learn/learn" 8 | "github.com/breskos/gopher-learn/net" 9 | "github.com/breskos/gopher-learn/persist" 10 | ) 11 | 12 | const ( 13 | dataFile = "data.csv" 14 | networkFile = "network.json" 15 | dataSetFile = "set.json" 16 | tries = 1 17 | epochs = 100 18 | trainingSplit = 0.7 19 | learningRate = 0.4 20 | decay = 0.005 21 | ) 22 | 23 | func main() { 24 | data := learn.NewSet(net.Classification) 25 | ok, err := data.LoadFromCSV(dataFile) 26 | if !ok || nil != err { 27 | fmt.Printf("something went wrong -> %v", err) 28 | } 29 | e := engine.NewEngine(net.Classification, []int{100}, data) 30 | e.SetVerbose(true) 31 | e.SetConfig(&engine.Config{ 32 | Tries: tries, 33 | Epochs: epochs, 34 | TrainingSplit: trainingSplit, 35 | LearningRate: learningRate, 36 | Decay: decay, 37 | }) 38 | e.Start(net.Distance) 39 | network, evaluation := e.GetWinner() 40 | 41 | evaluation.PrintSummary("R") 42 | fmt.Println() 43 | evaluation.PrintSummary("M") 44 | 45 | err = persist.SetToFile(dataSetFile, data) 46 | if err != nil { 47 | fmt.Printf("error while saving data set: %v\n", err) 48 | } 49 | err = persist.ToFile(networkFile, network) 50 | if err != nil { 51 | fmt.Printf("error while saving network: %v\n", err) 52 | } 53 | 54 | network2, err := persist.FromFile(networkFile) 55 | if err != nil { 56 | fmt.Printf("error while loading network: %v\n", err) 57 | } 58 | data2, err := persist.SetFromFile(dataSetFile) 59 | if err != nil { 60 | fmt.Printf("error while loading data set from file: %v\n", err) 61 | } 62 | 63 | w := network2.CalculateWinnerLabel(data2.Samples[0].Vector) 64 | fmt.Printf("%v -> %v\n", data2.Samples[0].Label, w) 65 | w = network2.CalculateWinnerLabel(data.Samples[70].Vector) 66 | fmt.Printf("%v -> %v\n", data2.Samples[70].Label, w) 67 | w = network2.CalculateWinnerLabel(data.Samples[120].Vector) 68 | fmt.Printf("%v -> %v\n", data2.Samples[120].Label, w) 69 | 70 | // print confusion matrix 71 | fmt.Println(" * Confusion Matrix *") 72 | evaluation.PrintConfusionMatrix() 73 | } 74 | -------------------------------------------------------------------------------- /examples/wine-quality/README.md: -------------------------------------------------------------------------------- 1 | # Wine quality 2 | 3 | Abstract: Two datasets are included, related to red and white vinho verde wine samples, from the north of Portugal. The goal is to model wine quality based on physicochemical tests (see [Cortez et al., 2009]). 4 | http://archive.ics.uci.edu/ml/datasets/Wine+Quality 5 | 6 | ## Data 7 | |fixed acidity|volatile acidity|citric acid|residual sugar|chlorides|free sulfur dioxide|total sulfur dioxide|density|pH|sulphates|alcohol|__quality__| 8 | |-------------|----------------|-----------|--------------|---------|-------------------|--------------------|-------|--|---------|-------|-------| 9 | |7|0.27|0.36|20.7|0.045|45|170|1.001|3|0.45|8.8|6| 10 | |6.3|0.3|0.34|1.6|0.049|14|132|0.994|3.3|0.49|9.5|6| 11 | |8.1|0.28|0.4|6.9|0.05|30|97|0.9951|3.26|0.44|10.1|6| 12 | 13 | 14 | 15 | ## Example 16 | This example demonstrate the application of a regressor: 17 | * with 100 epochs, 70 percent training data, 0.9 learning with 0.001 decay 18 | * Regression threshold of 0.2 19 | * 100 hidden neurons 20 | 21 | ## Learning 22 | The learning here is that the regressor decides between correct vs. wrong classified using a threshold. You can change this threshold to bring more tolerance to the system. 23 | 24 | ## Source 25 | Paulo Cortez, University of Minho, Guimarães, Portugal, http://www3.dsi.uminho.pt/pcortez 26 | A. Cerdeira, F. Almeida, T. Matos and J. Reis, Viticulture Commission of the Vinho Verde Region(CVRVV), Porto, Portugal 27 | @2009 28 | -------------------------------------------------------------------------------- /examples/wine-quality/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/breskos/gopher-learn/engine" 7 | "github.com/breskos/gopher-learn/learn" 8 | neural "github.com/breskos/gopher-learn/net" 9 | "github.com/breskos/gopher-learn/persist" 10 | ) 11 | 12 | const ( 13 | dataFile = "winequality-red.csv" 14 | networkFile = "network.json" 15 | tries = 1 16 | epochs = 200 17 | trainingSplit = 0.8 18 | learningRate = 0.02 19 | decay = 0.001 20 | hiddenNeurons = 50 21 | regressionThreshold = 0.04 // helps evaluation to define between wrong or right 22 | ) 23 | 24 | func main() { 25 | data := learn.NewSet(neural.Regression) 26 | ok, err := data.LoadFromCSV(dataFile) 27 | if !ok || nil != err { 28 | fmt.Printf("something went wrong -> %v", err) 29 | } 30 | e := engine.NewEngine(neural.Regression, []int{hiddenNeurons}, data) 31 | e.SetVerbose(true) 32 | e.SetConfig(&engine.Config{ 33 | Tries: tries, 34 | Epochs: epochs, 35 | TrainingSplit: trainingSplit, 36 | LearningRate: learningRate, 37 | Decay: decay, 38 | RegressionThreshold: 0.04, 39 | }) 40 | // here we ware choosing Distance because we want the regressor that produces the best examples 41 | e.Start(neural.Distance) 42 | network, evaluation := e.GetWinner() 43 | 44 | // regression evaluation 45 | evaluation.PrintRegressionSummary() 46 | 47 | err = persist.ToFile(networkFile, network) 48 | if err != nil { 49 | fmt.Printf("error while saving network: %v\n", err) 50 | } 51 | // persisted network 52 | network2, err := persist.FromFile(networkFile) 53 | if err != nil { 54 | fmt.Printf("error while loading network: %v\n", err) 55 | } 56 | 57 | // some examples 58 | w := network2.Calculate(data.Samples[0].Vector) 59 | fmt.Printf("%v -> %v\n", data.Samples[0].Value, w) 60 | w = network2.Calculate(data.Samples[52].Vector) 61 | fmt.Printf("%v -> %v\n", data.Samples[52].Value, w) 62 | w = network2.Calculate(data.Samples[180].Vector) 63 | fmt.Printf("%v -> %v\n", data.Samples[189].Value, w) 64 | } 65 | -------------------------------------------------------------------------------- /learn/learn.go: -------------------------------------------------------------------------------- 1 | package learn 2 | 3 | import neural "github.com/breskos/gopher-learn/net" 4 | 5 | // Deltas holds the deltas from the learner 6 | type Deltas [][]float64 7 | 8 | // Learner learns all samples and applies backprop on the network 9 | func Learner(n *neural.Network, samples []Sample, speed float64) { 10 | for sample := range samples { 11 | Learn(n, samples[sample].Vector, samples[sample].Output, speed) 12 | } 13 | } 14 | 15 | // Learn applies backprop on the network 16 | func Learn(n *neural.Network, in, ideal []float64, speed float64) { 17 | Backpropagation(n, in, ideal, speed) 18 | } 19 | 20 | // Backpropagation uses backprop on the network 21 | func Backpropagation(n *neural.Network, in, ideal []float64, speed float64) { 22 | n.Calculate(in) 23 | 24 | deltas := make([][]float64, len(n.Layers)) 25 | 26 | last := len(n.Layers) - 1 27 | l := n.Layers[last] 28 | deltas[last] = make([]float64, len(l.Neurons)) 29 | for i, n := range l.Neurons { 30 | deltas[last][i] = n.Out * (1 - n.Out) * (ideal[i] - n.Out) 31 | } 32 | 33 | for i := last - 1; i >= 0; i-- { 34 | l := n.Layers[i] 35 | deltas[i] = make([]float64, len(l.Neurons)) 36 | for j, n := range l.Neurons { 37 | sum := 0.0 38 | for k, s := range n.OutSynapses { 39 | sum += s.Weight * deltas[i+1][k] 40 | } 41 | deltas[i][j] = n.Out * (1 - n.Out) * sum 42 | } 43 | } 44 | 45 | for i, l := range n.Layers { 46 | for j, n := range l.Neurons { 47 | for _, s := range n.InSynapses { 48 | s.Weight += speed * deltas[i][j] * s.In 49 | } 50 | } 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /learn/samples.go: -------------------------------------------------------------------------------- 1 | package learn 2 | 3 | import ( 4 | "bufio" 5 | "crypto/md5" 6 | "encoding/hex" 7 | "fmt" 8 | "math/rand" 9 | "os" 10 | "strconv" 11 | "strings" 12 | ) 13 | 14 | const ( 15 | hashSeperator = "#" 16 | ) 17 | 18 | // Sample holds the sample data, value is just used for regression annotation 19 | type Sample struct { 20 | Vector []float64 21 | Output []float64 22 | Value float64 23 | VectorHash string 24 | OutputHash string 25 | Label string 26 | ClassNumber int 27 | } 28 | 29 | // NewClassificationSample creates a new sample data point for classification 30 | func NewClassificationSample(vector, output []float64, classLabel string) *Sample { 31 | sample := &Sample{ 32 | Vector: vector, 33 | Output: output, 34 | Label: classLabel, 35 | } 36 | sample.UpdateHashes() 37 | return sample 38 | } 39 | 40 | // NewRegressionSample creates a new sample data point for classification 41 | func NewRegressionSample(vector []float64, output float64, classLabel string) *Sample { 42 | sample := &Sample{ 43 | Vector: vector, 44 | Value: output, 45 | Label: classLabel, 46 | } 47 | sample.UpdateHashes() 48 | return sample 49 | } 50 | 51 | // Splits the Set based on the given ratio 52 | func splitSamples(set *Set, ratio float64) (Set, Set) { 53 | normalizedRatio := int(ratio * 100.0) 54 | firstSet := Set{ 55 | Samples: make([]*Sample, 0), 56 | ClassToLabel: set.ClassToLabel, 57 | } 58 | secondSet := Set{ 59 | Samples: make([]*Sample, 0), 60 | ClassToLabel: set.ClassToLabel, 61 | } 62 | for i := range set.Samples { 63 | if rand.Intn(100) <= normalizedRatio { 64 | firstSet.Samples = append(firstSet.Samples, set.Samples[i]) 65 | } else { 66 | secondSet.Samples = append(secondSet.Samples, set.Samples[i]) 67 | } 68 | } 69 | return firstSet, secondSet 70 | } 71 | 72 | // UpdateHashes updates hashes of vector and output vector 73 | func (s *Sample) UpdateHashes() { 74 | text := "" 75 | for k, v := range s.Vector { 76 | text += fmt.Sprintf("%v:%v;", k, v) 77 | } 78 | s.VectorHash = calculateHash(text) 79 | text = "" 80 | for k, v := range s.Label { 81 | text += fmt.Sprintf("%v:%v;", k, v) 82 | 83 | } 84 | text += fmt.Sprintf("%v", s.Value) 85 | s.OutputHash = calculateHash(text) 86 | } 87 | 88 | // GetHash calculates the has of feature vector and output and returns it 89 | func (s *Sample) GetHash() string { 90 | if s.OutputHash == "" || s.VectorHash == "" { 91 | s.UpdateHashes() 92 | } 93 | return s.VectorHash + hashSeperator + s.OutputHash 94 | } 95 | 96 | // Calculates a hash value 97 | func calculateHash(text string) string { 98 | hash := md5.Sum([]byte(text)) 99 | return hex.EncodeToString(hash[:]) 100 | } 101 | 102 | // Loads a SVM Problem file 103 | func problemToMap(problem string) (map[int]float64, string, error) { 104 | sliced := strings.Split(problem, " ") 105 | m := make(map[int]float64) 106 | label := sliced[0] 107 | features := sliced[1:len(sliced)] 108 | for feature := range features { 109 | if features[feature] == "" { 110 | continue 111 | } 112 | splitted := strings.Split(features[feature], ":") 113 | idx, errIdx := strconv.Atoi(splitted[0]) 114 | value, errVal := strconv.ParseFloat(splitted[1], 64) 115 | if errIdx == nil && errVal == nil { 116 | m[idx] = value 117 | } 118 | } 119 | return m, label, nil 120 | } 121 | 122 | // this function returns the highest index found 123 | func scanSamples(path string) int { 124 | highest := 0 125 | file, err := os.Open(path) 126 | if err != nil { 127 | fmt.Println("error while opening file") 128 | os.Exit(-1) 129 | } 130 | defer file.Close() 131 | scanner := bufio.NewScanner(file) 132 | for scanner.Scan() { 133 | m, _, err := problemToMap(scanner.Text()) 134 | if err != nil { 135 | fmt.Printf("error while scanning files: %v", err) 136 | os.Exit(-1) 137 | } 138 | for k := range m { 139 | if k > highest { 140 | highest = k 141 | } 142 | } 143 | } 144 | return highest 145 | } 146 | -------------------------------------------------------------------------------- /learn/set.go: -------------------------------------------------------------------------------- 1 | package learn 2 | 3 | import ( 4 | "bufio" 5 | "encoding/csv" 6 | "errors" 7 | "fmt" 8 | "io" 9 | "os" 10 | "strconv" 11 | 12 | neural "github.com/breskos/gopher-learn/net" 13 | ) 14 | 15 | const ( 16 | maxActivation = 1.0 17 | minActivation = 0.0 18 | labelRegressor = "output" 19 | 20 | errUsageTypeNotMatching = "usage type not matching" 21 | errClassLabelNotFound = "class label not found in set" 22 | ) 23 | 24 | // Set holds the samples and the output labels 25 | type Set struct { 26 | Samples []*Sample 27 | VectorHashes []string 28 | OutputHashes []string 29 | ClassToLabel map[int]string 30 | Usage neural.NetworkType 31 | } 32 | 33 | // NewSet creates a new set of empty data samples 34 | func NewSet(usage neural.NetworkType) *Set { 35 | return &Set{ 36 | Samples: make([]*Sample, 0), 37 | ClassToLabel: make(map[int]string), 38 | Usage: usage, 39 | } 40 | } 41 | 42 | // AddClass returns the classes in the set 43 | func (s *Set) AddClass(label string) (bool, error) { 44 | if s.Usage != neural.Classification { 45 | return false, fmt.Errorf(errUsageTypeNotMatching) 46 | } 47 | l := len(s.ClassToLabel) 48 | s.ClassToLabel[l] = label 49 | return true, nil 50 | } 51 | 52 | // GetClasses returns the classes in the set 53 | func (s *Set) GetClasses() []string { 54 | classes := make([]string, len(s.ClassToLabel)) 55 | for k, v := range s.ClassToLabel { 56 | classes[k] = v 57 | } 58 | return classes 59 | } 60 | 61 | // Adds a vector with the corresponding output to the data set 62 | func (s *Set) add(vector, output []float64, label string, classNumber int, value float64) { 63 | sample := &Sample{} 64 | sample.Vector = vector 65 | sample.Output = output 66 | sample.Label = label 67 | sample.ClassNumber = classNumber 68 | sample.Value = value 69 | sample.UpdateHashes() 70 | // register hashes in data set 71 | s.VectorHashes = append(s.VectorHashes, sample.VectorHash) 72 | s.OutputHashes = append(s.OutputHashes, sample.OutputHash) 73 | s.Samples = append(s.Samples, sample) 74 | } 75 | 76 | // AddSample adds samples to the set 77 | func (s *Set) AddSample(sample *Sample) error { 78 | index, err := s.getClassIndex(sample.Label) 79 | if err != nil { 80 | return err 81 | } 82 | sample.ClassNumber = index 83 | sample.UpdateHashes() 84 | s.VectorHashes = append(s.VectorHashes, sample.VectorHash) 85 | s.OutputHashes = append(s.OutputHashes, sample.OutputHash) 86 | s.Samples = append(s.Samples, sample) 87 | return nil 88 | } 89 | 90 | // Returns the label from a given class number 91 | func (s *Set) getLabelFromClass(number int) (string, bool) { 92 | if val, ok := s.ClassToLabel[number]; ok { 93 | return val, true 94 | } 95 | return "", false 96 | } 97 | 98 | // Returns the class from the corresponding label 99 | func (s *Set) getClassFromLabel(label string) (int, bool) { 100 | for k, v := range s.ClassToLabel { 101 | if v == label { 102 | return k, true 103 | } 104 | } 105 | return -1, false 106 | } 107 | 108 | // Shows the distribution of the data set by the label 109 | func (s *Set) distributionByLabel(label string) map[string]int { 110 | if s.Usage == neural.Classification { 111 | dist := make(map[string]int) 112 | for sample := range s.Samples { 113 | c := s.Samples[sample].Label 114 | if _, ok := dist[c]; ok { 115 | dist[c]++ 116 | } else { 117 | dist[c] = 1 118 | } 119 | } 120 | return dist 121 | } 122 | return nil 123 | } 124 | 125 | // Shows the distribution by class number of a the data set 126 | func (s *Set) distributionByClassNumber(number int) map[int]int { 127 | if s.Usage == neural.Classification { 128 | dist := make(map[int]int) 129 | for sample := range s.Samples { 130 | c := s.Samples[sample].ClassNumber 131 | if _, ok := dist[c]; ok { 132 | dist[c]++ 133 | } else { 134 | dist[c] = 1 135 | } 136 | } 137 | return dist 138 | } 139 | return nil 140 | } 141 | 142 | // LoadFromCSV where the last dimension is the label 143 | func (s *Set) LoadFromCSV(path string) (bool, error) { 144 | classNumbers := make(map[string]int) 145 | classNumber := 0 146 | f, err := os.Open(path) 147 | if err != nil { 148 | return false, fmt.Errorf("error while open file: %v", path) 149 | } 150 | defer f.Close() 151 | r := csv.NewReader(bufio.NewReader(f)) 152 | for { 153 | record, err := r.Read() 154 | if err == io.EOF { 155 | break 156 | } 157 | l := len(record) 158 | sample := &Sample{} 159 | sample.Vector = make([]float64, l-1) 160 | if s.Usage == neural.Regression { 161 | regression, err := strconv.ParseFloat(record[l-1], 64) 162 | if err == nil { 163 | sample.Value = regression 164 | } 165 | } else if s.Usage == neural.Classification { 166 | sample.Label = record[l-1] 167 | if _, ok := classNumbers[sample.Label]; !ok { 168 | classNumbers[sample.Label] = classNumber 169 | classNumber++ 170 | } 171 | } 172 | for value := range record { 173 | if value < l-1 { 174 | f, err := strconv.ParseFloat(record[value], 64) 175 | if err != nil { 176 | return false, fmt.Errorf("failed to parse float %v with error: %v", record[value], err) 177 | } 178 | sample.Vector[value] = f 179 | } 180 | } 181 | sample.UpdateHashes() 182 | // register hashes in data set 183 | s.VectorHashes = append(s.VectorHashes, sample.VectorHash) 184 | s.OutputHashes = append(s.OutputHashes, sample.OutputHash) 185 | s.Samples = append(s.Samples, sample) 186 | } 187 | s.createClassToLabel(classNumbers) 188 | s.addOutputVectors() 189 | return true, nil 190 | } 191 | 192 | // Adds the output vectors for the 2 cases classification or regression 193 | func (s *Set) addOutputVectors() { 194 | if s.Usage == neural.Classification { 195 | dim := len(s.ClassToLabel) 196 | for sample := range s.Samples { 197 | v := make([]float64, dim) 198 | v[s.Samples[sample].ClassNumber] = maxActivation 199 | s.Samples[sample].Output = v 200 | } 201 | } else if s.Usage == neural.Regression { 202 | for sample := range s.Samples { 203 | s.Samples[sample].Output = make([]float64, 1) 204 | s.Samples[sample].Output[0] = s.Samples[sample].Value 205 | } 206 | } 207 | } 208 | 209 | // Creats a class to the label and adding it to the set 210 | func (s *Set) createClassToLabel(mapping map[string]int) { 211 | s.ClassToLabel = make(map[int]string) 212 | if neural.Classification == s.Usage { 213 | for k, v := range mapping { 214 | s.ClassToLabel[v] = k 215 | } 216 | for i := range s.Samples { 217 | s.Samples[i].ClassNumber = mapping[s.Samples[i].Label] 218 | } 219 | } else { 220 | s.ClassToLabel[0] = labelRegressor 221 | } 222 | 223 | } 224 | 225 | // SampleExists looks up in the set if the presented example already exists 226 | func (s *Set) SampleExists(test *Sample) bool { 227 | if test.VectorHash == "" { 228 | test.UpdateHashes() 229 | } 230 | for _, vector := range s.VectorHashes { 231 | if vector == test.VectorHash { 232 | return true 233 | } 234 | } 235 | return false 236 | } 237 | 238 | // LoadFromSVMFile load data from an svm problem file 239 | func (s *Set) LoadFromSVMFile(path string) (bool, error) { 240 | classNumbers := make(map[string]int) 241 | classNumber := 0 242 | highestIndex := scanSamples(path) 243 | file, err := os.Open(path) 244 | if err != nil { 245 | return false, fmt.Errorf("error while opening file") 246 | } 247 | defer file.Close() 248 | scanner := bufio.NewScanner(file) 249 | for scanner.Scan() { 250 | line := scanner.Text() 251 | m, label, err := problemToMap(line) 252 | if err != nil { 253 | return false, fmt.Errorf("error while scanning files: %v", err) 254 | } 255 | sample := &Sample{} 256 | sample.Vector = make([]float64, highestIndex) 257 | sample.Label = label 258 | regression, err := strconv.ParseFloat(label, 64) 259 | if err != nil { 260 | sample.Value = regression 261 | } 262 | if _, ok := classNumbers[sample.Label]; !ok { 263 | classNumbers[sample.Label] = classNumber 264 | classNumber++ 265 | } 266 | for i := 0; i < highestIndex; i++ { 267 | if val, ok := m[i]; ok { 268 | sample.Vector[i] = val 269 | } else { 270 | sample.Vector[i] = 0.0 271 | } 272 | } 273 | sample.UpdateHashes() 274 | // register hashes in data set 275 | s.VectorHashes = append(s.VectorHashes, sample.VectorHash) 276 | s.OutputHashes = append(s.OutputHashes, sample.OutputHash) 277 | s.Samples = append(s.Samples, sample) 278 | } 279 | return true, nil 280 | } 281 | 282 | // GenerateOutputVector generates the output vector for a classification task and a specific label 283 | func (s *Set) GenerateOutputVector(label string) []float64 { 284 | var output []float64 285 | for _, v := range s.ClassToLabel { 286 | if v == label { 287 | output = append(output, maxActivation) 288 | } else { 289 | output = append(output, minActivation) 290 | } 291 | } 292 | return output 293 | } 294 | 295 | // Returns the class index of a string label 296 | func (s *Set) getClassIndex(label string) (int, error) { 297 | for k, v := range s.ClassToLabel { 298 | if label == v { 299 | return k, nil 300 | } 301 | } 302 | return 0, errors.New(errUsageTypeNotMatching) 303 | } 304 | -------------------------------------------------------------------------------- /net/activation_func.go: -------------------------------------------------------------------------------- 1 | package net 2 | 3 | import "math" 4 | 5 | // ActivationFunction function definition of activation functions 6 | type ActivationFunction func(float64) float64 7 | 8 | // NewLogisticFunc applies and returns the Logistic function 9 | func NewLogisticFunc(a float64) ActivationFunction { 10 | return func(x float64) float64 { 11 | return LogisticFunc(x, a) 12 | } 13 | } 14 | 15 | // LogisticFunc returns the value of the logistic function for x and a 16 | func LogisticFunc(x, a float64) float64 { 17 | return 1 / (1 + math.Exp(-a*x)) 18 | } 19 | -------------------------------------------------------------------------------- /net/activation_function_test.go: -------------------------------------------------------------------------------- 1 | package net 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | // TestLogisticFunc tests the activation function 8 | func TestLogisticFunc(t *testing.T) { 9 | f := NewLogisticFunc(1) 10 | 11 | if f(0) != 0.5 { 12 | t.Errorf("f(0) not equal 0.5") 13 | } 14 | if 1-f(6) <= 0 { 15 | t.Errorf("1-f(6) not > 0") 16 | } 17 | if 1-f(6) >= 0.1 { 18 | t.Errorf("1-f(6) not < 0.1") 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /net/enter.go: -------------------------------------------------------------------------------- 1 | package net 2 | 3 | // Enter represents the input vector that comes into the network 4 | type Enter struct { 5 | OutSynapses []*Synapse 6 | Input float64 `json:"-"` 7 | } 8 | 9 | // NewEnter creates a new Enter 10 | func NewEnter() *Enter { 11 | return &Enter{} 12 | } 13 | 14 | // SynapseTo creates a new Synapse to a Neuron from the next layer 15 | func (e *Enter) SynapseTo(nTo *Neuron, weight float64) { 16 | syn := NewSynapse(weight) 17 | 18 | e.OutSynapses = append(e.OutSynapses, syn) 19 | nTo.InSynapses = append(nTo.InSynapses, syn) 20 | } 21 | 22 | // SetInput sets the input the specific enter 23 | func (e *Enter) SetInput(val float64) { 24 | e.Input = val 25 | } 26 | 27 | // ConnectTo connects the Enter to the next layer (to the neurons) 28 | func (e *Enter) ConnectTo(layer *Layer) { 29 | for _, n := range layer.Neurons { 30 | e.SynapseTo(n, 0) 31 | } 32 | } 33 | 34 | // Signal passes the signal into the network 35 | func (e *Enter) Signal() { 36 | for _, s := range e.OutSynapses { 37 | s.Signal(e.Input) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /net/layer.go: -------------------------------------------------------------------------------- 1 | package net 2 | 3 | // A layer is a structure that holds the neurons with their corresponding 4 | // synapses. Here also the activation of the neurons is calculated. 5 | 6 | // NewLayer creats a new layer with the number of neurons given. 7 | func NewLayer(neurons int) *Layer { 8 | l := &Layer{} 9 | l.init(neurons) 10 | return l 11 | } 12 | 13 | // Layer holds the neurons with their synapse connections 14 | type Layer struct { 15 | Neurons []*Neuron 16 | } 17 | 18 | // ConnectTo is used to connect the neurons of one layer with the neurons of 19 | // another layer. 20 | func (l *Layer) ConnectTo(layer *Layer) { 21 | for _, n := range l.Neurons { 22 | for _, toN := range layer.Neurons { 23 | n.SynapseTo(toN, 0) 24 | } 25 | } 26 | } 27 | 28 | // Initializes the new Layer with the given number of neurons 29 | func (l *Layer) init(neurons int) { 30 | for ; neurons > 0; neurons-- { 31 | l.addNeuron() 32 | } 33 | } 34 | 35 | // Adds a new neuron to the layer 36 | func (l *Layer) addNeuron() { 37 | n := NewNeuron() 38 | l.Neurons = append(l.Neurons, n) 39 | } 40 | 41 | // Calculate the a activation of the current layer 42 | func (l *Layer) Calculate() { 43 | for _, n := range l.Neurons { 44 | n.Calculate() 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /net/layer_test.go: -------------------------------------------------------------------------------- 1 | package net 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | // TestLayer creates a layer with 5 neurons and tests if it was successful 8 | func TestLayer(t *testing.T) { 9 | l := NewLayer(5) 10 | if len(l.Neurons) != 5 { 11 | t.Errorf("len of Neurons not 5") 12 | } 13 | } 14 | 15 | // TestConnectToLayer creates two layers and tries to connect both of them 16 | func TestConnectToLayer(t *testing.T) { 17 | count := 5 18 | l := NewLayer(count) 19 | l2 := NewLayer(count) 20 | 21 | l.ConnectTo(l2) 22 | 23 | for _, n := range l.Neurons { 24 | if len(n.OutSynapses) != count { 25 | t.Errorf("out synapses are not equal %d", count) 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /net/network.go: -------------------------------------------------------------------------------- 1 | package net 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | ) 7 | 8 | // Criterion is needed to decide if the Engine found a better working network. 9 | // It functions as decider during the training. 10 | type Criterion int 11 | 12 | const ( 13 | // Accuracy decides evaluation by accuracy 14 | Accuracy Criterion = iota 15 | // BalancedAccuracy decides evaluation by balanced accuracy 16 | BalancedAccuracy 17 | // FMeasure decides evaluation by f-measure 18 | FMeasure 19 | // Simple decides on simple wrong/correct ratio 20 | Simple 21 | // Distance decides evaluation by distance to ideal output 22 | Distance 23 | ) 24 | 25 | // Network contains all the necessary information to use the neural network 26 | type Network struct { 27 | Enters []*Enter 28 | Layers []*Layer 29 | Out []float64 `json:"-"` 30 | OutLabels map[int]string 31 | } 32 | 33 | // NewNetwork creates a new neural network 34 | func NewNetwork(in int, layers []int, labels map[int]string) *Network { 35 | n := &Network{ 36 | Enters: make([]*Enter, 0, in), 37 | Layers: make([]*Layer, 0, len(layers)), 38 | OutLabels: labels, 39 | } 40 | n.init(in, layers, NewLogisticFunc(1)) 41 | return n 42 | } 43 | 44 | // Initializes the Network with the given layers and activation function. 45 | func (n *Network) init(in int, layers []int, aFunc ActivationFunction) { 46 | n.initLayers(layers) 47 | n.initEnters(in) 48 | n.ConnectLayers() 49 | n.ConnectEnters() 50 | n.SetActivationFunction(aFunc) 51 | } 52 | 53 | // Initializes the Layers with the given count of neurons as well as 54 | // creating all the synapses necessary. 55 | func (n *Network) initLayers(layers []int) { 56 | for _, count := range layers { 57 | layer := NewLayer(count) 58 | n.Layers = append(n.Layers, layer) 59 | } 60 | } 61 | 62 | // Intializes the Enters (size of feature vector) that enters the network. 63 | func (n *Network) initEnters(in int) { 64 | for ; in > 0; in-- { 65 | e := NewEnter() 66 | n.Enters = append(n.Enters, e) 67 | } 68 | } 69 | 70 | // ConnectLayers connects all layers with corresponding neurons 71 | func (n *Network) ConnectLayers() { 72 | for i := len(n.Layers) - 1; i > 0; i-- { 73 | n.Layers[i-1].ConnectTo(n.Layers[i]) 74 | } 75 | } 76 | 77 | // ConnectEnters connects the input neurons with the first hidden layer 78 | func (n *Network) ConnectEnters() { 79 | for _, e := range n.Enters { 80 | e.ConnectTo(n.Layers[0]) 81 | } 82 | } 83 | 84 | // SetActivationFunction sets the activation function for the network 85 | func (n *Network) SetActivationFunction(aFunc ActivationFunction) { 86 | for _, l := range n.Layers { 87 | for _, n := range l.Neurons { 88 | n.SetActivationFunction(aFunc) 89 | } 90 | } 91 | } 92 | 93 | // Set the current feature vector for the network 94 | func (n *Network) setEnters(v *[]float64) { 95 | values := *v 96 | if len(values) != len(n.Enters) { 97 | panic(fmt.Sprint("Enters count ( ", len(n.Enters), " ) != count of elements in SetEnters function argument ( ", len(values), " ) .")) 98 | } 99 | 100 | for i, e := range n.Enters { 101 | e.Input = values[i] 102 | } 103 | 104 | } 105 | 106 | // This function sends the current feature vector to the network 107 | func (n *Network) sendEnters() { 108 | for _, e := range n.Enters { 109 | e.Signal() 110 | } 111 | } 112 | 113 | // Used during forward calculation through the network 114 | func (n *Network) calculateLayers() { 115 | for _, l := range n.Layers { 116 | l.Calculate() 117 | } 118 | } 119 | 120 | // Generates the output from the neurons 121 | func (n *Network) generateOut() { 122 | outL := n.Layers[len(n.Layers)-1] 123 | n.Out = make([]float64, len(outL.Neurons)) 124 | 125 | for i, neuron := range outL.Neurons { 126 | n.Out[i] = neuron.Out 127 | } 128 | } 129 | 130 | // Calculate calculates the result of a input vector 131 | func (n *Network) Calculate(enters []float64) []float64 { 132 | n.setEnters(&enters) 133 | n.sendEnters() 134 | n.calculateLayers() 135 | n.generateOut() 136 | 137 | return n.Out 138 | } 139 | 140 | // CalculateLabels output with all labels of output neurons 141 | func (n *Network) CalculateLabels(enters []float64) map[string]float64 { 142 | results := make(map[string]float64) 143 | out := n.Calculate(enters) 144 | for index, label := range n.OutLabels { 145 | results[label] = out[index] 146 | } 147 | return results 148 | } 149 | 150 | // CalculateWinnerLabel calculates the output and just returns the label of the winning euron 151 | func (n *Network) CalculateWinnerLabel(enters []float64) string { 152 | calculatedLabels := n.CalculateLabels(enters) 153 | winnerValue := 0.0 154 | winnerLabel := "" 155 | for label, value := range calculatedLabels { 156 | if value > winnerValue { 157 | winnerValue = value 158 | winnerLabel = label 159 | } 160 | } 161 | return winnerLabel 162 | } 163 | 164 | // RandomizeSynapses applies a random value to all synapses 165 | func (n *Network) RandomizeSynapses() { 166 | for _, l := range n.Layers { 167 | for _, n := range l.Neurons { 168 | for _, s := range n.InSynapses { 169 | s.Weight = 2 * (rand.Float64() - 0.5) 170 | } 171 | } 172 | } 173 | } 174 | 175 | // BuildNetwork builds a neural network from parameters given 176 | func BuildNetwork(usage NetworkType, input int, hidden []int, labels map[int]string) *Network { 177 | hidden = append(hidden, len(labels)) 178 | network := NewNetwork(input, hidden, labels) 179 | network.RandomizeSynapses() 180 | return network 181 | } 182 | -------------------------------------------------------------------------------- /net/neuron.go: -------------------------------------------------------------------------------- 1 | package net 2 | 3 | // Neuron holds the neuron structure with incoming synapses, 4 | // outgoing synapses, the activation function of the neuron as well as 5 | // the out value. 6 | type Neuron struct { 7 | OutSynapses []*Synapse 8 | InSynapses []*Synapse `json:"-"` 9 | ActivationFunction ActivationFunction `json:"-"` 10 | Out float64 `json:"-"` 11 | } 12 | 13 | // NewNeuron creates a new empty neuron 14 | func NewNeuron() *Neuron { 15 | return &Neuron{} 16 | } 17 | 18 | // SynapseTo creates a new synapse to a neuron 19 | func (n *Neuron) SynapseTo(nTo *Neuron, weight float64) { 20 | NewSynapseFromTo(n, nTo, weight) 21 | } 22 | 23 | // SetActivationFunction sets the activation function for the neuron 24 | func (n *Neuron) SetActivationFunction(aFunc ActivationFunction) { 25 | n.ActivationFunction = aFunc 26 | } 27 | 28 | // Calculate calculates the actual neuron activity 29 | func (n *Neuron) Calculate() { 30 | var sum float64 31 | for _, s := range n.InSynapses { 32 | sum += s.Out 33 | } 34 | n.Out = n.ActivationFunction(sum) 35 | for _, s := range n.OutSynapses { 36 | s.Signal(n.Out) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /net/neuron_test.go: -------------------------------------------------------------------------------- 1 | package net 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | // TestAttachNeurons tries to attach new neuron to an existing neuron 8 | // with creating a new synapse between them. 9 | func TestAttachNeurons(t *testing.T) { 10 | n := NewNeuron() 11 | n2 := NewNeuron() 12 | w := 0.5 13 | n.SynapseTo(n2, w) 14 | if n.OutSynapses[0].Weight != w { 15 | t.Errorf("out synapse has wrong weights") 16 | } 17 | } 18 | 19 | // TestInputSynases takes a neuron and connects synapses to it. 20 | // It then tests if the neuron correctly stored these connections. 21 | func TestInputsSynapses(t *testing.T) { 22 | n := NewNeuron() 23 | NewSynapseFromTo(NewNeuron(), n, 0.1) 24 | NewSynapseFromTo(NewNeuron(), n, 0.1) 25 | NewSynapseFromTo(NewNeuron(), n, 0.1) 26 | if len(n.InSynapses) != 3 { 27 | t.Errorf("in synapse is not 3") 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /net/synapse.go: -------------------------------------------------------------------------------- 1 | package net 2 | 3 | // Synapse holds the synapse structure with the weight 4 | // and the In and Out neuron. 5 | type Synapse struct { 6 | Weight float64 7 | In float64 `json:"-"` 8 | Out float64 `json:"-"` 9 | } 10 | 11 | // NewSynapse creates a new synapse with the weight 12 | func NewSynapse(weight float64) *Synapse { 13 | return &Synapse{Weight: weight} 14 | } 15 | 16 | // NewSynapseFromTo creates a new synapse from neuron to neuron 17 | func NewSynapseFromTo(from, to *Neuron, weight float64) *Synapse { 18 | syn := NewSynapse(weight) 19 | from.OutSynapses = append(from.OutSynapses, syn) 20 | to.InSynapses = append(to.InSynapses, syn) 21 | return syn 22 | } 23 | 24 | // Signal activates the Synapse with an input value 25 | func (s *Synapse) Signal(value float64) { 26 | s.In = value 27 | s.Out = s.In * s.Weight 28 | } 29 | -------------------------------------------------------------------------------- /net/type.go: -------------------------------------------------------------------------------- 1 | package net 2 | 3 | // NetworkType represents the type of the neural network in terms of 4 | // which task the network has. Classification and Regression are implemented. 5 | type NetworkType int 6 | 7 | const ( 8 | // Classification describes the mode of operation: classification 9 | Classification NetworkType = iota 10 | // Regression describes the mode of operation: regression 11 | Regression 12 | ) 13 | -------------------------------------------------------------------------------- /online/config.go: -------------------------------------------------------------------------------- 1 | package online 2 | 3 | const ( 4 | dFirstShots = 5 5 | dHotShotBoost = 0.5 6 | dTrainingSplit = 0.7 7 | dMinimumDataPoints = 10 8 | dMinEpochs = 10 9 | dMaxEpochs = 30 10 | dMinLearningSpeed = 0.2 11 | dMaxLearningSpeed = 0.5 12 | dInitialFMeasure = 0.70 13 | dMaxInitLoops = 5 14 | dRegressionThreshold = 0.05 15 | ) 16 | 17 | // Config has all the learning configurations necessary to learn the network online 18 | type Config struct { 19 | FirstShots int 20 | HotShotBoost float64 21 | TrainingSplit float64 22 | MinimumDataPoints int 23 | MinEpochs int 24 | MaxEpochs int 25 | MinLearningSpeed float64 26 | MaxLearningSpeed float64 27 | InitialFMeasure float64 28 | MaxInitLoops int 29 | RegressionThreshold float64 30 | } 31 | 32 | // DefaultConfig returns the default config for the online learner 33 | func DefaultConfig() *Config { 34 | return &Config{ 35 | FirstShots: dFirstShots, 36 | HotShotBoost: dHotShotBoost, 37 | TrainingSplit: dTrainingSplit, 38 | MinimumDataPoints: dMinimumDataPoints, 39 | MinEpochs: dMinEpochs, 40 | MaxEpochs: dMaxEpochs, 41 | MinLearningSpeed: dMinLearningSpeed, 42 | MaxLearningSpeed: dMaxLearningSpeed, 43 | InitialFMeasure: dInitialFMeasure, 44 | MaxInitLoops: dMaxInitLoops, 45 | RegressionThreshold: dRegressionThreshold, 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /online/online.go: -------------------------------------------------------------------------------- 1 | package online 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "math/rand" 7 | "time" 8 | 9 | "github.com/breskos/gopher-learn/evaluation" 10 | learn "github.com/breskos/gopher-learn/learn" 11 | "github.com/breskos/gopher-learn/net" 12 | ) 13 | 14 | const ( 15 | errDataPointExists = "data point exists (force not activated)" 16 | ) 17 | 18 | // Online contains every necessary for starting the engine 19 | type Online struct { 20 | NetworkInput int 21 | NetworkLayer []int 22 | NetworkOutput int 23 | Data *learn.Set 24 | Network *net.Network 25 | LastEvaluation *evaluation.Evaluation 26 | Verbose bool 27 | Usage net.NetworkType 28 | AddedPoints int 29 | Config *Config 30 | } 31 | 32 | // NewOnline creates a new Engine object 33 | func NewOnline(usage net.NetworkType, inputs int, hiddenLayer []int, data *learn.Set) *Online { 34 | var outputLength int 35 | if net.Regression == usage { 36 | outputLength = 1 37 | } else { 38 | outputLength = len(data.ClassToLabel) 39 | } 40 | return &Online{ 41 | NetworkInput: inputs, 42 | NetworkOutput: outputLength, 43 | NetworkLayer: hiddenLayer, 44 | Data: data, 45 | Network: net.BuildNetwork(usage, inputs, hiddenLayer, data.ClassToLabel), 46 | Verbose: false, 47 | Usage: usage, 48 | AddedPoints: 0, 49 | Config: DefaultConfig(), 50 | } 51 | } 52 | 53 | // Init initializes the online learner with a short learning upfront 54 | func (o *Online) Init() float64 { 55 | fMeasure := 0.0 56 | for i := 0; i < o.Config.MaxInitLoops; i++ { 57 | fMeasure = o.Iterate() 58 | if fMeasure < o.Config.InitialFMeasure { 59 | return fMeasure 60 | } 61 | } 62 | return fMeasure 63 | 64 | } 65 | 66 | // Inject tries to inject a new data point into the neural net 67 | func (o *Online) Inject(sample *learn.Sample, force bool) error { 68 | exists := o.Data.SampleExists(sample) 69 | if exists && !force { 70 | return errors.New(errDataPointExists) 71 | } 72 | err := o.Data.AddSample(sample) 73 | if err != nil { 74 | return fmt.Errorf("cannot add example: %v", err) 75 | } 76 | o.hotShot(sample) 77 | return nil 78 | } 79 | 80 | // Applies a Sample with hotShot speed to the network 81 | func (o *Online) hotShot(sample *learn.Sample) { 82 | for i := 0; i < o.Config.FirstShots; i++ { 83 | learn.Learn(o.Network, sample.Vector, sample.Output, o.Config.HotShotBoost) 84 | } 85 | } 86 | 87 | // Iterate iterates over the data set and applies continous learning 88 | func (o *Online) Iterate() float64 { 89 | if len(o.Data.Samples) < o.Config.MinimumDataPoints { 90 | return 0.0 91 | } 92 | rand.Seed(time.Now().UnixNano()) 93 | training, testing := split(o.Usage, o.Data, o.Config.TrainingSplit) 94 | speed := o.Config.MinLearningSpeed + rand.Float64()*(o.Config.MaxLearningSpeed-o.Config.MinLearningSpeed) 95 | epochs := rand.Intn(o.Config.MaxEpochs-o.Config.MinEpochs+1) + o.Config.MinEpochs 96 | train(o.Network, training, speed, epochs) 97 | evaluation := evaluate(o.Usage, o.Network, testing, training, o.Config.RegressionThreshold) 98 | if o.Verbose { 99 | evaluation.PrintConfusionMatrix() 100 | evaluation.PrintSummaries() 101 | } 102 | o.LastEvaluation = evaluation 103 | return evaluation.GetOverallFMeasure() 104 | } 105 | 106 | // SetVerbose sets the verbose version meaning debug and evaluation logs 107 | func (o *Online) SetVerbose(verbose bool) { 108 | o.Verbose = verbose 109 | } 110 | 111 | // checks if a sample is already in set 112 | func (o *Online) sampleExists(sample *learn.Sample) bool { 113 | if sample.VectorHash == "" { 114 | sample.UpdateHashes() 115 | } 116 | if o.Data.SampleExists(sample) { 117 | return true 118 | } 119 | return false 120 | } 121 | 122 | // Prints the current evaluation 123 | func print(e *evaluation.Evaluation) { 124 | fmt.Printf("\n [Best] acc: %.2f / bacc: %.2f / f1: %.2f / correct: %.2f / distance: %.2f\n", e.GetOverallAccuracy(), e.GetOverallBalancedAccuracy(), e.GetOverallFMeasure(), e.GetCorrectRatio(), e.GetDistance()) 125 | } 126 | 127 | // SetConfig sets a new config from outside for the online learner 128 | func (o *Online) SetConfig(cfg *Config) { 129 | o.Config = cfg 130 | } 131 | 132 | // GetConfig returns the current online learner configuration 133 | func (o *Online) GetConfig() *Config { 134 | return o.Config 135 | } 136 | -------------------------------------------------------------------------------- /online/train.go: -------------------------------------------------------------------------------- 1 | package online 2 | 3 | import ( 4 | "math/rand" 5 | 6 | "github.com/breskos/gopher-learn/evaluation" 7 | learn "github.com/breskos/gopher-learn/learn" 8 | "github.com/breskos/gopher-learn/net" 9 | ) 10 | 11 | // Trains the network with the given Sample set and learning rate 12 | func train(network *net.Network, data *learn.Set, learning float64, epochs int) { 13 | for e := 0; e < epochs; e++ { 14 | for sample := range data.Samples { 15 | learn.Learn(network, data.Samples[sample].Vector, data.Samples[sample].Output, learning) 16 | } 17 | } 18 | } 19 | 20 | // Splits the set into training and test set 21 | func split(usage net.NetworkType, set *learn.Set, ratio float64) (*learn.Set, *learn.Set) { 22 | multiplier := 100 23 | normalizedRatio := int(ratio * float64(multiplier)) 24 | var training, evaluation learn.Set 25 | training.ClassToLabel = set.ClassToLabel 26 | evaluation.ClassToLabel = set.ClassToLabel 27 | for i := range set.Samples { 28 | if rand.Intn(multiplier) <= normalizedRatio { 29 | training.Samples = append(training.Samples, set.Samples[i]) 30 | } else { 31 | evaluation.Samples = append(evaluation.Samples, set.Samples[i]) 32 | } 33 | } 34 | return &training, &evaluation 35 | } 36 | 37 | // Evaluates the network and finds the winner network based on network criterion 38 | func evaluate(usage net.NetworkType, network *net.Network, test *learn.Set, train *learn.Set, regressionThreshold float64) *evaluation.Evaluation { 39 | evaluation := evaluation.NewEvaluation(usage, train.GetClasses()) 40 | evaluation.SetRegressionThreshold(regressionThreshold) 41 | for sample := range test.Samples { 42 | evaluation.AddDistance(network, test.Samples[sample].Vector, test.Samples[sample].Output) 43 | if net.Classification == usage { 44 | winner := network.CalculateWinnerLabel(test.Samples[sample].Vector) 45 | evaluation.Add(test.Samples[sample].Label, winner) 46 | } else { 47 | prediction := network.Calculate(test.Samples[sample].Vector) 48 | evaluation.AddRegression(test.Samples[sample].Value, prediction[0]) 49 | } 50 | } 51 | return evaluation 52 | } 53 | -------------------------------------------------------------------------------- /persist/encoder.go: -------------------------------------------------------------------------------- 1 | package persist 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | 8 | "github.com/breskos/gopher-learn/encoders" 9 | ) 10 | 11 | type EncoderDump struct { 12 | // Name of the encoder 13 | Name string 14 | // Dimensions hold the EncoderModel for the dimensions 15 | Models map[string]Models 16 | // Config of the Encoder 17 | Config encoders.EncoderConfig 18 | // Scanned determines if scan was executed 19 | Scanned bool 20 | } 21 | 22 | type Models struct { 23 | Inputs int 24 | InputType encoders.InputType 25 | Type encoders.EncoderType 26 | Model []byte 27 | } 28 | 29 | // FromFile loads a NetworkDump from File and creates Network out of it 30 | func EncoderFromFile(path string) (*encoders.Encoder, error) { 31 | dump, err := encoderDumpFromFile(path) 32 | if nil != err { 33 | return nil, err 34 | } 35 | n := encoderFromDump(dump) 36 | return n, nil 37 | } 38 | 39 | // ToFile takes a network and creats a NetworkDump out of it and writes it to a file 40 | func EncoderToFile(path string, n *encoders.Encoder) error { 41 | dump := encoderToDump(n) 42 | return encoderDumpToFile(path, dump) 43 | } 44 | 45 | // encoderDrumpFromFile loads an EncoderDump from file 46 | func encoderDumpFromFile(path string) (*EncoderDump, error) { 47 | b, err := ioutil.ReadFile(path) 48 | if nil != err { 49 | return nil, err 50 | } 51 | dump := &EncoderDump{} 52 | err = json.Unmarshal(b, dump) 53 | if nil != err { 54 | return nil, err 55 | } 56 | 57 | return dump, nil 58 | } 59 | 60 | // encoderDumpFromFile writes an EncoderDump to file 61 | func encoderDumpToFile(path string, dump *EncoderDump) error { 62 | j, err := json.Marshal(dump) 63 | if err != nil { 64 | return err 65 | } 66 | err = ioutil.WriteFile(path, j, 0644) 67 | return err 68 | } 69 | 70 | // encoderToDump creates an EncoderDump out of a Encoder 71 | func encoderToDump(n *encoders.Encoder) *EncoderDump { 72 | dimensions := make(map[string]Models, 0) 73 | for k, v := range n.Models { 74 | dump, err := v.Model.ToDump() 75 | if err != nil { 76 | fmt.Printf("error serializing encoder: %s (%s, %s)", k, v.InputType.String(), v.Type.String()) 77 | } 78 | dimensions[k] = Models{ 79 | Inputs: v.Inputs, 80 | InputType: v.InputType, 81 | Type: v.Type, 82 | Model: dump, 83 | } 84 | } 85 | return &EncoderDump{ 86 | Name: n.Name, 87 | Config: *n.Config, 88 | Models: dimensions, 89 | Scanned: n.Scanned, 90 | } 91 | } 92 | 93 | // encoderFromDump creates a Encoder out of a Encoder dump 94 | func encoderFromDump(dump *EncoderDump) *encoders.Encoder { 95 | n := &encoders.Encoder{ 96 | Name: dump.Name, 97 | Scanned: dump.Scanned, 98 | Config: &dump.Config, 99 | } 100 | n.Models = make(map[string]*encoders.Dimension) 101 | for k, v := range dump.Models { 102 | n.Models[k] = &encoders.Dimension{ 103 | Inputs: v.Inputs, 104 | InputType: v.InputType, 105 | Type: v.Type, 106 | } 107 | 108 | switch v.Type { 109 | case encoders.StringDictionary: 110 | n.Models[k].Model = encoders.NewDictionaryModel() 111 | n.Models[k].Model.FromDump(v.Model) 112 | case encoders.StringSplitDictionary: 113 | n.Models[k].Model = encoders.NewSplitDictionaryModel() 114 | n.Models[k].Model.FromDump(v.Model) 115 | case encoders.StringNGrams: 116 | n.Models[k].Model = encoders.NewNGramModel() 117 | n.Models[k].Model.FromDump(v.Model) 118 | case encoders.FloatExact: 119 | n.Models[k].Model = encoders.NewFloatExactModel() 120 | n.Models[k].Model.FromDump(v.Model) 121 | case encoders.FloatReducer: 122 | n.Models[k].Model = encoders.NewFloatReducerModel() 123 | n.Models[k].Model.FromDump(v.Model) 124 | } 125 | 126 | } 127 | return n 128 | } 129 | -------------------------------------------------------------------------------- /persist/network.go: -------------------------------------------------------------------------------- 1 | package persist 2 | 3 | import ( 4 | "encoding/json" 5 | "io/ioutil" 6 | "strconv" 7 | 8 | neural "github.com/breskos/gopher-learn/net" 9 | ) 10 | 11 | // Weights is used to persist the weights of the network 12 | type Weights [][][]float64 13 | 14 | // NetworkDump is the json representation of the network stucture 15 | type NetworkDump struct { 16 | Enters int 17 | Weights Weights 18 | OutLabels map[string]string 19 | } 20 | 21 | // FromFile loads a NetworkDump from File and creates Network out of it 22 | func FromFile(path string) (*neural.Network, error) { 23 | dump, err := dumpFromFile(path) 24 | if nil != err { 25 | return nil, err 26 | } 27 | n := FromDump(dump) 28 | return n, nil 29 | } 30 | 31 | // ToFile takes a network and creats a NetworkDump out of it and writes it to a file 32 | func ToFile(path string, n *neural.Network) error { 33 | dump := ToDump(n) 34 | return dumpToFile(path, dump) 35 | } 36 | 37 | // dumpFromFile loads a NetworkDump from file 38 | func dumpFromFile(path string) (*NetworkDump, error) { 39 | b, err := ioutil.ReadFile(path) 40 | if nil != err { 41 | return nil, err 42 | } 43 | dump := &NetworkDump{} 44 | err = json.Unmarshal(b, dump) 45 | if nil != err { 46 | return nil, err 47 | } 48 | 49 | return dump, nil 50 | } 51 | 52 | // dumpToFile writes a NetworkDump to file 53 | func dumpToFile(path string, dump *NetworkDump) error { 54 | j, err := json.Marshal(dump) 55 | if err != nil { 56 | return err 57 | } 58 | err = ioutil.WriteFile(path, j, 0644) 59 | return err 60 | } 61 | 62 | // ToDump creates a NetworkDump out of a Network 63 | func ToDump(n *neural.Network) *NetworkDump { 64 | labels := intToStringMap(n.OutLabels) 65 | dump := &NetworkDump{Enters: len(n.Enters), Weights: make([][][]float64, len(n.Layers)), OutLabels: labels} 66 | 67 | for i, l := range n.Layers { 68 | dump.Weights[i] = make([][]float64, len(l.Neurons)) 69 | for j, n := range l.Neurons { 70 | dump.Weights[i][j] = make([]float64, len(n.InSynapses)) 71 | for k, s := range n.InSynapses { 72 | dump.Weights[i][j][k] = s.Weight 73 | } 74 | } 75 | } 76 | return dump 77 | } 78 | 79 | // FromDump creates a Network out of a NetworkDump 80 | func FromDump(dump *NetworkDump) *neural.Network { 81 | layers := make([]int, len(dump.Weights)) 82 | for i, layer := range dump.Weights { 83 | layers[i] = len(layer) 84 | } 85 | labels := stringToIntMap(dump.OutLabels) 86 | n := neural.NewNetwork(dump.Enters, layers, labels) 87 | 88 | for i, l := range n.Layers { 89 | for j, n := range l.Neurons { 90 | for k, s := range n.InSynapses { 91 | s.Weight = dump.Weights[i][j][k] 92 | } 93 | } 94 | } 95 | 96 | return n 97 | } 98 | 99 | // Converts an int map to a string map 100 | func intToStringMap(m map[int]string) map[string]string { 101 | ms := make(map[string]string) 102 | for k, v := range m { 103 | ms[strconv.Itoa(k)] = v 104 | } 105 | return ms 106 | } 107 | 108 | // Converts a string map to an int map 109 | func stringToIntMap(m map[string]string) map[int]string { 110 | mi := make(map[int]string) 111 | for k, v := range m { 112 | index, err := strconv.Atoi(k) 113 | if err != nil { 114 | panic(err) 115 | } 116 | mi[index] = v 117 | } 118 | return mi 119 | } 120 | -------------------------------------------------------------------------------- /persist/online.go: -------------------------------------------------------------------------------- 1 | package persist 2 | 3 | import ( 4 | "encoding/json" 5 | "io/ioutil" 6 | 7 | "github.com/breskos/gopher-learn/evaluation" 8 | "github.com/breskos/gopher-learn/learn" 9 | neural "github.com/breskos/gopher-learn/net" 10 | "github.com/breskos/gopher-learn/online" 11 | ) 12 | 13 | // OnlineDump is the json representation of the network stucture 14 | type OnlineDump struct { 15 | NetworkInput int 16 | NetworkLayer []int 17 | NetworkOutput int 18 | Data *learn.Set 19 | Network *NetworkDump 20 | LastEvaluation *evaluation.Evaluation 21 | Verbose bool 22 | Usage neural.NetworkType 23 | AddedPoints int 24 | Config *online.Config 25 | } 26 | 27 | // FromOnlineFile loads a OnlineDump from File and creates Online out of it 28 | func OnlineFromFile(path string) (*online.Online, error) { 29 | dump, err := onlineDumpFromFile(path) 30 | if nil != err { 31 | return nil, err 32 | } 33 | n := fromOnlineDump(dump) 34 | return n, nil 35 | } 36 | 37 | // OnlineToFile takes a network and creats a NetworkDump out of it and writes it to a file 38 | func OnlineToFile(path string, n *online.Online) error { 39 | dump := toOnlineDump(n) 40 | return dumpToOnlineFile(path, dump) 41 | } 42 | 43 | // FromOnlineDump creates a Online out of an OnlineDump 44 | func fromOnlineDump(d *OnlineDump) *online.Online { 45 | return &online.Online{ 46 | NetworkInput: d.NetworkOutput, 47 | NetworkLayer: d.NetworkLayer, 48 | NetworkOutput: d.NetworkOutput, 49 | Data: d.Data, 50 | Network: FromDump(d.Network), 51 | LastEvaluation: d.LastEvaluation, 52 | Verbose: d.Verbose, 53 | Usage: d.Usage, 54 | AddedPoints: d.AddedPoints, 55 | Config: d.Config, 56 | } 57 | } 58 | 59 | // dumpToOnlineFile writes a NetworkDump to file 60 | func dumpToOnlineFile(path string, dump *OnlineDump) error { 61 | j, err := json.Marshal(dump) 62 | if err != nil { 63 | return err 64 | } 65 | err = ioutil.WriteFile(path, j, 0644) 66 | return err 67 | } 68 | 69 | // onlineDumpFromFile loads an OnlineDump from file 70 | func onlineDumpFromFile(path string) (*OnlineDump, error) { 71 | b, err := ioutil.ReadFile(path) 72 | if nil != err { 73 | return nil, err 74 | } 75 | dump := &OnlineDump{} 76 | err = json.Unmarshal(b, dump) 77 | if nil != err { 78 | return nil, err 79 | } 80 | 81 | return dump, nil 82 | } 83 | 84 | // toOnlineDump creates a OnlineDump out of an Online 85 | func toOnlineDump(d *online.Online) *OnlineDump { 86 | return &OnlineDump{ 87 | NetworkInput: d.NetworkOutput, 88 | NetworkLayer: d.NetworkLayer, 89 | NetworkOutput: d.NetworkOutput, 90 | Data: d.Data, 91 | Network: ToDump(d.Network), 92 | LastEvaluation: d.LastEvaluation, 93 | Verbose: d.Verbose, 94 | Usage: d.Usage, 95 | AddedPoints: d.AddedPoints, 96 | Config: d.Config, 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /persist/set.go: -------------------------------------------------------------------------------- 1 | package persist 2 | 3 | import ( 4 | "encoding/json" 5 | "io/ioutil" 6 | 7 | learn "github.com/breskos/gopher-learn/learn" 8 | ) 9 | 10 | // SetFromFile reads a data set from a file 11 | func SetFromFile(path string) (*learn.Set, error) { 12 | b, err := ioutil.ReadFile(path) 13 | if nil != err { 14 | return nil, err 15 | } 16 | set := &learn.Set{} 17 | err = json.Unmarshal(b, set) 18 | if nil != err { 19 | return nil, err 20 | } 21 | 22 | return set, nil 23 | } 24 | 25 | // SetToFile writes a set to a file 26 | func SetToFile(path string, set *learn.Set) error { 27 | j, err := json.Marshal(set) 28 | if err != nil { 29 | return err 30 | } 31 | err = ioutil.WriteFile(path, j, 0644) 32 | return err 33 | } 34 | --------------------------------------------------------------------------------