├── .github └── workflows │ ├── ci.yml │ └── gh-pages.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE-2.0 ├── LICENSE-CC-BY-SA ├── LICENSE-MIT ├── README.md ├── book.toml ├── examples ├── clustering_comparison.rs ├── dbscan.rs ├── kmeans.rs └── linear_regression.rs └── src ├── 2_intro.md ├── 3_kmeans.md ├── 4_dbscan.md ├── 5_linear_regression.md ├── SUMMARY.md ├── assets ├── clustering_comparison.png ├── dbscan.png ├── kmeans.png ├── kmeans_test.png └── linear_regression.png ├── kmeans_dbscan_comparison.png └── lib.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | with: 20 | profile: minimal 21 | toolchain: stable 22 | components: clippy 23 | - name: Build 24 | run: cargo build --all 25 | - name: Format 26 | run: cargo fmt --all -- --check 27 | -------------------------------------------------------------------------------- /.github/workflows/gh-pages.yml: -------------------------------------------------------------------------------- 1 | name: github pages 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | deploy: 10 | runs-on: ubuntu-20.04 11 | concurrency: 12 | group: ${{ github.workflow }}-${{ github.ref }} 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | 17 | - name: Setup mdBook 18 | uses: peaceiris/actions-mdbook@v1 19 | with: 20 | mdbook-version: '0.4.10' 21 | # mdbook-version: 'latest' 22 | 23 | - run: mdbook build 24 | 25 | - name: Deploy 26 | uses: peaceiris/actions-gh-pages@v3 27 | if: ${{ github.ref == 'refs/heads/main' }} 28 | with: 29 | github_token: ${{ secrets.GITHUB_TOKEN }} 30 | publish_dir: ./book 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | book/* 2 | *.aux 3 | plots/* 4 | target/ 5 | Cargo.lock 6 | 7 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "linfa-book" 3 | version = "0.2.0" 4 | authors = ["Christopher Moran "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | plotters = "0.3" 11 | ndarray = "0.15" 12 | ndarray-stats = "0.5" 13 | linfa = "0.7" 14 | linfa-clustering = "0.7" 15 | linfa-linear = "0.7" 16 | linfa-datasets = {version = "0.7", features = ["winequality", "diabetes"]} 17 | linfa-nn = "0.7" 18 | rand = "0.8" 19 | -------------------------------------------------------------------------------- /LICENSE-APACHE-2.0: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /LICENSE-CC-BY-SA: -------------------------------------------------------------------------------- 1 | Attribution-ShareAlike 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-ShareAlike 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-ShareAlike 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. BY-SA Compatible License means a license listed at 88 | creativecommons.org/compatiblelicenses, approved by Creative 89 | Commons as essentially the equivalent of this Public License. 90 | 91 | d. Copyright and Similar Rights means copyright and/or similar rights 92 | closely related to copyright including, without limitation, 93 | performance, broadcast, sound recording, and Sui Generis Database 94 | Rights, without regard to how the rights are labeled or 95 | categorized. For purposes of this Public License, the rights 96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 97 | Rights. 98 | 99 | e. Effective Technological Measures means those measures that, in the 100 | absence of proper authority, may not be circumvented under laws 101 | fulfilling obligations under Article 11 of the WIPO Copyright 102 | Treaty adopted on December 20, 1996, and/or similar international 103 | agreements. 104 | 105 | f. Exceptions and Limitations means fair use, fair dealing, and/or 106 | any other exception or limitation to Copyright and Similar Rights 107 | that applies to Your use of the Licensed Material. 108 | 109 | g. License Elements means the license attributes listed in the name 110 | of a Creative Commons Public License. The License Elements of this 111 | Public License are Attribution and ShareAlike. 112 | 113 | h. Licensed Material means the artistic or literary work, database, 114 | or other material to which the Licensor applied this Public 115 | License. 116 | 117 | i. Licensed Rights means the rights granted to You subject to the 118 | terms and conditions of this Public License, which are limited to 119 | all Copyright and Similar Rights that apply to Your use of the 120 | Licensed Material and that the Licensor has authority to license. 121 | 122 | j. Licensor means the individual(s) or entity(ies) granting rights 123 | under this Public License. 124 | 125 | k. Share means to provide material to the public by any means or 126 | process that requires permission under the Licensed Rights, such 127 | as reproduction, public display, public performance, distribution, 128 | dissemination, communication, or importation, and to make material 129 | available to the public including in ways that members of the 130 | public may access the material from a place and at a time 131 | individually chosen by them. 132 | 133 | l. Sui Generis Database Rights means rights other than copyright 134 | resulting from Directive 96/9/EC of the European Parliament and of 135 | the Council of 11 March 1996 on the legal protection of databases, 136 | as amended and/or succeeded, as well as other essentially 137 | equivalent rights anywhere in the world. 138 | 139 | m. You means the individual or entity exercising the Licensed Rights 140 | under this Public License. Your has a corresponding meaning. 141 | 142 | 143 | Section 2 -- Scope. 144 | 145 | a. License grant. 146 | 147 | 1. Subject to the terms and conditions of this Public License, 148 | the Licensor hereby grants You a worldwide, royalty-free, 149 | non-sublicensable, non-exclusive, irrevocable license to 150 | exercise the Licensed Rights in the Licensed Material to: 151 | 152 | a. reproduce and Share the Licensed Material, in whole or 153 | in part; and 154 | 155 | b. produce, reproduce, and Share Adapted Material. 156 | 157 | 2. Exceptions and Limitations. For the avoidance of doubt, where 158 | Exceptions and Limitations apply to Your use, this Public 159 | License does not apply, and You do not need to comply with 160 | its terms and conditions. 161 | 162 | 3. Term. The term of this Public License is specified in Section 163 | 6(a). 164 | 165 | 4. Media and formats; technical modifications allowed. The 166 | Licensor authorizes You to exercise the Licensed Rights in 167 | all media and formats whether now known or hereafter created, 168 | and to make technical modifications necessary to do so. The 169 | Licensor waives and/or agrees not to assert any right or 170 | authority to forbid You from making technical modifications 171 | necessary to exercise the Licensed Rights, including 172 | technical modifications necessary to circumvent Effective 173 | Technological Measures. For purposes of this Public License, 174 | simply making modifications authorized by this Section 2(a) 175 | (4) never produces Adapted Material. 176 | 177 | 5. Downstream recipients. 178 | 179 | a. Offer from the Licensor -- Licensed Material. Every 180 | recipient of the Licensed Material automatically 181 | receives an offer from the Licensor to exercise the 182 | Licensed Rights under the terms and conditions of this 183 | Public License. 184 | 185 | b. Additional offer from the Licensor -- Adapted Material. 186 | Every recipient of Adapted Material from You 187 | automatically receives an offer from the Licensor to 188 | exercise the Licensed Rights in the Adapted Material 189 | under the conditions of the Adapter's License You apply. 190 | 191 | c. No downstream restrictions. You may not offer or impose 192 | any additional or different terms or conditions on, or 193 | apply any Effective Technological Measures to, the 194 | Licensed Material if doing so restricts exercise of the 195 | Licensed Rights by any recipient of the Licensed 196 | Material. 197 | 198 | 6. No endorsement. Nothing in this Public License constitutes or 199 | may be construed as permission to assert or imply that You 200 | are, or that Your use of the Licensed Material is, connected 201 | with, or sponsored, endorsed, or granted official status by, 202 | the Licensor or others designated to receive attribution as 203 | provided in Section 3(a)(1)(A)(i). 204 | 205 | b. Other rights. 206 | 207 | 1. Moral rights, such as the right of integrity, are not 208 | licensed under this Public License, nor are publicity, 209 | privacy, and/or other similar personality rights; however, to 210 | the extent possible, the Licensor waives and/or agrees not to 211 | assert any such rights held by the Licensor to the limited 212 | extent necessary to allow You to exercise the Licensed 213 | Rights, but not otherwise. 214 | 215 | 2. Patent and trademark rights are not licensed under this 216 | Public License. 217 | 218 | 3. To the extent possible, the Licensor waives any right to 219 | collect royalties from You for the exercise of the Licensed 220 | Rights, whether directly or through a collecting society 221 | under any voluntary or waivable statutory or compulsory 222 | licensing scheme. In all other cases the Licensor expressly 223 | reserves any right to collect such royalties. 224 | 225 | 226 | Section 3 -- License Conditions. 227 | 228 | Your exercise of the Licensed Rights is expressly made subject to the 229 | following conditions. 230 | 231 | a. Attribution. 232 | 233 | 1. If You Share the Licensed Material (including in modified 234 | form), You must: 235 | 236 | a. retain the following if it is supplied by the Licensor 237 | with the Licensed Material: 238 | 239 | i. identification of the creator(s) of the Licensed 240 | Material and any others designated to receive 241 | attribution, in any reasonable manner requested by 242 | the Licensor (including by pseudonym if 243 | designated); 244 | 245 | ii. a copyright notice; 246 | 247 | iii. a notice that refers to this Public License; 248 | 249 | iv. a notice that refers to the disclaimer of 250 | warranties; 251 | 252 | v. a URI or hyperlink to the Licensed Material to the 253 | extent reasonably practicable; 254 | 255 | b. indicate if You modified the Licensed Material and 256 | retain an indication of any previous modifications; and 257 | 258 | c. indicate the Licensed Material is licensed under this 259 | Public License, and include the text of, or the URI or 260 | hyperlink to, this Public License. 261 | 262 | 2. You may satisfy the conditions in Section 3(a)(1) in any 263 | reasonable manner based on the medium, means, and context in 264 | which You Share the Licensed Material. For example, it may be 265 | reasonable to satisfy the conditions by providing a URI or 266 | hyperlink to a resource that includes the required 267 | information. 268 | 269 | 3. If requested by the Licensor, You must remove any of the 270 | information required by Section 3(a)(1)(A) to the extent 271 | reasonably practicable. 272 | 273 | b. ShareAlike. 274 | 275 | In addition to the conditions in Section 3(a), if You Share 276 | Adapted Material You produce, the following conditions also apply. 277 | 278 | 1. The Adapter's License You apply must be a Creative Commons 279 | license with the same License Elements, this version or 280 | later, or a BY-SA Compatible License. 281 | 282 | 2. You must include the text of, or the URI or hyperlink to, the 283 | Adapter's License You apply. You may satisfy this condition 284 | in any reasonable manner based on the medium, means, and 285 | context in which You Share Adapted Material. 286 | 287 | 3. You may not offer or impose any additional or different terms 288 | or conditions on, or apply any Effective Technological 289 | Measures to, Adapted Material that restrict exercise of the 290 | rights granted under the Adapter's License You apply. 291 | 292 | 293 | Section 4 -- Sui Generis Database Rights. 294 | 295 | Where the Licensed Rights include Sui Generis Database Rights that 296 | apply to Your use of the Licensed Material: 297 | 298 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 299 | to extract, reuse, reproduce, and Share all or a substantial 300 | portion of the contents of the database; 301 | 302 | b. if You include all or a substantial portion of the database 303 | contents in a database in which You have Sui Generis Database 304 | Rights, then the database in which You have Sui Generis Database 305 | Rights (but not its individual contents) is Adapted Material, 306 | 307 | including for purposes of Section 3(b); and 308 | c. You must comply with the conditions in Section 3(a) if You Share 309 | all or a substantial portion of the contents of the database. 310 | 311 | For the avoidance of doubt, this Section 4 supplements and does not 312 | replace Your obligations under this Public License where the Licensed 313 | Rights include other Copyright and Similar Rights. 314 | 315 | 316 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 317 | 318 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 319 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 320 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 321 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 322 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 323 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 324 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 325 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 326 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 327 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 328 | 329 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 330 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 331 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 332 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 333 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 334 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 335 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 336 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 337 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 338 | 339 | c. The disclaimer of warranties and limitation of liability provided 340 | above shall be interpreted in a manner that, to the extent 341 | possible, most closely approximates an absolute disclaimer and 342 | waiver of all liability. 343 | 344 | 345 | Section 6 -- Term and Termination. 346 | 347 | a. This Public License applies for the term of the Copyright and 348 | Similar Rights licensed here. However, if You fail to comply with 349 | this Public License, then Your rights under this Public License 350 | terminate automatically. 351 | 352 | b. Where Your right to use the Licensed Material has terminated under 353 | Section 6(a), it reinstates: 354 | 355 | 1. automatically as of the date the violation is cured, provided 356 | it is cured within 30 days of Your discovery of the 357 | violation; or 358 | 359 | 2. upon express reinstatement by the Licensor. 360 | 361 | For the avoidance of doubt, this Section 6(b) does not affect any 362 | right the Licensor may have to seek remedies for Your violations 363 | of this Public License. 364 | 365 | c. For the avoidance of doubt, the Licensor may also offer the 366 | Licensed Material under separate terms or conditions or stop 367 | distributing the Licensed Material at any time; however, doing so 368 | will not terminate this Public License. 369 | 370 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 371 | License. 372 | 373 | 374 | Section 7 -- Other Terms and Conditions. 375 | 376 | a. The Licensor shall not be bound by any additional or different 377 | terms or conditions communicated by You unless expressly agreed. 378 | 379 | b. Any arrangements, understandings, or agreements regarding the 380 | Licensed Material not stated herein are separate from and 381 | independent of the terms and conditions of this Public License. 382 | 383 | 384 | Section 8 -- Interpretation. 385 | 386 | a. For the avoidance of doubt, this Public License does not, and 387 | shall not be interpreted to, reduce, limit, restrict, or impose 388 | conditions on any use of the Licensed Material that could lawfully 389 | be made without permission under this Public License. 390 | 391 | b. To the extent possible, if any provision of this Public License is 392 | deemed unenforceable, it shall be automatically reformed to the 393 | minimum extent necessary to make it enforceable. If the provision 394 | cannot be reformed, it shall be severed from this Public License 395 | without affecting the enforceability of the remaining terms and 396 | conditions. 397 | 398 | c. No term or condition of this Public License will be waived and no 399 | failure to comply consented to unless expressly agreed to by the 400 | Licensor. 401 | 402 | d. Nothing in this Public License constitutes or may be interpreted 403 | as a limitation upon, or waiver of, any privileges and immunities 404 | that apply to the Licensor or You, including from the legal 405 | processes of any jurisdiction or authority. 406 | 407 | 408 | ======================================================================= 409 | 410 | Creative Commons is not a party to its public 411 | licenses. Notwithstanding, Creative Commons may elect to apply one of 412 | its public licenses to material it publishes and in those instances 413 | will be considered the “Licensor.” The text of the Creative Commons 414 | public licenses is dedicated to the public domain under the CC0 Public 415 | Domain Dedication. Except for the limited purpose of indicating that 416 | material is shared under a Creative Commons public license or as 417 | otherwise permitted by the Creative Commons policies published at 418 | creativecommons.org/policies, Creative Commons does not authorize the 419 | use of the trademark "Creative Commons" or any other trademark or logo 420 | of Creative Commons without its prior written consent including, 421 | without limitation, in connection with any unauthorized modifications 422 | to any of its public licenses or any other arrangements, 423 | understandings, or agreements concerning use of licensed material. For 424 | the avoidance of doubt, this paragraph does not form part of the 425 | public licenses. 426 | 427 | Creative Commons may be contacted at creativecommons.org. 428 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2021 Lorenz Schmidt, Christopher Moran 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The Rust Machine Learning Book 2 | 3 | This repository contains the source of "The Rust Machine Learning Book". 4 | 5 | ## Purpose 6 | 7 | The aim of this book is to demonstrate how the Rust language can be used for Machine Learning tasks. They encompass classical ML algorithms, like linear regression and KMeans clustering, but also more modern approaches. Most of the classical algorithms are contained in the `rust-ml/linfa` crate and ready to use. 8 | 9 | ## Audience 10 | 11 | The reader should have a basic knowledge of Rust type-system and linear algebra. A small recap on `rust-ndarray` type system should familiarize the reader with its applications and limitations. 12 | 13 | ## Requirements 14 | 15 | Building this book requires [mdBook](https://github.com/rust-lang/mdBook). 16 | ```bash 17 | $ cargo install mdbook 18 | ``` 19 | 20 | ## Building 21 | You can build the book with 22 | 23 | ```bash 24 | $ mdbook build 25 | ``` 26 | 27 | and append 28 | 29 | ```bash 30 | $ mdbook build --open 31 | # 32 | $ mdbook serve 33 | ``` 34 | 35 | in order to open it afterwards. 36 | 37 | Code samples are contained in the `examples/` directory, and can be built as a group or individually using: 38 | ```bash 39 | $ cargo build --all 40 | # or 41 | $ cargo run --example name_of_algorithm 42 | ``` 43 | 44 | By default, all plots will be written to the `target/` directory, so as not to be indexed by git. -------------------------------------------------------------------------------- /book.toml: -------------------------------------------------------------------------------- 1 | [book] 2 | authors = ["Lorenz Schmidt", "Christopher Moran"] 3 | language = "en" 4 | multilingual = false 5 | src = "src" 6 | title = "Rust Machine Learning Book" 7 | 8 | [output.html] 9 | # Mathjax support addition 10 | mathjax-support = true 11 | -------------------------------------------------------------------------------- /examples/clustering_comparison.rs: -------------------------------------------------------------------------------- 1 | use linfa_book::*; 2 | // ANCHOR: libraries 3 | // Import the linfa prelude and KMeans algorithm 4 | use linfa::prelude::*; 5 | use linfa_clustering::{Dbscan, KMeans}; 6 | // We'll build our dataset on our own using ndarray and rand 7 | use ndarray::prelude::*; 8 | // Import the plotters crate to create the scatter plot 9 | use plotters::prelude::*; 10 | use rand::prelude::*; 11 | // ANCHOR_END: libraries 12 | 13 | fn main() { 14 | // ANCHOR: build_chart_base 15 | let chart_dims = (900, 400); 16 | let root = 17 | BitMapBackend::new("target/clustering_comparison.png", chart_dims).into_drawing_area(); 18 | root.fill(&WHITE).unwrap(); 19 | let areas = root.split_by_breakpoints([chart_dims.0 / 2], [chart_dims.1]); 20 | 21 | let x_lim = 0.0..10.0f32; 22 | let y_lim = 0.0..10.0f32; 23 | 24 | let mut ctx_a = ChartBuilder::on(&areas[0]) 25 | .set_label_area_size(LabelAreaPosition::Left, 40) // Put in some margins 26 | .set_label_area_size(LabelAreaPosition::Right, 40) 27 | .set_label_area_size(LabelAreaPosition::Bottom, 40) 28 | .caption("DBSCAN", ("sans-serif", 20)) // Set a caption and font 29 | .build_cartesian_2d(x_lim.clone(), y_lim.clone()) 30 | .expect("Couldn't build our ChartBuilder"); 31 | 32 | ctx_a.configure_mesh().draw().unwrap(); 33 | let root_area_a = ctx_a.plotting_area(); 34 | 35 | let mut ctx_b = ChartBuilder::on(&areas[1]) 36 | .set_label_area_size(LabelAreaPosition::Left, 40) // Put in some margins 37 | .set_label_area_size(LabelAreaPosition::Right, 40) 38 | .set_label_area_size(LabelAreaPosition::Bottom, 40) 39 | .caption("KMeans", ("sans-serif", 20)) // Set a caption and font 40 | .build_cartesian_2d(x_lim, y_lim) 41 | .expect("Couldn't build our ChartBuilder"); 42 | 43 | ctx_b.configure_mesh().draw().unwrap(); 44 | let root_area_b = ctx_b.plotting_area(); 45 | 46 | // Plot space for both algos should be set up by this point 47 | 48 | // Now going to creat data that will be shared for both 49 | let circle: Array2 = create_circle([5.0, 5.0], 1.0, 100); // Cluster 0 50 | let donut_1: Array2 = create_hollow_circle([5.0, 5.0], [2.0, 3.0], 400); // Cluster 1 51 | let donut_2: Array2 = create_hollow_circle([5.0, 5.0], [4.5, 4.75], 1000); // Cluster 2 52 | let noise: Array2 = create_square([5.0, 5.0], 10.0, 100); // Random noise 53 | 54 | let data = ndarray::concatenate( 55 | Axis(0), 56 | &[circle.view(), donut_1.view(), donut_2.view(), noise.view()], 57 | ) 58 | .expect("An error occurred while stacking the dataset"); 59 | 60 | // DBSCAN STARTS HERE 61 | 62 | let min_points = 20; 63 | let clusters = Dbscan::params(min_points) 64 | .tolerance(0.6) 65 | .transform(&data) 66 | .unwrap(); 67 | println!("{:#?}", clusters); 68 | 69 | check_array_for_plotting(&circle); // Panics if that's not true 70 | 71 | for i in 0..data.shape()[0] { 72 | let coordinates = data.slice(s![i, 0..2]); 73 | 74 | let point = match clusters[i] { 75 | Some(0) => Circle::new( 76 | (coordinates[0], coordinates[1]), 77 | 3, 78 | ShapeStyle::from(&RED).filled(), 79 | ), 80 | Some(1) => Circle::new( 81 | (coordinates[0], coordinates[1]), 82 | 3, 83 | ShapeStyle::from(&GREEN).filled(), 84 | ), 85 | Some(2) => Circle::new( 86 | (coordinates[0], coordinates[1]), 87 | 3, 88 | ShapeStyle::from(&BLUE).filled(), 89 | ), 90 | // Making sure our pattern-matching is exhaustive 91 | _ => Circle::new( 92 | (coordinates[0], coordinates[1]), 93 | 3, 94 | ShapeStyle::from(&BLACK).filled(), 95 | ), 96 | }; 97 | 98 | root_area_a 99 | .draw(&point) 100 | .expect("An error occurred while drawing the point!"); 101 | } 102 | // ANCHOR_END: plot_points 103 | 104 | // KMEANS STARTS HERE 105 | 106 | let dataset = DatasetBase::from(data); 107 | let rng = thread_rng(); // Random number generator 108 | let n_clusters = 3; 109 | let model = KMeans::params_with_rng(n_clusters, rng) 110 | .max_n_iterations(200) 111 | .tolerance(1e-5) 112 | .fit(&dataset) 113 | .expect("Error while fitting KMeans to the dataset"); 114 | 115 | let dataset = model.predict(dataset); 116 | 117 | for i in 0..dataset.records.shape()[0] { 118 | let coordinates = dataset.records.slice(s![i, 0..2]); 119 | 120 | let point = match dataset.targets[i] { 121 | 0 => Circle::new( 122 | (coordinates[0], coordinates[1]), 123 | 3, 124 | ShapeStyle::from(&RED).filled(), 125 | ), 126 | 1 => Circle::new( 127 | (coordinates[0], coordinates[1]), 128 | 3, 129 | ShapeStyle::from(&GREEN).filled(), 130 | ), 131 | 132 | 2 => Circle::new( 133 | (coordinates[0], coordinates[1]), 134 | 3, 135 | ShapeStyle::from(&BLUE).filled(), 136 | ), 137 | // Making sure our pattern-matching is exhaustive 138 | _ => Circle::new( 139 | (coordinates[0], coordinates[1]), 140 | 3, 141 | ShapeStyle::from(&BLACK).filled(), 142 | ), 143 | }; 144 | 145 | root_area_b 146 | .draw(&point) 147 | .expect("An error occurred while drawing the point!"); 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /examples/dbscan.rs: -------------------------------------------------------------------------------- 1 | use linfa_book::*; 2 | // ANCHOR: libraries 3 | // Import the linfa prelude and KMeans algorithm 4 | use linfa::prelude::*; 5 | use linfa_clustering::Dbscan; 6 | // We'll build our dataset on our own using ndarray and rand 7 | use ndarray::prelude::*; 8 | // Import the plotters crate to create the scatter plot 9 | use plotters::prelude::*; 10 | // ANCHOR_END: libraries 11 | 12 | fn main() { 13 | // ANCHOR: create_circles 14 | // The goal is to be able to find each of these as distinct, and exclude some of the noise 15 | let circle: Array2 = create_circle([5.0, 5.0], 1.0, 100); // Cluster 0 16 | let donut_1: Array2 = create_hollow_circle([5.0, 5.0], [2.0, 3.0], 400); // Cluster 1 17 | let donut_2: Array2 = create_hollow_circle([5.0, 5.0], [4.5, 4.75], 1000); // Cluster 2 18 | let noise: Array2 = create_square([5.0, 5.0], 10.0, 100); // Random noise 19 | 20 | let data = ndarray::concatenate( 21 | Axis(0), 22 | &[circle.view(), donut_1.view(), donut_2.view(), noise.view()], 23 | ) 24 | .expect("An error occurred while stacking the dataset"); 25 | // ANCHOR_END: create_circles 26 | 27 | // ANCHOR: create_and_run_model 28 | // Compared to linfa's KMeans algorithm, the DBSCAN implementation can operate 29 | // directly on an ndarray `Array2` data structure, so there's no need to convert it 30 | // into the linfa-native `Dataset` first. 31 | let min_points = 20; 32 | let clusters = Dbscan::params(min_points) 33 | .tolerance(0.6) 34 | .transform(&data) 35 | .unwrap(); 36 | println!("{:#?}", clusters); 37 | // ANCHOR_END: create_and_run_model 38 | 39 | // ANCHOR: build_chart_base 40 | let root = BitMapBackend::new("target/dbscan.png", (600, 400)).into_drawing_area(); 41 | root.fill(&WHITE).unwrap(); 42 | 43 | let x_lim = 0.0..10.0f32; 44 | let y_lim = 0.0..10.0f32; 45 | 46 | let mut ctx = ChartBuilder::on(&root) 47 | .set_label_area_size(LabelAreaPosition::Left, 40) // Put in some margins 48 | .set_label_area_size(LabelAreaPosition::Right, 40) 49 | .set_label_area_size(LabelAreaPosition::Bottom, 40) 50 | .caption("DBSCAN", ("sans-serif", 25)) // Set a caption and font 51 | .build_cartesian_2d(x_lim, y_lim) 52 | .expect("Couldn't build our ChartBuilder"); 53 | // ANCHOR_END: build_chart_base 54 | 55 | // ANCHOR: configure_chart 56 | ctx.configure_mesh().draw().unwrap(); 57 | let root_area = ctx.plotting_area(); 58 | // ANCHOR_END: configure_chart 59 | 60 | // ANCHOR: run_check_for_plotting; 61 | // check_array_for_plotting(dataset: &Array2) -> bool {} 62 | check_array_for_plotting(&circle); // Panics if that's not true 63 | // ANCHOR_END: run_check_for_plotting 64 | 65 | // ANCHOR: plot_points 66 | for i in 0..data.shape()[0] { 67 | let coordinates = data.slice(s![i, 0..2]); 68 | 69 | let point = match clusters[i] { 70 | Some(0) => Circle::new( 71 | (coordinates[0], coordinates[1]), 72 | 3, 73 | ShapeStyle::from(&RED).filled(), 74 | ), 75 | Some(1) => Circle::new( 76 | (coordinates[0], coordinates[1]), 77 | 3, 78 | ShapeStyle::from(&GREEN).filled(), 79 | ), 80 | Some(2) => Circle::new( 81 | (coordinates[0], coordinates[1]), 82 | 3, 83 | ShapeStyle::from(&BLUE).filled(), 84 | ), 85 | // Making sure our pattern-matching is exhaustive 86 | // Note that we can define a custom color using RGB 87 | _ => Circle::new( 88 | (coordinates[0], coordinates[1]), 89 | 3, 90 | ShapeStyle::from(&RGBColor(255, 255, 255)).filled(), 91 | ), 92 | }; 93 | 94 | root_area 95 | .draw(&point) 96 | .expect("An error occurred while drawing the point!"); 97 | } 98 | // ANCHOR_END: plot_points 99 | } 100 | -------------------------------------------------------------------------------- /examples/kmeans.rs: -------------------------------------------------------------------------------- 1 | use linfa_book::*; 2 | // ANCHOR: libraries 3 | // Import the linfa prelude and KMeans algorithm 4 | use linfa::prelude::*; 5 | use linfa_clustering::KMeans; 6 | use linfa_nn::distance::L2Dist; 7 | // We'll build our dataset on our own using ndarray and rand 8 | use ndarray::prelude::*; 9 | use rand::prelude::*; 10 | // Import the plotters crate to create the scatter plot 11 | use plotters::prelude::*; 12 | // ANCHOR_END: libraries 13 | 14 | fn main() { 15 | // ANCHOR: create_squares 16 | let square_1: Array2 = create_square([7.0, 5.0], 1.0, 150); // Cluster 1 17 | let square_2: Array2 = create_square([2.0, 2.0], 2.0, 150); // Cluster 2 18 | let square_3: Array2 = create_square([3.0, 8.0], 1.0, 150); // Cluster 3 19 | let square_4: Array2 = create_square([5.0, 5.0], 9.0, 300); // A bunch of noise across them all 20 | 21 | let data: Array2 = ndarray::concatenate( 22 | Axis(0), 23 | &[ 24 | square_1.view(), 25 | square_2.view(), 26 | square_3.view(), 27 | square_4.view(), 28 | ], 29 | ) 30 | .expect("An error occurred while stacking the dataset"); 31 | //ANCHOR_END: create_squares 32 | 33 | // ANCHOR: create_model 34 | let dataset = DatasetBase::from(data); 35 | let rng = thread_rng(); // Random number generator 36 | let n_clusters = 3; 37 | let model = KMeans::params_with(n_clusters, rng, L2Dist) 38 | .max_n_iterations(200) 39 | .tolerance(1e-5) 40 | .fit(&dataset) 41 | .expect("Error while fitting KMeans to the dataset"); 42 | // ANCHOR_END: create_model 43 | 44 | // ANCHOR: run_model 45 | let dataset = model.predict(dataset); 46 | println!("{:?}", dataset.records.shape()); 47 | println!("{:?}", dataset.targets.shape()); 48 | // ANCHOR_END: run_model 49 | 50 | // ANCHOR: build_chart_base 51 | let root = BitMapBackend::new("target/kmeans.png", (600, 400)).into_drawing_area(); 52 | root.fill(&WHITE).unwrap(); 53 | 54 | let x_lim = 0.0..10.0f32; 55 | let y_lim = 0.0..10.0f32; 56 | 57 | let mut ctx = ChartBuilder::on(&root) 58 | .set_label_area_size(LabelAreaPosition::Left, 40) // Put in some margins 59 | .set_label_area_size(LabelAreaPosition::Right, 40) 60 | .set_label_area_size(LabelAreaPosition::Bottom, 40) 61 | .caption("KMeans Demo", ("sans-serif", 25)) // Set a caption and font 62 | .build_cartesian_2d(x_lim, y_lim) 63 | .expect("Couldn't build our ChartBuilder"); 64 | // ANCHOR_END: build_chart_base 65 | 66 | // ANCHOR: configure_chart 67 | ctx.configure_mesh().draw().unwrap(); 68 | let root_area = ctx.plotting_area(); 69 | // ANCHOR_END: configure_chart 70 | 71 | // ANCHOR: run_check_for_plotting; 72 | // check_array_for_plotting(dataset: &Array2) -> bool {} 73 | check_array_for_plotting(&dataset.records); // Panics if that's not true 74 | // ANCHOR_END: run_check_for_plotting 75 | 76 | // ANCHOR: plot_points 77 | for i in 0..dataset.records.shape()[0] { 78 | let coordinates = dataset.records.slice(s![i, 0..2]); 79 | 80 | let point = match dataset.targets[i] { 81 | 0 => Circle::new( 82 | (coordinates[0], coordinates[1]), 83 | 3, 84 | ShapeStyle::from(&RED).filled(), 85 | ), 86 | 1 => Circle::new( 87 | (coordinates[0], coordinates[1]), 88 | 3, 89 | ShapeStyle::from(&GREEN).filled(), 90 | ), 91 | 92 | 2 => Circle::new( 93 | (coordinates[0], coordinates[1]), 94 | 3, 95 | ShapeStyle::from(&BLUE).filled(), 96 | ), 97 | // Making sure our pattern-matching is exhaustive 98 | _ => Circle::new( 99 | (coordinates[0], coordinates[1]), 100 | 3, 101 | ShapeStyle::from(&BLACK).filled(), 102 | ), 103 | }; 104 | 105 | root_area 106 | .draw(&point) 107 | .expect("An error occurred while drawing the point!"); 108 | } 109 | // ANCHOR_END: plot_points 110 | } 111 | -------------------------------------------------------------------------------- /examples/linear_regression.rs: -------------------------------------------------------------------------------- 1 | use linfa::prelude::*; 2 | use linfa_linear::{LinearRegression, TweedieRegressor}; 3 | use ndarray::prelude::*; 4 | use ndarray_stats::QuantileExt; 5 | use plotters::prelude::*; 6 | 7 | fn main() { 8 | // ANCHOR: create_data 9 | let array: Array2 = linfa_book::create_curve(1.0, 1.0, 0.0, 50, [0.0, 7.0]); 10 | // ANCHOR_END: create_data 11 | 12 | // ANCHOR: data_format 13 | // Converting from an array to a Linfa Dataset can be the trickiest part of this process 14 | let (data, targets) = ( 15 | array.slice(s![.., 0..1]).to_owned(), 16 | array.column(1).to_owned(), 17 | ); 18 | 19 | let x_max = data.max().unwrap().ceil(); 20 | let y_max = targets.max().unwrap().ceil(); 21 | // ANCHOR_END: data_format 22 | 23 | // ANCHOR: build_dataset 24 | let dataset = Dataset::new(data, targets).with_feature_names(vec!["x", "y"]); 25 | // ANCHOR_END: build_dataset 26 | 27 | // ANCHOR: regression 28 | let lin_reg = LinearRegression::new(); 29 | let model = lin_reg.fit(&dataset).unwrap(); 30 | // ANCHOR_END: regression 31 | 32 | let root_area = 33 | BitMapBackend::new("target/linear_regression.png", (600, 400)).into_drawing_area(); 34 | root_area.fill(&WHITE).unwrap(); 35 | 36 | // ANCHOR: chart_context 37 | let mut ctx = ChartBuilder::on(&root_area) 38 | .set_label_area_size(LabelAreaPosition::Left, 40) 39 | .set_label_area_size(LabelAreaPosition::Bottom, 40) 40 | .caption("Legend", ("sans-serif", 40)) 41 | .caption("Linear Regression", ("sans-serif", 40)) 42 | .build_cartesian_2d(0.0..x_max + 1.0, 0.0..y_max + 1.0) 43 | .unwrap(); 44 | // ANCHOR_END: chart_context 45 | 46 | ctx.configure_mesh().draw().unwrap(); 47 | 48 | // ANCHOR: draw_line 49 | let mut line_points = Vec::with_capacity(2); 50 | for i in (0..8i32).step_by(1) { 51 | line_points.push((i as f64, (i as f64 * model.params()[0]) + model.intercept())); 52 | } 53 | // We can configure the rounded precision of our result here 54 | let precision = 2; 55 | let label = format!( 56 | "y = {:.2$}x + {:.2}", 57 | model.params()[0], 58 | model.intercept(), 59 | precision 60 | ); 61 | ctx.draw_series(LineSeries::new(line_points, &BLACK)) 62 | .unwrap() 63 | .label(&label); 64 | // ANCHOR_END: draw_line 65 | 66 | // ANCHOR: draw_points 67 | let num_points = array.shape()[0]; 68 | let mut points = Vec::with_capacity(num_points); 69 | for i in 0..array.shape()[0] { 70 | let point = (array[[i, 0]], array[[i, 1]]); 71 | let circle = Circle::new(point, 5, &RED); 72 | points.push(circle); 73 | } 74 | 75 | ctx.draw_series(points).unwrap(); 76 | // ANCHOR_END: draw_points 77 | 78 | // ANCHOR: labels 79 | ctx.configure_series_labels() 80 | .border_style(&BLACK) 81 | .background_style(&WHITE.mix(0.8)) 82 | .draw() 83 | .unwrap(); 84 | // ANCHOR_END: labels 85 | } 86 | -------------------------------------------------------------------------------- /src/2_intro.md: -------------------------------------------------------------------------------- 1 | # Introduction to Machine Learning with Rust 2 | 3 | ## What is this book for? 4 | 5 | This book aims to provide an accessible introduction to machine learning and data science in the Rust ecosystem. Each chapter will have the description of an algorithm, and walk through a code example from start to finish. 6 | 7 | ## Who is this book for? 8 | 9 | This book is written with two primary audiences in mind: developers who are familiar with machine learning and want to write their code Rust, and developers who are familiar with Rust and want to do some machine learning. 10 | 11 | In both cases, we generally assume a basic level of understanding of the Rust programming language, although mastery is certainly not required! If you're brand new to the language, it's suggested to start off by reading [*The Rust Programming Language*](https://doc.rust-lang.org/book/), then returning when you feel a little more comfortable. In particular, it's worth reviewing the sections on [ownership](https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html), [error handling](https://doc.rust-lang.org/book/ch09-00-error-handling.html), and [functional features](https://doc.rust-lang.org/book/ch13-00-functional-features.html). Perhaps just as importantly as Rust's syntax, a familiarity with the library/crates ecosystem and documentation practices will prove very valuable. Machine learning in many cases sits near the top of the stack; especially when one is working with data, there are usually several layers of code beneath what the top one is doing. That's one of the benefits of working in Rust; these lower layers are often also written in Rust, which makes the abstraction more transparent and empowers developers to dig fearlessly into the underlying aspects of these programs. 12 | 13 | Conversely, we don't assume an in-depth knowledge of machine learning (i.e. mathematical familiarity of the field). Some familiarity with the algorithms may be helpful, but the descriptions and code contained in here should help to build a foundation of some of these topics. 14 | 15 | ## How to use this book 16 | 17 | Each chapter's code sample is available (and the plots generated) from the code available under the `examples` directory, and can be run independently of the book. For example, to run the entirety of the code example for the KMeans algorithm, you would do the following: 18 | ```bash 19 | # From repo directory 20 | $ cargo run --release --example kmeans 21 | ``` 22 | 23 | ## An additional note 24 | 25 | Like much of Rust, many of the libraries in this ecosystem empower people to write code that they might otherwise not feel able to write otherwise. Machine learning provides a really interesting and useful set of tools. That is a great benefit! However, as the saying goes, with great power comes great responsibility. This means that **it is the responsibility of each developer individually, and the community as a whole, to make sure that the code we write is not being used in harmful ways and make ethical decisions surrounding our work.** 26 | 27 | As a start, we suggest making yourself familiar with some of the resources that have been collected by the Institute for Ethical Machine Learning [here](https://github.com/EthicalML/awesome-artificial-intelligence-guidelines). 28 | 29 | -------------------------------------------------------------------------------- /src/3_kmeans.md: -------------------------------------------------------------------------------- 1 | ## Getting Started With The K-Means Clustering Algorithm 2 | 3 | ### What is KMeans? 4 | 5 | KMeans is one of the most common clustering algorithms, where a set of unlabeled data points are grouped into a set of clusters such that each data point is part of the cluster with the centroid nearest to itself. 6 | 7 | The centroid of a cluster is calculated as the mean, or average, of the points assigned to that cluster. The [`linfa`](https://github.com/rust-ml/linfa) crate provides an implementation of the standard algorithm for this process, known as "Lloyd's algorithm." 8 | 9 | KMeans is_iterative_, meaning that it progressively refines the points assigned to each cluster, and therefore a new centroid for that cluster (leading to new points being assigned to it) during each successive iteration. At a high level, there are three main steps to the algorithm: 10 | 1. **Initialization**: Choose our initial set of centroids--this can happen randomly or be set by the user, but the number of clusters/centroids is always defined ahead of time in KMeans 11 | 2. **Assignment**: Assign each observation to the nearest cluster (minimum distance between the observation and the cluster's centroid); 12 | 3. **Update**: Recompute the centroid of each cluster. 13 | 14 | Steps 2 and 3 are repeated until the location of the centroid for each cluster converges. 15 | 16 | 17 | ### Using KMeans with `linfa-clustering` 18 | 19 | First, we'll start off by importing the dependencies, which can be found in the `Cargo.toml` file in the `code/` folder. Note that we need to include both the overall `linfa` crate, which will provide some of the structuring, as well as the actual KMeans algorithm from the `linfa-clustering` crate. 20 | ```rust,no_run 21 | {{#include ../examples/kmeans.rs:libraries}} 22 | ``` 23 | After importing the dependencies, we'll start off by creating a set of data points that we want to cluster. This data could be imported from somewhere else through a library like [`ndarray_csv`](https://github.com/paulkernfeld/ndarray-csv) or [`polars`](https://github.com/ritchie46/polars), but we'll create it manually here for this example. The most important thing is that we end up with an `ndarray` `Array2` data structure. 24 | 25 | For this dataset, we'll get started with a few squares filled with random points, in which each square is defined by a center point, edge length, number of points contained within it's boundaries. Each of those squares should end up having a high-enough density to be the center point of one of our clusters. We'll also create a large, sparse set of points covering all over them to act as background noise, which will help to visually demonstrate how disparate points get assigned to clusters. 26 | 27 | Since each of these squares is being created individually, we'll then need to consolidate them along (along the y-axis) by using the `ndarray::concatenate()` function, which concatenates arrays along the specified axis. 28 | 29 | 30 | ```rust,no_run 31 | {{#include ../examples/kmeans.rs:create_squares}} 32 | ``` 33 | 34 | Now that we have our data, we'll convert it into the form that Linfa uses for training and predicting model, the `Dataset` type. 35 | 36 | In order to actually build the KMeans algorithm, there are two additional things that we'll need: the number of clusters we're expecting, and a random number generator (RNG). While it is possible to manually define the starting location of each centroid, we often use KMeans in situations where we don't know much about the data ahead of time, so randomly creating them can work just as well. This represents one of the trade-offs of using KMeans; it will always converge towards a minima, it's just not guaranteed that is will be a *global* minima. 37 | 38 | Using these variables, we can build our model, and set a few additional parameters that may be useful along the way. In this case, those parameters are the maximum number of iterations that we'll allow before stopping, and the tolerance in terms of distance between each iteration that we'll allow before considering our fit to have converged. Finally, we'll run the `fit()` method against the dataset. 39 | 40 | ```rust,no_run 41 | {{#include ../examples/kmeans.rs:create_model}} 42 | ``` 43 | 44 | In order to actually get the cluster assignments for the original dataset, however, we'll need to actually run the model against the dataset it was trained on. This may seem a little counter-intuitive, but this two-step process of `fit()` and `predict()` helps to make the overall modelling system more flexible. 45 | 46 | Calling the `predict()` method will also convert the `dataset` variable from a single `Array2` in a pair of arrays `(records, targets): (Array2, Array1)`. 47 | 48 | ```rust,no_run 49 | {{#include ../examples/kmeans.rs:run_model}} 50 | ``` 51 | 52 | At this point, we have all of our points and their assigned clusters, and we can move onto doing some data visualization! The initial step in that process is setting up the backend, of which the `plotters` library has several. We'll use the `BitMapBackend`, which will save the chart we create into a `.png` image file with a specified name and size. 53 | 54 | A `ChartBuilder` data structure will be laid on top of the backend, which will actually be responsible for the placing of chart elements like labels, margins, grids, etc. which are all defined by the user. In this case, we want to graph on a two-dimensional Cartesian plane, with both the x- and y-axes set to a range of `[0..10]`. 55 | 56 | ```rust,no_run 57 | {{#include ../examples/kmeans.rs:build_chart_base}} 58 | ``` 59 | 60 | The final part of this process consists of actually adding in the mesh, and setting up an area for plotting each of the individual data points. 61 | 62 | ```rust,no_run 63 | {{#include ../examples/kmeans.rs:configure_chart}} 64 | ``` 65 | Before starting to plot, however, we want to make sure that the data we're going to plot is the right shape; a two-dimensional dataset with two columns. Fortunately, a simple helper function has been written to double-check if that is true. 66 | 67 | ```rust,no_run 68 | {{#include ../examples/kmeans.rs:run_check_for_plotting}} 69 | ``` 70 | 71 | We're now ready to begin plotting! It is possible to plot elements as part of a series, but it's easy (and still quite fast) to do each individually. First, the coordinates from each element get pulled from the `dataset.records` array. Those coordinates are then used to create a dot, where we pattern-match on the point's assigned cluster from `dataset.targets` to choose the color. 72 | 73 | Notice that the pattern-matching here is exhaustive! For KMeans, this isn't important, because each point is automatically assigned to a cluster. However, that's not necessarily true for all clustering algorithms, where some less-important data points can be left behind, so it's good practice to make sure that we consider that possibility. Finally, we'll actually draw the chart element we created using that information onto the chart area. 74 | 75 | ```rust,no_run 76 | {{#include ../examples/kmeans.rs:plot_points}} 77 | ``` 78 | And that's it! Note that there's not separate step for saving the final product, since that's automatically taken care of by our backend. The final visualization of the clusters created by the KMeans algorithm will look like the following: 79 | 80 | ![KMeans](assets/kmeans.png) 81 | -------------------------------------------------------------------------------- /src/4_dbscan.md: -------------------------------------------------------------------------------- 1 | ## Using DBSCAN with `linfa-clustering` 2 | 3 | ### What is the DBSCAN algorithm? 4 | 5 | The DBSCAN algorithm (Density-Based Spatial Clustering Algorithm with Noise) was originally published in [1996](https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.121.9220), and has since become one of the most popular and well-known clustering algorithms available. 6 | 7 | 8 | ### Comparison with KMeans 9 | 10 | Before getting into the code, let's examine how these differences in approach plays out on different types of data. In the images below, both the DBSCAN and KMeans algorithms were applied to the same dataset. The KMeans algorithm was manually set to find 3 clusters (remember, DBSCAN automatically calculates the number of clusters based on the provided parameters). 11 | 12 | Comparison 13 | 14 | This example[^1] demonstrates two of the major strengths of DBSCAN over an algorithm like KMeans; it is able to automatically detect the number of clusters that meet the set of given parameters. Keep in mind that this doesn't mean DBSCAN require less information about the dataset, but rather that the information it does require differs from an algorithm like KMeans. 15 | 16 | DBSCAN does a great job at finding clustering that are spatially contiguous, but not necessarily confined to single region. This is where the "and Noise" part of the algorithm's name comes in. Especially in real-world data, there's often data that won't fit well into a given cluster. These can be outliers or points that don't demonstrate good alignment with any of the main clusters. DBSCAN doesn't require that they do. Instead, it will simply give them a cluster label of `None` (in our example, these are graphically the black points). However, DBSCAN does a good job at analyzing existing information, it doesn't predict new data, which is one of its main drawbacks 17 | 18 | Comparatively, KMeans will take into account each point in the dataset, which means outliers can negatively affect the local optimal location for a given cluster's centroid in order to accommodate them. Euclidean space is linear, which means that small changes in the data result in proportionately small changes to the position of the centroids. This is problematic when there are outliers in the data. 19 | 20 | ### Using DSBCAN with `linfa` 21 | 22 | Compared to 23 | ```rust,no_run 24 | {{#include ../examples/dbscan.rs:libraries}} 25 | ``` 26 | 27 | Instead of having a several higher-density clusters different areas, we'll take advantage of DBSCAN's ability to follow spatially-contiguous non-localized clusters by building our data out of both filled and hollow circles, with some random noise tossed in as well. The end goal will be to re-find each of these clusters, and exclude some of the noise! 28 | 29 | ```rust,no_run 30 | {{#include ../examples/dbscan.rs:create_circles}} 31 | ``` 32 | Compared to `linfa`'s KMeans algorithm, the DBSCAN implementation is able to operate directly on a ndarray `Array2` data structure, so there's no need to convert it into the `linfa`-native `Dataset` type first. It's also worth pointing out that choosing the chosen parameters often take some experimentation and tuning before they produce results that actually make sense. This is one of the areas where data visualization can be really valuable; it is helpful in developing some spatial intuition about your data set and understand how your choice of hyperparameters will affect the results produced by the algorithm. 33 | 34 | ```rust,no_run 35 | {{#include ../examples/dbscan.rs:create_and_run_model}} 36 | ``` 37 | We'll skip over setting up `ChartBuilder` struct and drawing areas from the `plotters` crate, since it's exactly the same as in the [KMeans](./3_kmeans.md) example. 38 | 39 | Remember how we mentioned DBSCAN is an algorithm that can exclude noise? That's particularly important for the pattern-matching in this case, since we're almost guaranteed to end up with some values that don't fit nicely into any of our expected clusters. Since we generated an artificial dataset, we know the number of clusters that should be generated, and where they're located. However, that won't always be the case. In that situation, we could instead examine the number of clusters afterwards, create a colormap using custom RGB colors which matches the highest number of clusters, and plot it that way. 40 | 41 | ```rust,no_run 42 | {{#include ../examples/dbscan.rs:plot_points}} 43 | ``` 44 | 45 | As a result, we then get the following chart, where each cluster is uniquely identified, and some of the random noise associated with the dataset is discarded. 46 | 47 | DBSCAN 48 | 49 | --- 50 | [^1]: This code for this comparison is actually separate from the main DBSCAN example. It can be found at `examples/clustering_comparison.rs`. -------------------------------------------------------------------------------- /src/5_linear_regression.md: -------------------------------------------------------------------------------- 1 | ## Linear Regression 2 | 3 | Now that we've gotten some clustering under our belt, let's take a look at one of the other common data science tasks: linear regression on two-dimensional data. This example includes code for both calculating the linear equation using `linfa`, as well as code for plotting both the data and line on a single graph using the `plotters` library. 4 | 5 | Per usual, we'll create some data using one of our built-in functions. This simply creates an `Array2` with two columns, one of which will be our x-axis and the other our y-axis. We're generating this artificially, but remember, we could get this from a real data source like processing a CSV file or reading in values from a sensor. 6 | 7 | ```rust,no_run 8 | {{#include ../examples/linear_regression.rs:create_data}} 9 | ``` 10 | Now that we have the initial data, let's break that down into something that we can use for our regression; a `data` array and a `target` array. Fortunately, this is pretty simple with the `slice()` and `column()` functions provided by `ndarray`. We're also going to want to grab the maximum values for our arrays (and round them up to the nearest integer using the `ceil()` function) to be used for plotting those values a little bit later. 11 | 12 | ```rust,no_run 13 | {{#include ../examples/linear_regression.rs:data_format}} 14 | ``` 15 | 16 | Once the data is formatted, we'll be able to nicely add it into the `linfa`-native `Dataset` format, along with the appropriate feature names. If you're running into funky error related to array shapes in your code, this section and the step before (where we create our `data` and `target` data structures) are ones you should double-check; dynamically-shaped arrays as found in most scientific computing libraries, Rust-based or not, can be tricky. 17 | 18 | In fact, as you may have experienced yourself, it's very common that the pre-processing steps of many data science problems (filtering, formatting, distributing, etc.) are actually the most complicated and often where a little bit of additional effort can save you a lot of trouble down the road. 19 | 20 | ```rust,no_run 21 | {{#include ../examples/linear_regression.rs:build_dataset}} 22 | ``` 23 | 24 | However, now we have our data formatted properly and in the `Dataset` format, actually running the regression is pretty simple; we only need to create our `LinearRegression` object and fit it to the dataset. 25 | 26 | ```rust,no_run 27 | {{#include ../examples/linear_regression.rs:regression}} 28 | ``` 29 | 30 | We're going to leave out a little bit of the boilerplate (check the repository for the full example code), but you'll notice that when we set up our chart context, we'll use the rounded maximum values in both the `data` and `target` arrays to set our maximum chart range (as mentioned earlier). 31 | 32 | ```rust,no_run 33 | {{#include ../examples/linear_regression.rs:chart_context}} 34 | ``` 35 | 36 | Now that the chart is good to go, we'll start off by drawing our best fit line using the linear equation we derived above. We can't just supply the equation and let the plotting figure it out; instead, what we'll do it create series of points that exactly match this equation at regular intervals, and connect those with a smooth, continuous line. If this seems clunky, just remember: we have a nice, smooth solution this time around, but that might not always be the case. In the future, we might want more complicated polynomial, or even a discontinuous function. This approach (smoothly connecting an arbitrary set of points) is applicable to a wide variety of potential applications. 37 | 38 | Once we add our line, we'll also want a nice label, with a set level of precision; this will be added to the legend once our chart is complete. 39 | 40 | ```rust,no_run 41 | {{#include ../examples/linear_regression.rs:draw_line}} 42 | ``` 43 | 44 | Now that the line is present, we can add our points; this should look very familiar, as we're functionally doing something similar to the clustering examples we've already put together. 45 | 46 | ```rust,no_run 47 | {{#include ../examples/linear_regression.rs:draw_points}} 48 | ``` 49 | 50 | Finally, we'll configure the labels that we'll assigned to each of the series that we've drawn on the chart. 51 | 52 | ```rust,no_run 53 | {{#include ../examples/linear_regression.rs:labels}} 54 | ``` 55 | 56 | And we're done (ooooh, ahhhh, pretty)! 57 | 58 | linear regression 59 | -------------------------------------------------------------------------------- /src/SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | - [Introduction to Machine Learning with Rust](./2_intro.md) 4 | - [Getting Started With The KMeans Algorithm](./3_kmeans.md) 5 | - [Clustering with DBSCAN](./4_dbscan.md) 6 | - [Linear Regression](./5_linear_regression.md) 7 | -------------------------------------------------------------------------------- /src/assets/clustering_comparison.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-ml/book/a7e764bc8a6c207740ed1849b926f3aad42ad913/src/assets/clustering_comparison.png -------------------------------------------------------------------------------- /src/assets/dbscan.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-ml/book/a7e764bc8a6c207740ed1849b926f3aad42ad913/src/assets/dbscan.png -------------------------------------------------------------------------------- /src/assets/kmeans.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-ml/book/a7e764bc8a6c207740ed1849b926f3aad42ad913/src/assets/kmeans.png -------------------------------------------------------------------------------- /src/assets/kmeans_test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-ml/book/a7e764bc8a6c207740ed1849b926f3aad42ad913/src/assets/kmeans_test.png -------------------------------------------------------------------------------- /src/assets/linear_regression.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-ml/book/a7e764bc8a6c207740ed1849b926f3aad42ad913/src/assets/linear_regression.png -------------------------------------------------------------------------------- /src/kmeans_dbscan_comparison.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-ml/book/a7e764bc8a6c207740ed1849b926f3aad42ad913/src/kmeans_dbscan_comparison.png -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | use ndarray::prelude::*; 2 | use rand::prelude::*; 3 | use std::f32; 4 | 5 | // Creates random points contained in an approximately square area 6 | pub fn create_square(center_point: [f32; 2], edge_length: f32, num_points: usize) -> Array2 { 7 | // We 8 | let mut data: Array2 = Array2::zeros((num_points, 2)); 9 | let mut rng = rand::thread_rng(); 10 | for i in 0..num_points { 11 | let x = rng.gen_range(-edge_length * 0.5..edge_length * 0.5); // generates a float between 0 and 1 12 | let y = rng.gen_range(-edge_length * 0.5..edge_length * 0.5); 13 | data[[i, 0]] = center_point[0] + x; 14 | data[[i, 1]] = center_point[1] + y; 15 | } 16 | 17 | data 18 | } 19 | 20 | // Creates a circle of random points 21 | pub fn create_circle(center_point: [f32; 2], radius: f32, num_points: usize) -> Array2 { 22 | let mut data: Array2 = Array2::zeros((num_points, 2)); 23 | let mut rng = rand::thread_rng(); 24 | for i in 0..num_points { 25 | let theta = rng.gen_range(0.0..2.0 * f32::consts::PI); 26 | let r = rng.gen_range(0.0..radius); 27 | let x = r * f32::cos(theta); 28 | let y = r * f32::sin(theta); 29 | 30 | data[[i, 0]] = center_point[0] + x; 31 | data[[i, 1]] = center_point[1] + y; 32 | } 33 | 34 | data 35 | } 36 | 37 | // Creates a line y = m*x + b with some noise 38 | pub fn create_line(m: f64, b: f64, num_points: usize, min_max: [f64; 2]) -> Array2 { 39 | let mut data: Array2 = Array2::zeros((num_points, 2)); 40 | 41 | let mut rng = rand::thread_rng(); 42 | for i in 0..num_points { 43 | let var_y = rng.gen_range(-0.5..0.5f64); 44 | data[[i, 0]] = rng.gen_range(min_max[0]..min_max[1]); 45 | data[[i, 1]] = (m * data[[i, 0]]) + b + var_y; 46 | } 47 | 48 | data 49 | } 50 | 51 | // Creates a quadratic y = m*x^2 + b with some noise 52 | pub fn create_curve(m: f64, pow: f64, b: f64, num_points: usize, min_max: [f64; 2]) -> Array2 { 53 | let mut data: Array2 = Array2::zeros((num_points, 2)); 54 | 55 | let mut rng = rand::thread_rng(); 56 | for i in 0..num_points { 57 | let var_y = rng.gen_range(-0.5..0.5f64); 58 | data[[i, 0]] = rng.gen_range(min_max[0]..min_max[1]); 59 | data[[i, 1]] = (m * data[[i, 0]].powf(pow)) + b + var_y; 60 | } 61 | 62 | data 63 | } 64 | 65 | // Creates a hollow circle of random points with a specified inner and outer diameter 66 | pub fn create_hollow_circle( 67 | center_point: [f32; 2], 68 | radius: [f32; 2], 69 | num_points: usize, 70 | ) -> Array2 { 71 | assert!(radius[0] < radius[1]); 72 | let mut data: Array2 = Array2::zeros((num_points, 2)); 73 | let mut rng = rand::thread_rng(); 74 | for i in 0..num_points { 75 | let theta = rng.gen_range(0.0..2.0 * f32::consts::PI); 76 | let r = rng.gen_range(radius[0]..radius[1]); 77 | let x = r * f32::cos(theta); 78 | let y = r * f32::sin(theta); 79 | 80 | data[[i, 0]] = center_point[0] + x; 81 | data[[i, 1]] = center_point[1] + y; 82 | } 83 | 84 | data 85 | } 86 | 87 | // Check the array has the correct shape for plotting (Two-dimensional, with 2 columns) 88 | pub fn check_array_for_plotting(arr: &Array2) -> bool { 89 | if (arr.shape().len() != 2) || (arr.shape()[1] != 2) { 90 | panic!( 91 | "Array shape of {:?} is incorrect for 2D plotting!", 92 | arr.shape() 93 | ); 94 | // false 95 | } else { 96 | true 97 | } 98 | } 99 | --------------------------------------------------------------------------------