├── .gitignore ├── LICENSE ├── README.md ├── examples ├── accelerometerMachineryFailureRecognitionNrf52840 │ ├── platformio.ini │ └── src │ │ └── main.cpp ├── baggingOnEsp32 │ ├── .gitignore │ ├── platformio.ini │ └── src │ │ └── main.cpp ├── bechmarkBreastCancerOnEsp32 │ ├── platformio.ini │ └── src │ │ ├── Breast_cancer.h │ │ └── main.cpp ├── bechmarkHeartDiseaseOnEsp32 │ ├── platformio.ini │ └── src │ │ ├── Heart_disease.h │ │ └── main.cpp ├── bechmarkIrisWithAIEFSOnEsp32 │ ├── platformio.ini │ └── src │ │ ├── Iris_flowers.h │ │ ├── TDC │ │ └── main.cpp ├── bechmarkingOnArduinoUno │ ├── platformio.ini │ └── src │ │ └── main.cpp ├── bechmarkingOnEsp32 │ ├── platformio.ini │ └── src │ │ └── main.cpp ├── bencharkIrisWithAIEFSOnNrf52 │ ├── .gitignore │ ├── platformio.ini │ └── src │ │ ├── AIEFS │ │ ├── Iris_flowers.h │ │ └── main.cpp ├── benchmarkBreastCancerWithAIEFS │ ├── platformio.ini │ └── src │ │ ├── AIEFS │ │ ├── Breast_cancer.h │ │ └── main.cpp ├── benchmarkingOnNrf52840 │ ├── platformio.ini │ └── src │ │ └── main.cpp ├── binaryPhysicalActivityClassificationOnNrf52840 │ ├── platformio.ini │ └── src │ │ └── main.cpp ├── cncLearnerOnEsp32C6 │ ├── .gitignore │ ├── measuredData │ │ ├── class_1 │ │ │ ├── 1_num_0_class_1.csv │ │ │ ├── 1_num_1_class_1.csv │ │ │ ├── num_0_class_1.csv │ │ │ ├── num_1_class_1.csv │ │ │ ├── num_2_class_1.csv │ │ │ ├── num_3_class_1.csv │ │ │ ├── try1_num_0_class_1.csv │ │ │ └── try1_num_1_class_1.csv │ │ ├── class_2 │ │ │ ├── 1_1num_0_class_2.csv │ │ │ ├── 1_num_1_class_2.csv │ │ │ ├── num_0_class_2.csv │ │ │ ├── num_1_class_2.csv │ │ │ ├── num_2_class_2.csv │ │ │ ├── num_3_class_2.csv │ │ │ ├── try1_num_1_class_2.csv │ │ │ └── try1_num_2_class_2.csv │ │ └── tree.csv │ ├── platformio.ini │ └── src │ │ ├── computationFunctions.h │ │ ├── globals.h │ │ ├── main.cpp │ │ └── sdHelpFunctions.h ├── irisTestTrainFromSDOnEsp32 │ ├── iris_test_ok.csv │ ├── iris_train_ok.csv │ ├── platformio.ini │ └── src │ │ └── main.cpp ├── saveLoadMBEDonNrf52840 │ ├── mbed_app.json │ ├── platformio.ini │ └── src │ │ └── main.cpp ├── saveLoadOnEsp32 │ ├── platformio.ini │ └── src │ │ └── main.cpp ├── saveLoadOnNrf52 │ ├── platformio.ini │ └── src │ │ └── main.cpp ├── sitStandWalkClassificationOnNrf52840 │ ├── platformio.ini │ └── src │ │ └── main.cpp └── testForMemoryLeaksOnEsp32 │ ├── platformio.ini │ └── src │ └── main.cpp ├── img ├── aLotOfSamples.png ├── benchmarking.png ├── libmanagerinstallation.png ├── pioinst.png └── someSamples.png ├── library.properties ├── robots.txt └── src ├── ProcessingFunctions.h ├── TinyDecisionTreeClassifier.cpp └── TinyDecisionTreeClassifier.h /.gitignore: -------------------------------------------------------------------------------- 1 | library.json -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TinyDecisionTreeClassifier 2 | ## Introduction 3 | 4 | TinyDecisionTreeClassifier is a simple but elegant standalone library for training decision trees directly on the edge. Decision trees were chosen since they are very fast and easily interpretable. 5 | 6 | Main features are: 7 | - Based around classic C4.5 decision tree algorithm for continious variables. 8 | - This is a standalone library. Since the library depends only on , ,, "math.h" and "float.h" it can easily be ported to other frameworks like Mbed/ESP-IDF. 9 | - Fast and small. Checkout the benchmarking examples for Arduino Uno, Esp32 and NRF52840 provided in examples folder and the benchmarking graph. 10 | - Simple to use. I tried to make the methods similar to the DecisionTreeClassifier from scikit-learn. If you ever used it, you will quickly recognize the familiar names like fit(), predict() and score(). 11 | - The average comlexity is O(Nlog(N)) (because of the quicksort). 12 | - Template usage allows to train 8-bit models, which boosts performance on 8-bit MCUs and significantly reduces RAM requirements. 13 | - Trained tree visualisation is supported via plot() method. 14 | 15 | ## Installation 16 | The library can be installed via Arduino IDE library manager or via Platformio library manager: 17 | ![Arduino IDE installation](img/libmanagerinstallation.png) 18 | ![Platoformio installation](img/pioinst.png) 19 | 20 | ## Benchmarking 21 | The following picture shows the maximum training time on different mcus, the labels and data were generated using random() function. In practice training times are usually shorter. The number of training features was 5. 22 | ![Benchmarking](img/someSamples.png) 23 | 24 | ![Benchmarking](img/aLotOfSamples.png) 25 | ## Examples 26 | There are several examples available. 27 | 28 | ### bechmarkingOnArduinoUno 29 | You can change Treetype from int8_t to float and see how it changes the performance. 30 | 31 | ### bechmarkingOnEsp32 32 | Very fast decision tree training thanks to higher Esp32 clock speed. 33 | 34 | ### benchmarkingOnNrf52840 35 | Nrf52840 is a good compromise between speed and power consumption. Also, it is often used in smartwatches. 36 | 37 | ### binaryPhysicalActivityClassificationOnNrf52840 38 | 39 | MPU6050 accelerometer is needed to measure the 3-axis acceleration. Any other accel is also ok if you can make it work. 9 features were extracted in total, 3 for each axis: mean, variance and average difference between the current and the previous sample. 40 | 41 | After the power is on, the example records data labeled as class 0 for 90s, then the same for class 1. Then automatically classifies the incoming data in a while loop. 42 | After power is on you can put an accelerometer in idle position. After the 90s you can rotate it by 90 degrees. When the data are measured and the training is complete, the device classifies input in while loop(if the accel is rotated by 90 degree). You can use the similar approach to classify the physical activity(ensure that the accelerometer is in different positions during each training period, so it is not classifying based on mean value only). The LED blinking speed depends on the classified class. 43 | 44 | I managed to classify activity/no activity with this code. You can check the tree that was built in serial terminal. 45 | 46 | ### sitStandWalkClassificationOnNrf52840 47 | 48 | Again, accelerometer is required. This time there are 3 classes and the time interval is around 150s. It is possible to classify sit/walk/stand with this code, however while recording the data you should ensure that the accelerometer is in different positions during each training period.(So it is not classifying based on mean value only). If you want to change the number of classes, use TREE_NUMBER_OF_CLASSES 49 | 50 | 51 | ### accelerometerMachineryFailureRecognitionNrf52840 52 | In this example the accelerometer sampling frequency is increased to 50 Hz. The Nrf52840 recognized fan failure state based on data it learned during the first two minutes of training. 53 | 54 | [Arduino-compatible machinery failure recognition on the edge with TinyDecisionTreeClassifier](https://www.youtube.com/watch?v=4Kl571AXN1U) 55 | -------------------------------------------------------------------------------- /examples/accelerometerMachineryFailureRecognitionNrf52840/platformio.ini: -------------------------------------------------------------------------------- 1 | ; PlatformIO Project Configuration File 2 | ; 3 | ; Build options: build flags, source filter 4 | ; Upload options: custom upload port, speed and extra flags 5 | ; Library options: dependencies, extra library storages 6 | ; Advanced options: extra scripting 7 | ; 8 | ; Please visit documentation for the other options and examples 9 | ; https://docs.platformio.org/page/projectconf.html 10 | 11 | [env:nrf52840_dk] 12 | platform = nordicnrf52 13 | framework = arduino 14 | upload_protocol = stlink 15 | board = nrf52840_dk 16 | lib_deps = tockn/MPU6050_tockn@^1.5.2 -------------------------------------------------------------------------------- /examples/accelerometerMachineryFailureRecognitionNrf52840/src/main.cpp: -------------------------------------------------------------------------------- 1 | #define ARDUINO_GENERIC 2 | #include 3 | // #define __DTR_DEBUG_ 4 | #include "TinyDecisionTreeClassifier.h" 5 | #include 6 | #include 7 | 8 | MPU6050 mpu6050(Wire); 9 | #define WINDOW_SIZE_SECONDS 2 10 | #define SAMPLING_FREQENCY 50 11 | #define WINDOW_BUFFER_SIZE WINDOW_SIZE_SECONDS*SAMPLING_FREQENCY 12 | 13 | #define TRREE_TRAINING_TIME_SECONDS 30 14 | #define TRREE_TEST_TIME_SECONDS (uint32_t)(TRREE_TRAINING_TIME_SECONDS/2) 15 | #define TREE_NUMBER_OF_CLASSES 2 16 | #define TREE_NUMBER_OF_FEATURES 9 17 | #define TREE_NUMBER_OF_TRAINING_SAMPLES (uint32_t(TREE_NUMBER_OF_CLASSES*TRREE_TRAINING_TIME_SECONDS/WINDOW_SIZE_SECONDS))+1 18 | #define TREE_NUMBER_OF_TEST_SAMPLES (uint32_t(TREE_NUMBER_OF_CLASSES*TRREE_TEST_TIME_SECONDS/WINDOW_SIZE_SECONDS))+1 19 | 20 | #define MAX_TREE_DEPTH 4 21 | typedef float Treetype; 22 | Treetype X_train[TREE_NUMBER_OF_TRAINING_SAMPLES][TREE_NUMBER_OF_FEATURES]; 23 | Treetype Y_train[TREE_NUMBER_OF_TRAINING_SAMPLES][1]; 24 | 25 | Treetype X_test[TREE_NUMBER_OF_TEST_SAMPLES][TREE_NUMBER_OF_FEATURES]; 26 | Treetype Y_test[TREE_NUMBER_OF_TEST_SAMPLES][1]; 27 | 28 | Treetype **X; 29 | Treetype **Y; 30 | Treetype **X_t; 31 | Treetype **Y_t; 32 | 33 | #define STATUS_LED_PIN 2 //P0.13 34 | 35 | void setup() { 36 | 37 | Serial.begin(115200); 38 | Serial.println("Here we go!"); 39 | X = new Treetype *[TREE_NUMBER_OF_TRAINING_SAMPLES]; 40 | Y = new Treetype *[TREE_NUMBER_OF_TRAINING_SAMPLES]; 41 | for(uint32_t i=0;i(20)/((k+1)*(k+1)*(k+1))){ 102 | digitalWrite(STATUS_LED_PIN,ledstate); 103 | ledstate=!ledstate; 104 | blinkCtr=0; 105 | } 106 | } 107 | float mean; 108 | float variance; 109 | float avgDif; 110 | computeFeatures(aXbuffer,&mean,&variance,&avgDif); 111 | X[i*(k+1)][0]=mean; 112 | X[i*(k+1)][1]=avgDif; 113 | X[i*(k+1)][2]=variance; 114 | 115 | computeFeatures(aYbuffer,&mean,&variance,&avgDif); 116 | X[i*(k+1)][3]=mean; 117 | X[i*(k+1)][4]=avgDif; 118 | X[i*(k+1)][5]=variance; 119 | 120 | computeFeatures(aZbuffer,&mean,&variance,&avgDif); 121 | X[i*(k+1)][6]=mean; 122 | X[i*(k+1)][7]=avgDif; 123 | X[i*(k+1)][8]=variance; 124 | 125 | Y[i*(k+1)][0]=k; 126 | } 127 | Serial.println("Recording test data"); 128 | for(uint32_t i=0;i<(TRREE_TEST_TIME_SECONDS/WINDOW_SIZE_SECONDS);i++){ 129 | for(uint32_t j=0;j(20)/((k+1)*(k+1)*(k+1))){ 137 | digitalWrite(STATUS_LED_PIN,ledstate); 138 | ledstate=!ledstate; 139 | blinkCtr=0; 140 | } 141 | } 142 | float mean; 143 | float variance; 144 | float avgDif; 145 | computeFeatures(aXbuffer,&mean,&variance,&avgDif); 146 | X[i*(k+1)][0]=mean; 147 | X[i*(k+1)][1]=avgDif; 148 | X[i*(k+1)][2]=variance; 149 | 150 | computeFeatures(aYbuffer,&mean,&variance,&avgDif); 151 | X[i*(k+1)][3]=mean; 152 | X[i*(k+1)][4]=avgDif; 153 | X[i*(k+1)][5]=variance; 154 | 155 | computeFeatures(aZbuffer,&mean,&variance,&avgDif); 156 | X[i*(k+1)][6]=mean; 157 | X[i*(k+1)][7]=avgDif; 158 | X[i*(k+1)][8]=variance; 159 | 160 | Y[i*(k+1)][0]=k; 161 | } 162 | 163 | digitalWrite(STATUS_LED_PIN,0); 164 | delay(10000); 165 | 166 | for(uint32_t i=0;i<(TRREE_TRAINING_TIME_SECONDS/WINDOW_SIZE_SECONDS);i++){ 167 | for(uint32_t n=0;n clf(MAX_TREE_DEPTH,2); 176 | 177 | before = micros(); 178 | clf.fit(X,Y,TREE_NUMBER_OF_TRAINING_SAMPLES,TREE_NUMBER_OF_FEATURES); 179 | after = micros(); 180 | Serial.print("Training time: "); 181 | Serial.println(after-before); 182 | Serial.print("Accuracy:"); 183 | accuracy=clf.score(X_t,Y_t,TREE_NUMBER_OF_TEST_SAMPLES); 184 | Serial.println(accuracy); 185 | 186 | clf.plot(); 187 | Treetype k=0; 188 | while(1){ 189 | for(uint32_t j=0;j(10)/((k+1)*(k+1)*(k+1))){ 197 | digitalWrite(STATUS_LED_PIN,ledstate); 198 | ledstate=!ledstate; 199 | blinkCtr=0; 200 | } 201 | } 202 | float mean; 203 | float variance; 204 | float avgDif; 205 | computeFeatures(aXbuffer,&mean,&variance,&avgDif); 206 | Xp[0]=mean; 207 | Xp[1]=avgDif; 208 | Xp[2]=variance; 209 | 210 | computeFeatures(aYbuffer,&mean,&variance,&avgDif); 211 | Xp[3]=mean; 212 | Xp[4]=avgDif; 213 | Xp[5]=variance; 214 | 215 | computeFeatures(aZbuffer,&mean,&variance,&avgDif); 216 | Xp[6]=mean; 217 | Xp[7]=avgDif; 218 | Xp[8]=variance; 219 | 220 | k = clf.predict(Xp); 221 | Serial.print("Predicted label:"); 222 | Serial.println(k); 223 | Serial.println(accuracy); 224 | clf.plot(); 225 | } 226 | 227 | // digitalWrite(13,HIGH); 228 | // delay(100); 229 | // digitalWrite(13,LOW); 230 | // delay(1000); 231 | } 232 | -------------------------------------------------------------------------------- /examples/baggingOnEsp32/.gitignore: -------------------------------------------------------------------------------- 1 | .pio 2 | .vscode/.browse.c_cpp.db* 3 | .vscode/c_cpp_properties.json 4 | .vscode/launch.json 5 | .vscode/ipch 6 | -------------------------------------------------------------------------------- /examples/baggingOnEsp32/platformio.ini: -------------------------------------------------------------------------------- 1 | ; PlatformIO Project Configuration File 2 | ; 3 | ; Build options: build flags, source filter 4 | ; Upload options: custom upload port, speed and extra flags 5 | ; Library options: dependencies, extra library storages 6 | ; Advanced options: extra scripting 7 | ; 8 | ; Please visit documentation for the other options and examples 9 | ; https://docs.platformio.org/page/projectconf.html 10 | 11 | [env:esp32dev] 12 | platform = espressif32 13 | board = esp32dev 14 | framework = arduino 15 | monitor_speed = 115200 -------------------------------------------------------------------------------- /examples/baggingOnEsp32/src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // #define DTR_DEBUG_ 3 | #include "TinyDecisionTreeClassifier.h" 4 | #include "ProcessingFunctions.h" 5 | 6 | #define NUMBER_OF_FEATURES 5 7 | #define NUMBER_OF_SAMPLES 100 8 | #define MAX_TREE_DEPTH 3 9 | typedef float Treetype; 10 | Treetype X_const[NUMBER_OF_SAMPLES][NUMBER_OF_FEATURES]; 11 | Treetype Y_const[NUMBER_OF_SAMPLES][1]; 12 | Treetype **X; 13 | Treetype **Y; 14 | 15 | void fillBuffersWithRandom(void){ 16 | for(uint32_t i=0;i clf(MAX_TREE_DEPTH,2,TinyDecisionTreeClassifier::GINI); 37 | TinyDecisionTreeClassifier::RowsSubIndexes baggingRsi; 38 | sampleBagging(&baggingRsi,NUMBER_OF_SAMPLES,NUMBER_OF_SAMPLES*0.66); 39 | timeBefore = micros(); 40 | clf.fit(X,Y,NUMBER_OF_SAMPLES,NUMBER_OF_FEATURES,&baggingRsi); 41 | timeAfter = micros(); 42 | heapAfter = ESP.getFreeHeap(); 43 | benchmarkingTrainingTime+=(timeAfter-timeBefore); 44 | Treetype rslt; 45 | for(uint32_t j=0;j 2 | // #define DTR_DEBUG_ 3 | #include "TinyDecisionTreeClassifier.h" 4 | #include "ProcessingFunctions.h" 5 | 6 | typedef float Treetype; 7 | #include "Breast_cancer.h" 8 | 9 | #define MAX_TREE_DEPTH 4 10 | #define MIN_SAMPLES_SPLIT 10 11 | #define TEST_RATIO 0.33f 12 | #define TEST_SIZE (uint32_t)(NUMBER_OF_SAMPLES*TEST_RATIO) 13 | #define TRAIN_SIZE (uint32_t)(NUMBER_OF_SAMPLES-TEST_SIZE) 14 | 15 | // Treetype X_const[NUMBER_OF_SAMPLES][NUMBER_OF_FEATURES]; 16 | Treetype Y_const[NUMBER_OF_SAMPLES][1]; 17 | 18 | Treetype **X; 19 | Treetype **Y; 20 | 21 | #define BENCHMARK_AVERAGING 20 22 | void benchmark(void){ 23 | uint32_t timeBefore; 24 | uint32_t timeAfter; 25 | uint64_t benchmarkingTrainingTime = 0; 26 | uint64_t benchmarkingPredictionTime = 0; 27 | float totalScore=0; 28 | Serial.println("Bechmarking start"); 29 | for(uint32_t i=0;i(X,Y,NUMBER_OF_SAMPLES,NUMBER_OF_FEATURES); 31 | TinyDecisionTreeClassifier clf(MAX_TREE_DEPTH,MIN_SAMPLES_SPLIT,TinyDecisionTreeClassifier ::GINI); 32 | timeBefore = micros(); 33 | clf.fit(X+TEST_SIZE,Y+TEST_SIZE,TRAIN_SIZE,NUMBER_OF_FEATURES); 34 | // Serial.println("Tree before pruning: "); 35 | // clf.plot(); 36 | while(clf.prune(X,Y,TRAIN_SIZE)); 37 | timeAfter = micros(); 38 | benchmarkingTrainingTime+=(timeAfter-timeBefore); 39 | Treetype rslt; 40 | for(uint32_t j=0;j 2 | // #define DTR_DEBUG_ 3 | #include "TinyDecisionTreeClassifier.h" 4 | #include "ProcessingFunctions.h" 5 | 6 | typedef float Treetype; 7 | #include "Heart_disease.h" 8 | 9 | #define MAX_TREE_DEPTH 4 10 | #define MIN_SAMPLES_SPLIT 10 11 | #define TEST_RATIO 0.33f 12 | #define TEST_SIZE (uint32_t)(NUMBER_OF_SAMPLES*TEST_RATIO) 13 | #define TRAIN_SIZE (uint32_t)(NUMBER_OF_SAMPLES-TEST_SIZE) 14 | 15 | // Treetype X_const[NUMBER_OF_SAMPLES][NUMBER_OF_FEATURES]; 16 | Treetype Y_const[NUMBER_OF_SAMPLES][1]; 17 | 18 | Treetype **X; 19 | Treetype **Y; 20 | 21 | #define BENCHMARK_AVERAGING 20 22 | void benchmark(void){ 23 | uint32_t timeBefore; 24 | uint32_t timeAfter; 25 | uint64_t benchmarkingTrainingTime = 0; 26 | uint64_t benchmarkingPredictionTime = 0; 27 | float totalScore=0; 28 | Serial.println("Bechmarking start"); 29 | for(uint32_t i=0;i(X,Y,NUMBER_OF_SAMPLES,NUMBER_OF_FEATURES); 31 | TinyDecisionTreeClassifier clf(MAX_TREE_DEPTH,MIN_SAMPLES_SPLIT,TinyDecisionTreeClassifier ::GINI); 32 | timeBefore = micros(); 33 | clf.fit(X+TEST_SIZE,Y+TEST_SIZE,TRAIN_SIZE,NUMBER_OF_FEATURES); 34 | // Serial.println("Tree before pruning: "); 35 | // clf.plot(); 36 | while(clf.prune(X,Y,TRAIN_SIZE)); 37 | timeAfter = micros(); 38 | benchmarkingTrainingTime+=(timeAfter-timeBefore); 39 | Treetype rslt; 40 | for(uint32_t j=0;j 2 | // #define DTR_DEBUG_ 3 | #include "TinyDecisionTreeClassifier.h" 4 | 5 | typedef float Treetype; 6 | #include "Iris_flowers.h" 7 | 8 | #define MAX_TREE_DEPTH 4 9 | #define MIN_SAMPLES_SPLIT 10 10 | #define TEST_RATIO 0.33 11 | #define TEST_SIZE (uint32_t)(DATASET_SIZE*TEST_RATIO) 12 | #define TRAIN_SIZE DATASET_SIZE-TEST_SIZE 13 | 14 | // Treetype X_const[DATASET_SIZE][FEATURES_DIM]; 15 | Treetype Y_const[DATASET_SIZE][1]; 16 | 17 | Treetype **X; 18 | Treetype **Y; 19 | 20 | #define BENCHMARK_AVERAGING 5 21 | void benchmark(void){ 22 | uint32_t timeBefore; 23 | uint32_t timeAfter; 24 | uint64_t benchmarkingTrainingTime = 0; 25 | uint64_t benchmarkingPredictionTime = 0; 26 | Serial.println("Bechmarking start"); 27 | for(uint32_t i=0;i clf(MAX_TREE_DEPTH,MIN_SAMPLES_SPLIT,TinyDecisionTreeClassifier::GINI); 29 | timeBefore = micros(); 30 | clf.fit(X,Y,TRAIN_SIZE,FEATURES_DIM); 31 | // Serial.println("Tree before pruning: "); 32 | // clf.plot(); 33 | while(clf.prune(X,Y,TRAIN_SIZE)); 34 | timeAfter = micros(); 35 | benchmarkingTrainingTime+=(timeAfter-timeBefore); 36 | Treetype rslt; 37 | for(uint32_t j=0;j. 19 | 20 | AIfES-Express XOR training demo 21 | -------------------- 22 | 23 | Versions: 24 | 1.0.0 Initial version 25 | 26 | AIfES-Express is a simplified API for AIfES, which is directly integrated. So you can simply decide which variant you want to use. 27 | 28 | The sketch shows an example of how a neural network is trained from scratch in AIfES-Express using training data. 29 | As in the example "0_AIfES-Express_XOR_Inference", an XOR gate is mapped here using a neural network. 30 | The 4 different states of an XOR gate are fed in as training data here. 31 | The network structure is 2-3(Sigmoid)-1(Sigmoid) and Sigmoid is used as activation function. 32 | In the example, the weights are initialized randomly in a range of values from -2 to +2. The Gotrot initialization was inserted as an alternative and commented out. 33 | For the training the ADAM Optimizer is used, the SGD Optimizer was commented out. 34 | The optimizer runs a batch traininig over a maximum of 1000 epochs. 35 | The early stopping is activated and stops the training when a desired target loss is reached. 36 | The calculation is done in float 32. 37 | 38 | XOR truth table / training data 39 | Input Output 40 | 0 0 0 41 | 0 1 1 42 | 1 0 1 43 | 1 1 0 44 | 45 | Tested on: 46 | Arduino UNO 47 | Arduino Nano 33 BLE Sense 48 | Arduino Portenta H7 49 | 50 | You can find more AIfES tutorials here: 51 | https://create.arduino.cc/projecthub/aifes_team 52 | */ 53 | 54 | #include // include the AIfES libary 55 | 56 | #define TEST_RATIO 0.33 57 | #define TEST_SIZE (uint32_t)(DATASET_SIZE*TEST_RATIO) 58 | #define TRAINING_SIZE (uint32_t)(DATASET_SIZE-TEST_SIZE) 59 | 60 | #define FNN_3_LAYERS 3 61 | #define PRINT_INTERVAL 10 62 | #include "Iris_flowers.h" 63 | 64 | uint32_t global_epoch_counter = 0; 65 | 66 | // The print function for the loss. It can be customized. 67 | void printLoss(float loss) 68 | { 69 | global_epoch_counter = global_epoch_counter + 1; 70 | Serial.print(F("Epoch: ")); 71 | Serial.print(global_epoch_counter * PRINT_INTERVAL); 72 | Serial.print(F(" / Loss: ")); 73 | Serial.println(loss,5); 74 | 75 | } 76 | 77 | 78 | void error_handling_training(int8_t error_nr){ 79 | switch(error_nr){ 80 | case 0: 81 | //Serial.println(F("No Error :)")); 82 | break; 83 | case -1: 84 | Serial.println(F("ERROR! Tensor dtype")); 85 | break; 86 | case -2: 87 | Serial.println(F("ERROR! Tensor shape: Data Number")); 88 | break; 89 | case -3: 90 | Serial.println(F("ERROR! Input tensor shape does not correspond to ANN inputs")); 91 | break; 92 | case -4: 93 | Serial.println(F("ERROR! Output tensor shape does not correspond to ANN outputs")); 94 | break; 95 | case -5: 96 | Serial.println(F("ERROR! Use the crossentropy as loss for softmax")); 97 | break; 98 | case -6: 99 | Serial.println(F("ERROR! learn_rate or sgd_momentum negative")); 100 | break; 101 | case -7: 102 | Serial.println(F("ERROR! Init uniform weights min - max wrong")); 103 | break; 104 | case -8: 105 | Serial.println(F("ERROR! batch_size: min = 1 / max = Number of training data")); 106 | break; 107 | case -9: 108 | Serial.println(F("ERROR! Unknown activation function")); 109 | break; 110 | case -10: 111 | Serial.println(F("ERROR! Unknown loss function")); 112 | break; 113 | case -11: 114 | Serial.println(F("ERROR! Unknown init weights method")); 115 | break; 116 | case -12: 117 | Serial.println(F("ERROR! Unknown optimizer")); 118 | break; 119 | case -13: 120 | Serial.println(F("ERROR! Not enough memory")); 121 | break; 122 | default : 123 | Serial.println(F("Unknown error")); 124 | } 125 | } 126 | 127 | void error_handling_inference(int8_t error_nr){ 128 | switch(error_nr){ 129 | case 0: 130 | //Serial.println(F("No Error :)")); 131 | break; 132 | case -1: 133 | Serial.println(F("ERROR! Tensor dtype")); 134 | break; 135 | case -2: 136 | Serial.println(F("ERROR! Tensor shape: Data Number")); 137 | break; 138 | case -3: 139 | Serial.println(F("ERROR! Input tensor shape does not correspond to ANN inputs")); 140 | break; 141 | case -4: 142 | Serial.println(F("ERROR! Output tensor shape does not correspond to ANN outputs")); 143 | break; 144 | case -5: 145 | Serial.println(F("ERROR! Unknown activation function")); 146 | break; 147 | case -6: 148 | Serial.println(F("ERROR! Not enough memory")); 149 | break; 150 | default : 151 | Serial.println(F("Unknown error")); 152 | } 153 | } 154 | 155 | void setup() { 156 | Serial.begin(115200); //115200 baud rate (If necessary, change in the serial monitor) 157 | while (!Serial); 158 | 159 | //IMPORTANT 160 | //AIfES requires random weights for training 161 | //Here the random seed is generated by the noise of an analog pin 162 | srand(analogRead(A5)); 163 | 164 | Serial.println(F("AIfES-Express XOR training demo")); 165 | Serial.println(F("Type >training< to start")); 166 | 167 | } 168 | 169 | void loop() { 170 | 171 | while(Serial.available() > 0 ){ 172 | String str = Serial.readString(); 173 | if(str.indexOf("training") > -1) //Keyword "training" 174 | { 175 | 176 | Serial.println(F("AIfES:")); 177 | Serial.println(F("")); 178 | Serial.println(F("rand test")); 179 | Serial.println(rand()); 180 | 181 | global_epoch_counter = 0; 182 | 183 | uint32_t i; 184 | 185 | // -------------------------------- describe the feed forward neural network ---------------------------------- 186 | // neurons each layer 187 | // FNN_structure[0] = input layer with 2 inputs 188 | // FNN_structure[1] = hidden (dense) layer with 3 neurons 189 | // FNN_structure[2] = output (dense) layer with 1 output 190 | uint32_t FNN_structure[FNN_3_LAYERS] = {FEATURES_DIM,10,1}; 191 | 192 | // select the activation functions for the dense layer 193 | AIFES_E_activations FNN_activations[FNN_3_LAYERS - 1]; 194 | FNN_activations[0] = AIfES_E_sigmoid; // Sigmoid for hidden (dense) layer 195 | FNN_activations[1] = AIfES_E_sigmoid; // Sigmoid for output (dense) layer 196 | 197 | /* possible activation functions 198 | AIfES_E_relu 199 | AIfES_E_sigmoid 200 | AIfES_E_softmax 201 | AIfES_E_leaky_relu 202 | AIfES_E_elu 203 | AIfES_E_tanh 204 | AIfES_E_softsign 205 | AIfES_E_linear 206 | */ 207 | 208 | // AIfES Express function: calculate the number of weights needed 209 | uint32_t weight_number = AIFES_E_flat_weights_number_fnn_f32(FNN_structure,FNN_3_LAYERS); 210 | 211 | Serial.print(F("Weights: ")); 212 | Serial.println(weight_number); 213 | 214 | // FlatWeights array 215 | //float FlatWeights[weight_number]; 216 | 217 | // Alternative weight array 218 | float *FlatWeights; 219 | FlatWeights = (float *)malloc(sizeof(float)*weight_number); 220 | 221 | 222 | // fill the AIfES Express struct 223 | AIFES_E_model_parameter_fnn_f32 FNN; 224 | FNN.layer_count = FNN_3_LAYERS; 225 | FNN.fnn_structure = FNN_structure; 226 | FNN.fnn_activations = FNN_activations; 227 | FNN.flat_weights = FlatWeights; 228 | 229 | // -------------------------------- create the tensors ---------------------------------- 230 | 231 | uint16_t input_shape[] = {TRAINING_SIZE, (uint16_t)FNN_structure[0]}; // Definition of the input shape 232 | aitensor_t input_tensor = AITENSOR_2D_F32(input_shape, input_data); // Macro for the simple creation of a float32 tensor. Also usable in the normal AIfES version 233 | 234 | uint16_t target_shape[] = {TRAINING_SIZE, (uint16_t)FNN_structure[FNN_3_LAYERS - 1]}; // Definition of the target shape 235 | aitensor_t target_tensor = AITENSOR_2D_F32(target_shape, target_data); // Macro for the simple creation of a float32 tensor. Also usable in the normal AIfES version 236 | 237 | float output_data[TRAINING_SIZE]; // Output data 238 | uint16_t output_shape[] = {TRAINING_SIZE, (uint16_t)FNN_structure[FNN_3_LAYERS - 1]}; // Definition of the output shape 239 | aitensor_t output_tensor = AITENSOR_2D_F32(output_shape, output_data); // Macro for the simple creation of a float32 tensor. Also usable in the normal AIfES version 240 | 241 | // -------------------------------- init weights settings ---------------------------------- 242 | 243 | AIFES_E_init_weights_parameter_fnn_f32 FNN_INIT_WEIGHTS; 244 | FNN_INIT_WEIGHTS.init_weights_method = AIfES_E_init_uniform; 245 | 246 | /* init methods 247 | AIfES_E_init_uniform 248 | AIfES_E_init_glorot_uniform 249 | AIfES_E_init_no_init //If starting weights are already available or if you want to continue training 250 | */ 251 | 252 | FNN_INIT_WEIGHTS.min_init_uniform = -2; // only for the AIfES_E_init_uniform 253 | FNN_INIT_WEIGHTS.max_init_uniform = 2; // only for the AIfES_E_init_uniform 254 | // -------------------------------- set training parameter ---------------------------------- 255 | AIFES_E_training_parameter_fnn_f32 FNN_TRAIN; 256 | FNN_TRAIN.optimizer = AIfES_E_adam; 257 | /* optimizers 258 | AIfES_E_adam 259 | AIfES_E_sgd 260 | */ 261 | FNN_TRAIN.loss = AIfES_E_mse; 262 | /* loss 263 | AIfES_E_mse, 264 | AIfES_E_crossentropy 265 | */ 266 | FNN_TRAIN.learn_rate = 0.1; // Learning rate is for all optimizers 267 | FNN_TRAIN.sgd_momentum = 0.0; // Only interesting for SGD 268 | FNN_TRAIN.batch_size = TRAINING_SIZE; // Here a full batch 269 | FNN_TRAIN.epochs = 1000; // Number of epochs 270 | FNN_TRAIN.epochs_loss_print_interval = PRINT_INTERVAL; // Print the loss every x times 271 | 272 | // Your individual print function 273 | // it must look like this: void YourFunctionName(float x) 274 | FNN_TRAIN.loss_print_function = printLoss; 275 | 276 | //You can enable early stopping, so that learning is automatically stopped when a learning target is reached 277 | FNN_TRAIN.early_stopping = AIfES_E_early_stopping_on; 278 | /* early_stopping 279 | AIfES_E_early_stopping_off, 280 | AIfES_E_early_stopping_on 281 | */ 282 | //Define your target loss 283 | FNN_TRAIN.early_stopping_target_loss = 0.1; 284 | 285 | int8_t error = 0; 286 | 287 | // -------------------------------- do the training ---------------------------------- 288 | // In the training function, the FNN is set up, the weights are initialized and the training is performed. 289 | Serial.println("Training start"); 290 | uint32_t trainingS = micros(); 291 | error = AIFES_E_training_fnn_f32(&input_tensor,&target_tensor,&FNN,&FNN_TRAIN,&FNN_INIT_WEIGHTS,&output_tensor); 292 | Serial.print("Total training time:"); 293 | Serial.println(micros()-trainingS); 294 | Serial.print("Total epochs:"); 295 | Serial.println(global_epoch_counter); 296 | 297 | error_handling_training(error); 298 | 299 | // -------------------------------- do the inference ---------------------------------- 300 | uint16_t input_shape_test[] = {TEST_SIZE, (uint16_t)FNN_structure[0]}; // Definition of the input shape 301 | aitensor_t input_tensor_test = AITENSOR_2D_F32(input_shape_test, (input_data+(TRAINING_SIZE))); // Macro for the simple creation of a float32 tensor. Also usable in the normal AIfES version 302 | 303 | 304 | // AIfES Express function: do the inference 305 | float output_data_test[TEST_SIZE]; // Output data 306 | uint16_t output_shape_test[] = {TEST_SIZE, (uint16_t)FNN_structure[FNN_3_LAYERS - 1]}; // Definition of the output shape 307 | aitensor_t output_tensor_test = AITENSOR_2D_F32(output_shape_test, output_data_test); // Macro for the simple creation of a float32 tensor. Also usable in the normal AIfES version 308 | 309 | error = AIFES_E_inference_fnn_f32(&input_tensor_test,&FNN,&output_tensor_test); 310 | 311 | error_handling_inference(error); 312 | 313 | // -------------------------------- print the results ---------------------------------- 314 | 315 | Serial.println(F("")); 316 | Serial.println(F("Results:")); 317 | Serial.println(F("input 1:\tinput 2:\treal output:\tcalculated output:")); 318 | 319 | 320 | uint32_t errorCounter=0; 321 | for (i = 0; i < TEST_SIZE; i++) { 322 | uint32_t predictionResult = output_data_test[i]>0.5 ? 1 : 0; 323 | if(predictionResult!=target_data[i+TRAINING_SIZE])errorCounter++; 324 | uint32_t k =0; 325 | for(k=0;k"); 332 | Serial.print (target_data[i+TRAINING_SIZE]); 333 | Serial.print("("); 334 | Serial.print(output_data_test[i], 5); 335 | Serial.println(")"); 336 | //Serial.println(((float* ) output_tensor.data)[i], 5); //Alternative print for the tensor 337 | } 338 | Serial.print("Score:"); 339 | Serial.println(((float)((float)TEST_SIZE-(float)errorCounter))/(float)TEST_SIZE); 340 | 341 | Serial.println(F("")); 342 | Serial.println(F("A learning success is not guaranteed")); 343 | Serial.println(F("The weights were initialized randomly")); 344 | Serial.println(F("You can repeat the training with >training<")); 345 | 346 | } 347 | else{ 348 | Serial.println(F("unknown")); 349 | } 350 | } 351 | 352 | } 353 | -------------------------------------------------------------------------------- /examples/bechmarkingOnArduinoUno/platformio.ini: -------------------------------------------------------------------------------- 1 | ; PlatformIO Project Configuration File 2 | ; 3 | ; Build options: build flags, source filter 4 | ; Upload options: custom upload port, speed and extra flags 5 | ; Library options: dependencies, extra library storages 6 | ; Advanced options: extra scripting 7 | ; 8 | ; Please visit documentation for the other options and examples 9 | ; https://docs.platformio.org/page/projectconf.html 10 | 11 | [env:uno] 12 | platform = atmelavr 13 | board = uno 14 | framework = arduino 15 | lib_deps = locoduino/MemoryUsage@^2.21.1 16 | monitor_speed = 115200 -------------------------------------------------------------------------------- /examples/bechmarkingOnArduinoUno/src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // #define DTR_DEBUG_ 3 | #include "TinyDecisionTreeClassifier.h" 4 | 5 | #define NUMBER_OF_FEATURES 5 6 | #define NUMBER_OF_SAMPLES 15 7 | #define MAX_TREE_DEPTH 3 8 | typedef float Treetype; 9 | Treetype X_const[NUMBER_OF_SAMPLES][NUMBER_OF_FEATURES]; 10 | Treetype Y_const[NUMBER_OF_SAMPLES][1]; 11 | Treetype **X; 12 | Treetype **Y; 13 | 14 | void fillBuffersWithRandom(void){ 15 | for(uint32_t i=0;i clf(MAX_TREE_DEPTH,2,TinyDecisionTreeClassifier::GINI); 33 | fillBuffersWithRandom(); 34 | timeBefore = micros(); 35 | clf.fit(X,Y,NUMBER_OF_SAMPLES,NUMBER_OF_FEATURES); 36 | timeAfter = micros(); 37 | benchmarkingTrainingTime+=(timeAfter-timeBefore); 38 | Treetype rslt; 39 | for(uint32_t j=0;j 2 | // #define DTR_DEBUG_ 3 | #include "TinyDecisionTreeClassifier.h" 4 | 5 | #define NUMBER_OF_FEATURES 5 6 | #define NUMBER_OF_SAMPLES 100 7 | #define MAX_TREE_DEPTH 3 8 | typedef float Treetype; 9 | Treetype X_const[NUMBER_OF_SAMPLES][NUMBER_OF_FEATURES]; 10 | Treetype Y_const[NUMBER_OF_SAMPLES][1]; 11 | Treetype **X; 12 | Treetype **Y; 13 | 14 | void fillBuffersWithRandom(void){ 15 | for(uint32_t i=0;i clf(MAX_TREE_DEPTH,2,TinyDecisionTreeClassifier::GINI); 36 | fillBuffersWithRandom(); 37 | timeBefore = micros(); 38 | clf.fit(X,Y,NUMBER_OF_SAMPLES,NUMBER_OF_FEATURES); 39 | timeAfter = micros(); 40 | heapAfter = ESP.getFreeHeap(); 41 | benchmarkingTrainingTime+=(timeAfter-timeBefore); 42 | Treetype rslt; 43 | for(uint32_t j=0;j. 19 | 20 | AIfES-Express XOR training demo 21 | -------------------- 22 | 23 | Versions: 24 | 1.0.0 Initial version 25 | 26 | AIfES-Express is a simplified API for AIfES, which is directly integrated. So you can simply decide which variant you want to use. 27 | 28 | The sketch shows an example of how a neural network is trained from scratch in AIfES-Express using training data. 29 | As in the example "0_AIfES-Express_XOR_Inference", an XOR gate is mapped here using a neural network. 30 | The 4 different states of an XOR gate are fed in as training data here. 31 | The network structure is 2-3(Sigmoid)-1(Sigmoid) and Sigmoid is used as activation function. 32 | In the example, the weights are initialized randomly in a range of values from -2 to +2. The Gotrot initialization was inserted as an alternative and commented out. 33 | For the training the ADAM Optimizer is used, the SGD Optimizer was commented out. 34 | The optimizer runs a batch traininig over a maximum of 1000 epochs. 35 | The early stopping is activated and stops the training when a desired target loss is reached. 36 | The calculation is done in float 32. 37 | 38 | XOR truth table / training data 39 | Input Output 40 | 0 0 0 41 | 0 1 1 42 | 1 0 1 43 | 1 1 0 44 | 45 | Tested on: 46 | Arduino UNO 47 | Arduino Nano 33 BLE Sense 48 | Arduino Portenta H7 49 | 50 | You can find more AIfES tutorials here: 51 | https://create.arduino.cc/projecthub/aifes_team 52 | */ 53 | 54 | #include // include the AIfES libary 55 | 56 | #define DATASETS DATASET_SIZE 57 | #define FNN_3_LAYERS 3 58 | #define PRINT_INTERVAL 1 59 | #include "Iris_flowers.h" 60 | 61 | uint32_t global_epoch_counter = 0; 62 | 63 | // The print function for the loss. It can be customized. 64 | void printLoss(float loss) 65 | { 66 | global_epoch_counter = global_epoch_counter + 1; 67 | // Serial.print(F("Epoch: ")); 68 | // Serial.print(global_epoch_counter * PRINT_INTERVAL); 69 | // Serial.print(F(" / Loss: ")); 70 | // Serial.println(loss,5); 71 | 72 | } 73 | 74 | 75 | void error_handling_training(int8_t error_nr){ 76 | switch(error_nr){ 77 | case 0: 78 | //Serial.println(F("No Error :)")); 79 | break; 80 | case -1: 81 | Serial.println(F("ERROR! Tensor dtype")); 82 | break; 83 | case -2: 84 | Serial.println(F("ERROR! Tensor shape: Data Number")); 85 | break; 86 | case -3: 87 | Serial.println(F("ERROR! Input tensor shape does not correspond to ANN inputs")); 88 | break; 89 | case -4: 90 | Serial.println(F("ERROR! Output tensor shape does not correspond to ANN outputs")); 91 | break; 92 | case -5: 93 | Serial.println(F("ERROR! Use the crossentropy as loss for softmax")); 94 | break; 95 | case -6: 96 | Serial.println(F("ERROR! learn_rate or sgd_momentum negative")); 97 | break; 98 | case -7: 99 | Serial.println(F("ERROR! Init uniform weights min - max wrong")); 100 | break; 101 | case -8: 102 | Serial.println(F("ERROR! batch_size: min = 1 / max = Number of training data")); 103 | break; 104 | case -9: 105 | Serial.println(F("ERROR! Unknown activation function")); 106 | break; 107 | case -10: 108 | Serial.println(F("ERROR! Unknown loss function")); 109 | break; 110 | case -11: 111 | Serial.println(F("ERROR! Unknown init weights method")); 112 | break; 113 | case -12: 114 | Serial.println(F("ERROR! Unknown optimizer")); 115 | break; 116 | case -13: 117 | Serial.println(F("ERROR! Not enough memory")); 118 | break; 119 | default : 120 | Serial.println(F("Unknown error")); 121 | } 122 | } 123 | 124 | void error_handling_inference(int8_t error_nr){ 125 | switch(error_nr){ 126 | case 0: 127 | //Serial.println(F("No Error :)")); 128 | break; 129 | case -1: 130 | Serial.println(F("ERROR! Tensor dtype")); 131 | break; 132 | case -2: 133 | Serial.println(F("ERROR! Tensor shape: Data Number")); 134 | break; 135 | case -3: 136 | Serial.println(F("ERROR! Input tensor shape does not correspond to ANN inputs")); 137 | break; 138 | case -4: 139 | Serial.println(F("ERROR! Output tensor shape does not correspond to ANN outputs")); 140 | break; 141 | case -5: 142 | Serial.println(F("ERROR! Unknown activation function")); 143 | break; 144 | case -6: 145 | Serial.println(F("ERROR! Not enough memory")); 146 | break; 147 | default : 148 | Serial.println(F("Unknown error")); 149 | } 150 | } 151 | 152 | void setup() { 153 | Serial.begin(115200); //115200 baud rate (If necessary, change in the serial monitor) 154 | while (!Serial); 155 | 156 | //IMPORTANT 157 | //AIfES requires random weights for training 158 | //Here the random seed is generated by the noise of an analog pin 159 | srand(analogRead(A5)); 160 | 161 | Serial.println(F("AIfES-Express XOR training demo")); 162 | Serial.println(F("Type >training< to start")); 163 | 164 | } 165 | 166 | void loop() { 167 | 168 | while(1){ 169 | // String str = Serial.readString(); 170 | Serial.println(F("AIfES:")); 171 | Serial.println(F("")); 172 | Serial.println(F("rand test")); 173 | Serial.println(rand()); 174 | 175 | global_epoch_counter = 0; 176 | 177 | uint32_t i; 178 | 179 | // -------------------------------- describe the feed forward neural network ---------------------------------- 180 | // neurons each layer 181 | // FNN_structure[0] = input layer with 2 inputs 182 | // FNN_structure[1] = hidden (dense) layer with 3 neurons 183 | // FNN_structure[2] = output (dense) layer with 1 output 184 | uint32_t FNN_structure[FNN_3_LAYERS] = {FEATURES_DIM,10,1}; 185 | 186 | // select the activation functions for the dense layer 187 | AIFES_E_activations FNN_activations[FNN_3_LAYERS - 1]; 188 | FNN_activations[0] = AIfES_E_sigmoid; // Sigmoid for hidden (dense) layer 189 | FNN_activations[1] = AIfES_E_sigmoid; // Sigmoid for output (dense) layer 190 | 191 | /* possible activation functions 192 | AIfES_E_relu 193 | AIfES_E_sigmoid 194 | AIfES_E_softmax 195 | AIfES_E_leaky_relu 196 | AIfES_E_elu 197 | AIfES_E_tanh 198 | AIfES_E_softsign 199 | AIfES_E_linear 200 | */ 201 | 202 | // AIfES Express function: calculate the number of weights needed 203 | uint32_t weight_number = AIFES_E_flat_weights_number_fnn_f32(FNN_structure,FNN_3_LAYERS); 204 | 205 | Serial.print(F("Weights: ")); 206 | Serial.println(weight_number); 207 | 208 | // FlatWeights array 209 | //float FlatWeights[weight_number]; 210 | 211 | // Alternative weight array 212 | float *FlatWeights; 213 | FlatWeights = (float *)malloc(sizeof(float)*weight_number); 214 | 215 | 216 | // fill the AIfES Express struct 217 | AIFES_E_model_parameter_fnn_f32 FNN; 218 | FNN.layer_count = FNN_3_LAYERS; 219 | FNN.fnn_structure = FNN_structure; 220 | FNN.fnn_activations = FNN_activations; 221 | FNN.flat_weights = FlatWeights; 222 | 223 | // -------------------------------- create the tensors ---------------------------------- 224 | 225 | uint16_t input_shape[] = {DATASETS, (uint16_t)FNN_structure[0]}; // Definition of the input shape 226 | aitensor_t input_tensor = AITENSOR_2D_F32(input_shape, input_data); // Macro for the simple creation of a float32 tensor. Also usable in the normal AIfES version 227 | 228 | uint16_t target_shape[] = {DATASETS, (uint16_t)FNN_structure[FNN_3_LAYERS - 1]}; // Definition of the target shape 229 | aitensor_t target_tensor = AITENSOR_2D_F32(target_shape, target_data); // Macro for the simple creation of a float32 tensor. Also usable in the normal AIfES version 230 | 231 | float output_data[DATASETS]; // Output data 232 | uint16_t output_shape[] = {DATASETS, (uint16_t)FNN_structure[FNN_3_LAYERS - 1]}; // Definition of the output shape 233 | aitensor_t output_tensor = AITENSOR_2D_F32(output_shape, output_data); // Macro for the simple creation of a float32 tensor. Also usable in the normal AIfES version 234 | 235 | // -------------------------------- init weights settings ---------------------------------- 236 | 237 | AIFES_E_init_weights_parameter_fnn_f32 FNN_INIT_WEIGHTS; 238 | FNN_INIT_WEIGHTS.init_weights_method = AIfES_E_init_uniform; 239 | 240 | /* init methods 241 | AIfES_E_init_uniform 242 | AIfES_E_init_glorot_uniform 243 | AIfES_E_init_no_init //If starting weights are already available or if you want to continue training 244 | */ 245 | 246 | FNN_INIT_WEIGHTS.min_init_uniform = -2; // only for the AIfES_E_init_uniform 247 | FNN_INIT_WEIGHTS.max_init_uniform = 2; // only for the AIfES_E_init_uniform 248 | // -------------------------------- set training parameter ---------------------------------- 249 | AIFES_E_training_parameter_fnn_f32 FNN_TRAIN; 250 | FNN_TRAIN.optimizer = AIfES_E_adam; 251 | /* optimizers 252 | AIfES_E_adam 253 | AIfES_E_sgd 254 | */ 255 | FNN_TRAIN.loss = AIfES_E_mse; 256 | /* loss 257 | AIfES_E_mse, 258 | AIfES_E_crossentropy 259 | */ 260 | FNN_TRAIN.learn_rate = 0.1; // Learning rate is for all optimizers 261 | FNN_TRAIN.sgd_momentum = 0.0; // Only interesting for SGD 262 | FNN_TRAIN.batch_size = DATASETS; // Here a full batch 263 | FNN_TRAIN.epochs = 1000; // Number of epochs 264 | FNN_TRAIN.epochs_loss_print_interval = PRINT_INTERVAL; // Print the loss every x times 265 | 266 | // Your individual print function 267 | // it must look like this: void YourFunctionName(float x) 268 | FNN_TRAIN.loss_print_function = printLoss; 269 | 270 | //You can enable early stopping, so that learning is automatically stopped when a learning target is reached 271 | FNN_TRAIN.early_stopping = AIfES_E_early_stopping_on; 272 | /* early_stopping 273 | AIfES_E_early_stopping_off, 274 | AIfES_E_early_stopping_on 275 | */ 276 | //Define your target loss 277 | FNN_TRAIN.early_stopping_target_loss = 0.004; 278 | 279 | int8_t error = 0; 280 | 281 | // -------------------------------- do the training ---------------------------------- 282 | // In the training function, the FNN is set up, the weights are initialized and the training is performed. 283 | Serial.println("Training start"); 284 | uint32_t trainingS = micros(); 285 | error = AIFES_E_training_fnn_f32(&input_tensor,&target_tensor,&FNN,&FNN_TRAIN,&FNN_INIT_WEIGHTS,&output_tensor); 286 | Serial.print("Total training time:"); 287 | Serial.println(micros()-trainingS); 288 | Serial.print("Total epochs:"); 289 | Serial.println(global_epoch_counter); 290 | 291 | error_handling_training(error); 292 | 293 | // -------------------------------- do the inference ---------------------------------- 294 | // AIfES Express function: do the inference 295 | error = AIFES_E_inference_fnn_f32(&input_tensor,&FNN,&output_tensor); 296 | 297 | error_handling_inference(error); 298 | 299 | // -------------------------------- print the results ---------------------------------- 300 | 301 | Serial.println(F("")); 302 | Serial.println(F("Results:")); 303 | Serial.println(F("input 1:\tinput 2:\treal output:\tcalculated output:")); 304 | 305 | 306 | for (i = 0; i < DATASET_SIZE; i++) { 307 | uint32_t k =0; 308 | for(k=0;k"); 315 | Serial.print (target_data[i]); 316 | Serial.print("("); 317 | Serial.print(output_data[i], 5); 318 | Serial.println(")"); 319 | //Serial.println(((float* ) output_tensor.data)[i], 5); //Alternative print for the tensor 320 | } 321 | 322 | Serial.println(F("")); 323 | Serial.println(F("A learning success is not guaranteed")); 324 | Serial.println(F("The weights were initialized randomly")); 325 | Serial.println(F("You can repeat the training with >training<")); 326 | delay(10000); 327 | } 328 | 329 | } 330 | -------------------------------------------------------------------------------- /examples/bencharkIrisWithAIEFSOnNrf52/src/Iris_flowers.h: -------------------------------------------------------------------------------- 1 | // Other full TinyML datasets available at: https://github.com/bharathsudharsan/ML-MCU/tree/master/TinyML%20Datasets 2 | #pragma once 3 | #define FEATURES_DIM 4 4 | #define DATASET_SIZE 100 5 | 6 | float input_data[DATASET_SIZE][FEATURES_DIM] = { 7 | { 6.3 , 2.5 , 4.9 , 1.5 }, 8 | { 5.0 , 3.4 , 1.5 , 0.2 }, 9 | { 5.4 , 3.7 , 1.5 , 0.2 }, 10 | { 5.7 , 4.4 , 1.5 , 0.4 }, 11 | { 6.6 , 3.0 , 4.4 , 1.4 }, 12 | { 5.6 , 2.5 , 3.9 , 1.1 }, 13 | { 4.3 , 3.0 , 1.1 , 0.1 }, 14 | { 4.9 , 3.0 , 1.4 , 0.2 }, 15 | { 6.3 , 3.3 , 4.7 , 1.6 }, 16 | { 5.5 , 2.5 , 4.0 , 1.3 }, 17 | { 4.8 , 3.4 , 1.6 , 0.2 }, 18 | { 5.2 , 3.5 , 1.5 , 0.2 }, 19 | { 7.0 , 3.2 , 4.7 , 1.4 }, 20 | { 5.6 , 3.0 , 4.5 , 1.5 }, 21 | { 4.4 , 2.9 , 1.4 , 0.2 }, 22 | { 6.0 , 2.7 , 5.1 , 1.6 }, 23 | { 6.0 , 2.9 , 4.5 , 1.5 }, 24 | { 6.1 , 2.8 , 4.0 , 1.3 }, 25 | { 4.4 , 3.2 , 1.3 , 0.2 }, 26 | { 4.8 , 3.4 , 1.9 , 0.2 }, 27 | { 5.1 , 3.5 , 1.4 , 0.2 }, 28 | { 5.1 , 3.8 , 1.5 , 0.3 }, 29 | { 4.6 , 3.6 , 1.0 , 0.2 }, 30 | { 5.0 , 3.4 , 1.6 , 0.4 }, 31 | { 5.0 , 3.0 , 1.6 , 0.2 }, 32 | { 6.8 , 2.8 , 4.8 , 1.4 }, 33 | { 4.5 , 2.3 , 1.3 , 0.3 }, 34 | { 5.0 , 2.0 , 3.5 , 1.0 }, 35 | { 6.7 , 3.0 , 5.0 , 1.7 }, 36 | { 5.8 , 2.7 , 3.9 , 1.2 }, 37 | { 6.0 , 2.2 , 4.0 , 1.0 }, 38 | { 4.9 , 3.1 , 1.5 , 0.2 }, 39 | { 6.0 , 3.4 , 4.5 , 1.6 }, 40 | { 4.6 , 3.1 , 1.5 , 0.2 }, 41 | { 4.7 , 3.2 , 1.3 , 0.2 }, 42 | { 4.8 , 3.0 , 1.4 , 0.1 }, 43 | { 6.1 , 2.9 , 4.7 , 1.4 }, 44 | { 6.1 , 2.8 , 4.7 , 1.2 }, 45 | { 5.4 , 3.4 , 1.5 , 0.4 }, 46 | { 5.1 , 3.8 , 1.9 , 0.4 }, 47 | { 6.7 , 3.1 , 4.4 , 1.4 }, 48 | { 4.8 , 3.0 , 1.4 , 0.3 }, 49 | { 5.7 , 2.8 , 4.5 , 1.3 }, 50 | { 5.1 , 3.5 , 1.4 , 0.3 }, 51 | { 5.1 , 3.4 , 1.5 , 0.2 }, 52 | { 5.2 , 2.7 , 3.9 , 1.4 }, 53 | { 5.7 , 2.8 , 4.1 , 1.3 }, 54 | { 5.0 , 3.5 , 1.6 , 0.6 }, 55 | { 4.9 , 3.6 , 1.4 , 0.1 }, 56 | { 6.9 , 3.1 , 4.9 , 1.5 }, 57 | { 5.8 , 2.7 , 4.1 , 1.0 }, 58 | { 5.2 , 4.1 , 1.5 , 0.1 }, 59 | { 4.8 , 3.1 , 1.6 , 0.2 }, 60 | { 5.1 , 3.8 , 1.6 , 0.2 }, 61 | { 5.5 , 2.4 , 3.8 , 1.1 }, 62 | { 5.5 , 4.2 , 1.4 , 0.2 }, 63 | { 5.0 , 3.5 , 1.3 , 0.3 }, 64 | { 4.7 , 3.2 , 1.6 , 0.2 }, 65 | { 6.2 , 2.2 , 4.5 , 1.5 }, 66 | { 6.2 , 2.9 , 4.3 , 1.3 }, 67 | { 6.6 , 2.9 , 4.6 , 1.3 }, 68 | { 5.7 , 3.0 , 4.2 , 1.2 }, 69 | { 5.7 , 2.9 , 4.2 , 1.3 }, 70 | { 6.5 , 2.8 , 4.6 , 1.5 }, 71 | { 5.8 , 4.0 , 1.2 , 0.2 }, 72 | { 5.5 , 2.6 , 4.4 , 1.2 }, 73 | { 4.6 , 3.2 , 1.4 , 0.2 }, 74 | { 5.7 , 3.8 , 1.7 , 0.3 }, 75 | { 5.2 , 3.4 , 1.4 , 0.2 }, 76 | { 5.6 , 3.0 , 4.1 , 1.3 }, 77 | { 5.3 , 3.7 , 1.5 , 0.2 }, 78 | { 5.1 , 2.5 , 3.0 , 1.1 }, 79 | { 5.6 , 2.7 , 4.2 , 1.3 }, 80 | { 5.5 , 2.4 , 3.7 , 1.0 }, 81 | { 5.4 , 3.4 , 1.7 , 0.2 }, 82 | { 5.0 , 2.3 , 3.3 , 1.0 }, 83 | { 6.1 , 3.0 , 4.6 , 1.4 }, 84 | { 5.8 , 2.6 , 4.0 , 1.2 }, 85 | { 5.0 , 3.3 , 1.4 , 0.2 }, 86 | { 5.4 , 3.0 , 4.5 , 1.5 }, 87 | { 4.9 , 2.4 , 3.3 , 1.0 }, 88 | { 5.1 , 3.3 , 1.7 , 0.5 }, 89 | { 4.9 , 3.1 , 1.5 , 0.1 }, 90 | { 4.6 , 3.4 , 1.4 , 0.3 }, 91 | { 5.5 , 2.3 , 4.0 , 1.3 }, 92 | { 5.0 , 3.2 , 1.2 , 0.2 }, 93 | { 5.9 , 3.0 , 4.2 , 1.5 }, 94 | { 5.9 , 3.2 , 4.8 , 1.8 }, 95 | { 5.5 , 3.5 , 1.3 , 0.2 }, 96 | { 5.1 , 3.7 , 1.5 , 0.4 }, 97 | { 5.7 , 2.6 , 3.5 , 1.0 }, 98 | { 6.3 , 2.3 , 4.4 , 1.3 }, 99 | { 4.4 , 3.0 , 1.3 , 0.2 }, 100 | { 5.6 , 2.9 , 3.6 , 1.3 }, 101 | { 6.4 , 3.2 , 4.5 , 1.5 }, 102 | { 5.4 , 3.9 , 1.3 , 0.4 }, 103 | { 6.7 , 3.1 , 4.7 , 1.5 }, 104 | { 5.4 , 3.9 , 1.7 , 0.4 }, 105 | { 6.4 , 2.9 , 4.3 , 1.3 }, 106 | { 5.0 , 3.6 , 1.4 , 0.2 }, 107 | }; 108 | float target_data[DATASET_SIZE] = { 1 , 0 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 1 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 1 , 1 , 1 , 0 , 1 , 0 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 0 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 0 , 1 , 0 , 0 , 0 , 1 , 0 , 1 , 1 , 1 , 0 , 1 , 1 , 1 , 0 , 1 , 1 , 0 , 0 , 0 , 1 , 0 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 1 , 1 , 0 , 1 , 0 , 1 , 0 }; 109 | -------------------------------------------------------------------------------- /examples/bencharkIrisWithAIEFSOnNrf52/src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // #define DTR_DEBUG_ 3 | #include "TinyDecisionTreeClassifier.h" 4 | 5 | typedef float Treetype; 6 | #include "Iris_flowers.h" 7 | 8 | #define MAX_TREE_DEPTH 4 9 | #define MIN_SAMPLES_SPLIT 10 10 | 11 | // Treetype X_const[DATASET_SIZE][FEATURES_DIM]; 12 | Treetype Y_const[DATASET_SIZE][1]; 13 | 14 | Treetype **X; 15 | Treetype **Y; 16 | 17 | #define BENCHMARK_AVERAGING 10 18 | void benchmark(void){ 19 | uint32_t timeBefore; 20 | uint32_t timeAfter; 21 | uint64_t benchmarkingTrainingTime = 0; 22 | uint64_t benchmarkingPredictionTime = 0; 23 | Serial.println("Bechmarking start"); 24 | for(uint32_t i=0;i clf(MAX_TREE_DEPTH,MIN_SAMPLES_SPLIT,TinyDecisionTreeClassifier::INFO_GAIN); 26 | timeBefore = micros(); 27 | clf.fit(X,Y,DATASET_SIZE,FEATURES_DIM); 28 | Serial.println("Tree before pruning: "); 29 | clf.plot(); 30 | while(clf.prune(X,Y,DATASET_SIZE)); 31 | timeAfter = micros(); 32 | benchmarkingTrainingTime+=(timeAfter-timeBefore); 33 | Treetype rslt; 34 | for(uint32_t j=0;j. 19 | 20 | AIfES-Express XOR training demo 21 | -------------------- 22 | 23 | Versions: 24 | 1.0.0 Initial version 25 | 26 | AIfES-Express is a simplified API for AIfES, which is directly integrated. So you can simply decide which variant you want to use. 27 | 28 | The sketch shows an example of how a neural network is trained from scratch in AIfES-Express using training data. 29 | As in the example "0_AIfES-Express_XOR_Inference", an XOR gate is mapped here using a neural network. 30 | The 4 different states of an XOR gate are fed in as training data here. 31 | The network structure is 2-3(Sigmoid)-1(Sigmoid) and Sigmoid is used as activation function. 32 | In the example, the weights are initialized randomly in a range of values from -2 to +2. The Gotrot initialization was inserted as an alternative and commented out. 33 | For the training the ADAM Optimizer is used, the SGD Optimizer was commented out. 34 | The optimizer runs a batch traininig over a maximum of 1000 epochs. 35 | The early stopping is activated and stops the training when a desired target loss is reached. 36 | The calculation is done in float 32. 37 | 38 | XOR truth table / training data 39 | Input Output 40 | 0 0 0 41 | 0 1 1 42 | 1 0 1 43 | 1 1 0 44 | 45 | Tested on: 46 | Arduino UNO 47 | Arduino Nano 33 BLE Sense 48 | Arduino Portenta H7 49 | 50 | You can find more AIfES tutorials here: 51 | https://create.arduino.cc/projecthub/aifes_team 52 | */ 53 | 54 | #include // include the AIfES libary 55 | 56 | #define TEST_RATIO 0.33 57 | #define TEST_SIZE (uint32_t)(DATASET_SIZE*TEST_RATIO) 58 | #define TRAINING_SIZE (uint32_t)(DATASET_SIZE-TEST_SIZE) 59 | 60 | #define FNN_3_LAYERS 3 61 | #define PRINT_INTERVAL 10 62 | #include "Breast_cancer.h" 63 | 64 | uint32_t global_epoch_counter = 0; 65 | 66 | // The print function for the loss. It can be customized. 67 | void printLoss(float loss) 68 | { 69 | global_epoch_counter = global_epoch_counter + 1; 70 | Serial.print(F("Epoch: ")); 71 | Serial.print(global_epoch_counter * PRINT_INTERVAL); 72 | Serial.print(F(" / Loss: ")); 73 | Serial.println(loss,5); 74 | 75 | } 76 | 77 | 78 | void error_handling_training(int8_t error_nr){ 79 | switch(error_nr){ 80 | case 0: 81 | //Serial.println(F("No Error :)")); 82 | break; 83 | case -1: 84 | Serial.println(F("ERROR! Tensor dtype")); 85 | break; 86 | case -2: 87 | Serial.println(F("ERROR! Tensor shape: Data Number")); 88 | break; 89 | case -3: 90 | Serial.println(F("ERROR! Input tensor shape does not correspond to ANN inputs")); 91 | break; 92 | case -4: 93 | Serial.println(F("ERROR! Output tensor shape does not correspond to ANN outputs")); 94 | break; 95 | case -5: 96 | Serial.println(F("ERROR! Use the crossentropy as loss for softmax")); 97 | break; 98 | case -6: 99 | Serial.println(F("ERROR! learn_rate or sgd_momentum negative")); 100 | break; 101 | case -7: 102 | Serial.println(F("ERROR! Init uniform weights min - max wrong")); 103 | break; 104 | case -8: 105 | Serial.println(F("ERROR! batch_size: min = 1 / max = Number of training data")); 106 | break; 107 | case -9: 108 | Serial.println(F("ERROR! Unknown activation function")); 109 | break; 110 | case -10: 111 | Serial.println(F("ERROR! Unknown loss function")); 112 | break; 113 | case -11: 114 | Serial.println(F("ERROR! Unknown init weights method")); 115 | break; 116 | case -12: 117 | Serial.println(F("ERROR! Unknown optimizer")); 118 | break; 119 | case -13: 120 | Serial.println(F("ERROR! Not enough memory")); 121 | break; 122 | default : 123 | Serial.println(F("Unknown error")); 124 | } 125 | } 126 | 127 | void error_handling_inference(int8_t error_nr){ 128 | switch(error_nr){ 129 | case 0: 130 | //Serial.println(F("No Error :)")); 131 | break; 132 | case -1: 133 | Serial.println(F("ERROR! Tensor dtype")); 134 | break; 135 | case -2: 136 | Serial.println(F("ERROR! Tensor shape: Data Number")); 137 | break; 138 | case -3: 139 | Serial.println(F("ERROR! Input tensor shape does not correspond to ANN inputs")); 140 | break; 141 | case -4: 142 | Serial.println(F("ERROR! Output tensor shape does not correspond to ANN outputs")); 143 | break; 144 | case -5: 145 | Serial.println(F("ERROR! Unknown activation function")); 146 | break; 147 | case -6: 148 | Serial.println(F("ERROR! Not enough memory")); 149 | break; 150 | default : 151 | Serial.println(F("Unknown error")); 152 | } 153 | } 154 | 155 | void setup() { 156 | Serial.begin(115200); //115200 baud rate (If necessary, change in the serial monitor) 157 | while (!Serial); 158 | 159 | //IMPORTANT 160 | //AIfES requires random weights for training 161 | //Here the random seed is generated by the noise of an analog pin 162 | srand(analogRead(A5)); 163 | 164 | Serial.println(F("AIfES-Express XOR training demo")); 165 | Serial.println(F("Type >training< to start")); 166 | 167 | } 168 | 169 | void loop() { 170 | 171 | while(Serial.available() > 0 ){ 172 | String str = Serial.readString(); 173 | if(str.indexOf("training") > -1) //Keyword "training" 174 | { 175 | 176 | Serial.println(F("AIfES:")); 177 | Serial.println(F("")); 178 | Serial.println(F("rand test")); 179 | Serial.println(rand()); 180 | 181 | global_epoch_counter = 0; 182 | 183 | uint32_t i; 184 | 185 | // -------------------------------- describe the feed forward neural network ---------------------------------- 186 | // neurons each layer 187 | // FNN_structure[0] = input layer with 2 inputs 188 | // FNN_structure[1] = hidden (dense) layer with 3 neurons 189 | // FNN_structure[2] = output (dense) layer with 1 output 190 | uint32_t FNN_structure[FNN_3_LAYERS] = {FEATURES_DIM,10,1}; 191 | 192 | // select the activation functions for the dense layer 193 | AIFES_E_activations FNN_activations[FNN_3_LAYERS - 1]; 194 | FNN_activations[0] = AIfES_E_sigmoid; // Sigmoid for hidden (dense) layer 195 | FNN_activations[1] = AIfES_E_sigmoid; // Sigmoid for output (dense) layer 196 | 197 | /* possible activation functions 198 | AIfES_E_relu 199 | AIfES_E_sigmoid 200 | AIfES_E_softmax 201 | AIfES_E_leaky_relu 202 | AIfES_E_elu 203 | AIfES_E_tanh 204 | AIfES_E_softsign 205 | AIfES_E_linear 206 | */ 207 | 208 | // AIfES Express function: calculate the number of weights needed 209 | uint32_t weight_number = AIFES_E_flat_weights_number_fnn_f32(FNN_structure,FNN_3_LAYERS); 210 | 211 | Serial.print(F("Weights: ")); 212 | Serial.println(weight_number); 213 | 214 | // FlatWeights array 215 | //float FlatWeights[weight_number]; 216 | 217 | // Alternative weight array 218 | float *FlatWeights; 219 | FlatWeights = (float *)malloc(sizeof(float)*weight_number); 220 | 221 | 222 | // fill the AIfES Express struct 223 | AIFES_E_model_parameter_fnn_f32 FNN; 224 | FNN.layer_count = FNN_3_LAYERS; 225 | FNN.fnn_structure = FNN_structure; 226 | FNN.fnn_activations = FNN_activations; 227 | FNN.flat_weights = FlatWeights; 228 | 229 | // -------------------------------- create the tensors ---------------------------------- 230 | 231 | uint16_t input_shape[] = {TRAINING_SIZE, (uint16_t)FNN_structure[0]}; // Definition of the input shape 232 | aitensor_t input_tensor = AITENSOR_2D_F32(input_shape, input_data); // Macro for the simple creation of a float32 tensor. Also usable in the normal AIfES version 233 | 234 | uint16_t target_shape[] = {TRAINING_SIZE, (uint16_t)FNN_structure[FNN_3_LAYERS - 1]}; // Definition of the target shape 235 | aitensor_t target_tensor = AITENSOR_2D_F32(target_shape, target_data); // Macro for the simple creation of a float32 tensor. Also usable in the normal AIfES version 236 | 237 | float output_data[TRAINING_SIZE]; // Output data 238 | uint16_t output_shape[] = {TRAINING_SIZE, (uint16_t)FNN_structure[FNN_3_LAYERS - 1]}; // Definition of the output shape 239 | aitensor_t output_tensor = AITENSOR_2D_F32(output_shape, output_data); // Macro for the simple creation of a float32 tensor. Also usable in the normal AIfES version 240 | 241 | // -------------------------------- init weights settings ---------------------------------- 242 | 243 | AIFES_E_init_weights_parameter_fnn_f32 FNN_INIT_WEIGHTS; 244 | FNN_INIT_WEIGHTS.init_weights_method = AIfES_E_init_uniform; 245 | 246 | /* init methods 247 | AIfES_E_init_uniform 248 | AIfES_E_init_glorot_uniform 249 | AIfES_E_init_no_init //If starting weights are already available or if you want to continue training 250 | */ 251 | 252 | FNN_INIT_WEIGHTS.min_init_uniform = -2; // only for the AIfES_E_init_uniform 253 | FNN_INIT_WEIGHTS.max_init_uniform = 2; // only for the AIfES_E_init_uniform 254 | // -------------------------------- set training parameter ---------------------------------- 255 | AIFES_E_training_parameter_fnn_f32 FNN_TRAIN; 256 | FNN_TRAIN.optimizer = AIfES_E_adam; 257 | /* optimizers 258 | AIfES_E_adam 259 | AIfES_E_sgd 260 | */ 261 | FNN_TRAIN.loss = AIfES_E_mse; 262 | /* loss 263 | AIfES_E_mse, 264 | AIfES_E_crossentropy 265 | */ 266 | FNN_TRAIN.learn_rate = 0.1; // Learning rate is for all optimizers 267 | FNN_TRAIN.sgd_momentum = 0.0; // Only interesting for SGD 268 | FNN_TRAIN.batch_size = TRAINING_SIZE; // Here a full batch 269 | FNN_TRAIN.epochs = 1000; // Number of epochs 270 | FNN_TRAIN.epochs_loss_print_interval = PRINT_INTERVAL; // Print the loss every x times 271 | 272 | // Your individual print function 273 | // it must look like this: void YourFunctionName(float x) 274 | FNN_TRAIN.loss_print_function = printLoss; 275 | 276 | //You can enable early stopping, so that learning is automatically stopped when a learning target is reached 277 | FNN_TRAIN.early_stopping = AIfES_E_early_stopping_on; 278 | /* early_stopping 279 | AIfES_E_early_stopping_off, 280 | AIfES_E_early_stopping_on 281 | */ 282 | //Define your target loss 283 | FNN_TRAIN.early_stopping_target_loss = 0.04; 284 | 285 | int8_t error = 0; 286 | 287 | // -------------------------------- do the training ---------------------------------- 288 | // In the training function, the FNN is set up, the weights are initialized and the training is performed. 289 | Serial.println("Training start"); 290 | uint32_t trainingS = micros(); 291 | error = AIFES_E_training_fnn_f32(&input_tensor,&target_tensor,&FNN,&FNN_TRAIN,&FNN_INIT_WEIGHTS,&output_tensor); 292 | Serial.print("Total training time:"); 293 | Serial.println(micros()-trainingS); 294 | Serial.print("Total epochs:"); 295 | Serial.println(global_epoch_counter); 296 | 297 | error_handling_training(error); 298 | 299 | // -------------------------------- do the inference ---------------------------------- 300 | uint16_t input_shape_test[] = {TEST_SIZE, (uint16_t)FNN_structure[0]}; // Definition of the input shape 301 | aitensor_t input_tensor_test = AITENSOR_2D_F32(input_shape_test, (input_data+(TRAINING_SIZE))); // Macro for the simple creation of a float32 tensor. Also usable in the normal AIfES version 302 | 303 | 304 | // AIfES Express function: do the inference 305 | float output_data_test[TEST_SIZE]; // Output data 306 | uint16_t output_shape_test[] = {TEST_SIZE, (uint16_t)FNN_structure[FNN_3_LAYERS - 1]}; // Definition of the output shape 307 | aitensor_t output_tensor_test = AITENSOR_2D_F32(output_shape_test, output_data_test); // Macro for the simple creation of a float32 tensor. Also usable in the normal AIfES version 308 | 309 | error = AIFES_E_inference_fnn_f32(&input_tensor_test,&FNN,&output_tensor_test); 310 | 311 | error_handling_inference(error); 312 | 313 | // -------------------------------- print the results ---------------------------------- 314 | 315 | Serial.println(F("")); 316 | Serial.println(F("Results:")); 317 | Serial.println(F("input 1:\tinput 2:\treal output:\tcalculated output:")); 318 | 319 | 320 | uint32_t errorCounter=0; 321 | for (i = 0; i < TEST_SIZE; i++) { 322 | uint32_t predictionResult = output_data_test[i]>0.5 ? 1 : 0; 323 | if(predictionResult!=target_data[i+TRAINING_SIZE])errorCounter++; 324 | uint32_t k =0; 325 | for(k=0;k"); 332 | Serial.print (target_data[i+TRAINING_SIZE]); 333 | Serial.print("("); 334 | Serial.print(output_data_test[i], 5); 335 | Serial.println(")"); 336 | //Serial.println(((float* ) output_tensor.data)[i], 5); //Alternative print for the tensor 337 | } 338 | Serial.print("Score:"); 339 | Serial.println(((float)((float)TEST_SIZE-(float)errorCounter))/(float)TEST_SIZE); 340 | 341 | Serial.println(F("")); 342 | Serial.println(F("A learning success is not guaranteed")); 343 | Serial.println(F("The weights were initialized randomly")); 344 | Serial.println(F("You can repeat the training with >training<")); 345 | 346 | } 347 | else{ 348 | Serial.println(F("unknown")); 349 | } 350 | } 351 | 352 | } 353 | -------------------------------------------------------------------------------- /examples/benchmarkBreastCancerWithAIEFS/src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // #define DTR_DEBUG_ 3 | #include "TinyDecisionTreeClassifier.h" 4 | 5 | typedef float Treetype; 6 | #include "Breast_cancer.h" 7 | 8 | #define MAX_TREE_DEPTH 4 9 | #define MIN_SAMPLES_SPLIT 10 10 | #define TEST_RATIO 0.33 11 | #define TEST_SIZE (uint32_t)(DATASET_SIZE*TEST_RATIO) 12 | #define TRAIN_SIZE DATASET_SIZE-TEST_SIZE 13 | 14 | // Treetype X_const[DATASET_SIZE][FEATURES_DIM]; 15 | Treetype Y_const[DATASET_SIZE][1]; 16 | 17 | Treetype **X; 18 | Treetype **Y; 19 | 20 | #define BENCHMARK_AVERAGING 5 21 | void benchmark(void){ 22 | uint32_t timeBefore; 23 | uint32_t timeAfter; 24 | uint64_t benchmarkingTrainingTime = 0; 25 | uint64_t benchmarkingPredictionTime = 0; 26 | Serial.println("Bechmarking start"); 27 | for(uint32_t i=0;i clf(MAX_TREE_DEPTH,MIN_SAMPLES_SPLIT,TinyDecisionTreeClassifier::GINI); 29 | timeBefore = micros(); 30 | clf.fit(X,Y,TRAIN_SIZE,FEATURES_DIM); 31 | // Serial.println("Tree before pruning: "); 32 | // clf.plot(); 33 | while(clf.prune(X,Y,TRAIN_SIZE)); 34 | timeAfter = micros(); 35 | benchmarkingTrainingTime+=(timeAfter-timeBefore); 36 | Treetype rslt; 37 | for(uint32_t j=0;j 2 | // #define __DTR_DEBUG_ 3 | #include "TinyDecisionTreeClassifier.h" 4 | 5 | #define NUMBER_OF_FEATURES 5 6 | #define NUMBER_OF_SAMPLES 800 7 | #define MAX_TREE_DEPTH 3 8 | typedef float Treetype; 9 | Treetype X_const[NUMBER_OF_SAMPLES][NUMBER_OF_FEATURES]; 10 | Treetype Y_const[NUMBER_OF_SAMPLES][1]; 11 | Treetype **X; 12 | Treetype **Y; 13 | 14 | void fillBuffersWithRandom(void){ 15 | for(uint32_t i=0;i clf(MAX_TREE_DEPTH,2,TinyDecisionTreeClassifier::GINI); 32 | fillBuffersWithRandom(); 33 | timeBefore = micros(); 34 | clf.fit(X,Y,NUMBER_OF_SAMPLES,NUMBER_OF_FEATURES); 35 | timeAfter = micros(); 36 | benchmarkingTrainingTime+=(timeAfter-timeBefore); 37 | Treetype rslt; 38 | for(uint32_t j=0;j 3 | // #define __DTR_DEBUG_ 4 | #include "TinyDecisionTreeClassifier.h" 5 | #include 6 | #include 7 | 8 | MPU6050 mpu6050(Wire); 9 | #define WINDOW_SIZE_SECONDS 2 10 | #define SAMPLING_FREQENCY 20 11 | #define WINDOW_BUFFER_SIZE WINDOW_SIZE_SECONDS*SAMPLING_FREQENCY 12 | 13 | #define TRREE_TRAINING_TIME_SECONDS 60 14 | #define TRREE_TEST_TIME_SECONDS (uint32_t)(TRREE_TRAINING_TIME_SECONDS/2) 15 | #define TREE_NUMBER_OF_CLASSES 2 16 | #define TREE_NUMBER_OF_FEATURES 9 17 | #define TREE_NUMBER_OF_TRAINING_SAMPLES (uint32_t(TREE_NUMBER_OF_CLASSES*TRREE_TRAINING_TIME_SECONDS/WINDOW_SIZE_SECONDS))+1 18 | #define TREE_NUMBER_OF_TEST_SAMPLES (uint32_t(TREE_NUMBER_OF_CLASSES*TRREE_TEST_TIME_SECONDS/WINDOW_SIZE_SECONDS))+1 19 | 20 | #define MAX_TREE_DEPTH 4 21 | typedef float Treetype; 22 | Treetype X_train[TREE_NUMBER_OF_TRAINING_SAMPLES][TREE_NUMBER_OF_FEATURES]; 23 | Treetype Y_train[TREE_NUMBER_OF_TRAINING_SAMPLES][1]; 24 | 25 | Treetype X_test[TREE_NUMBER_OF_TEST_SAMPLES][TREE_NUMBER_OF_FEATURES]; 26 | Treetype Y_test[TREE_NUMBER_OF_TEST_SAMPLES][1]; 27 | 28 | Treetype **X; 29 | Treetype **Y; 30 | Treetype **X_t; 31 | Treetype **Y_t; 32 | 33 | #define STATUS_LED_PIN 2 //P0.13 34 | 35 | void setup() { 36 | 37 | Serial.begin(115200); 38 | Serial.println("Here we go!"); 39 | X = new Treetype *[TREE_NUMBER_OF_TRAINING_SAMPLES]; 40 | Y = new Treetype *[TREE_NUMBER_OF_TRAINING_SAMPLES]; 41 | for(uint32_t i=0;i(6)/((k+1)*(k+1))){ 102 | digitalWrite(STATUS_LED_PIN,ledstate); 103 | ledstate=!ledstate; 104 | blinkCtr=0; 105 | } 106 | } 107 | float mean; 108 | float variance; 109 | float avgDif; 110 | computeFeatures(aXbuffer,&mean,&variance,&avgDif); 111 | X[i*(k+1)][0]=mean; 112 | X[i*(k+1)][1]=avgDif; 113 | X[i*(k+1)][2]=variance; 114 | 115 | computeFeatures(aYbuffer,&mean,&variance,&avgDif); 116 | X[i*(k+1)][3]=mean; 117 | X[i*(k+1)][4]=avgDif; 118 | X[i*(k+1)][5]=variance; 119 | 120 | computeFeatures(aZbuffer,&mean,&variance,&avgDif); 121 | X[i*(k+1)][6]=mean; 122 | X[i*(k+1)][7]=avgDif; 123 | X[i*(k+1)][8]=variance; 124 | 125 | Y[i*(k+1)][0]=k; 126 | } 127 | Serial.println("Recording test data"); 128 | for(uint32_t i=0;i<(TRREE_TEST_TIME_SECONDS/WINDOW_SIZE_SECONDS);i++){ 129 | for(uint32_t j=0;j(6)/((k+1)*(k+1))){ 137 | digitalWrite(STATUS_LED_PIN,ledstate); 138 | ledstate=!ledstate; 139 | blinkCtr=0; 140 | } 141 | } 142 | float mean; 143 | float variance; 144 | float avgDif; 145 | computeFeatures(aXbuffer,&mean,&variance,&avgDif); 146 | X[i*(k+1)][0]=mean; 147 | X[i*(k+1)][1]=avgDif; 148 | X[i*(k+1)][2]=variance; 149 | 150 | computeFeatures(aYbuffer,&mean,&variance,&avgDif); 151 | X[i*(k+1)][3]=mean; 152 | X[i*(k+1)][4]=avgDif; 153 | X[i*(k+1)][5]=variance; 154 | 155 | computeFeatures(aZbuffer,&mean,&variance,&avgDif); 156 | X[i*(k+1)][6]=mean; 157 | X[i*(k+1)][7]=avgDif; 158 | X[i*(k+1)][8]=variance; 159 | 160 | Y[i*(k+1)][0]=k; 161 | } 162 | 163 | digitalWrite(STATUS_LED_PIN,0); 164 | delay(4000); 165 | 166 | for(uint32_t i=0;i<(TRREE_TRAINING_TIME_SECONDS/WINDOW_SIZE_SECONDS);i++){ 167 | for(uint32_t n=0;n clf(MAX_TREE_DEPTH,2); 176 | 177 | before = micros(); 178 | clf.fit(X,Y,TREE_NUMBER_OF_TRAINING_SAMPLES,TREE_NUMBER_OF_FEATURES); 179 | after = micros(); 180 | Serial.print("Training time: "); 181 | Serial.println(after-before); 182 | Serial.print("Accuracy:"); 183 | accuracy=clf.score(X_t,Y_t,TREE_NUMBER_OF_TEST_SAMPLES); 184 | Serial.println(accuracy); 185 | 186 | clf.plot(); 187 | Treetype k=0; 188 | while(1){ 189 | for(uint32_t j=0;j(6)/((k+1)*(k+1))){ 197 | digitalWrite(STATUS_LED_PIN,ledstate); 198 | ledstate=!ledstate; 199 | blinkCtr=0; 200 | } 201 | } 202 | float mean; 203 | float variance; 204 | float avgDif; 205 | computeFeatures(aXbuffer,&mean,&variance,&avgDif); 206 | Xp[0]=mean; 207 | Xp[1]=avgDif; 208 | Xp[2]=variance; 209 | 210 | computeFeatures(aYbuffer,&mean,&variance,&avgDif); 211 | Xp[3]=mean; 212 | Xp[4]=avgDif; 213 | Xp[5]=variance; 214 | 215 | computeFeatures(aZbuffer,&mean,&variance,&avgDif); 216 | Xp[6]=mean; 217 | Xp[7]=avgDif; 218 | Xp[8]=variance; 219 | 220 | k = clf.predict(Xp); 221 | Serial.print("Predicted label:"); 222 | Serial.println(k); 223 | Serial.println(accuracy); 224 | clf.plot(); 225 | } 226 | 227 | // digitalWrite(13,HIGH); 228 | // delay(100); 229 | // digitalWrite(13,LOW); 230 | // delay(1000); 231 | } 232 | -------------------------------------------------------------------------------- /examples/cncLearnerOnEsp32C6/.gitignore: -------------------------------------------------------------------------------- 1 | .pio 2 | .vscode/.browse.c_cpp.db* 3 | .vscode/c_cpp_properties.json 4 | .vscode/launch.json 5 | .vscode/ipch 6 | -------------------------------------------------------------------------------- /examples/cncLearnerOnEsp32C6/measuredData/tree.csv: -------------------------------------------------------------------------------- 1 | r,6 2 | n,-1,1,-1,-1 3 | n,-1,2,-1,-1 4 | n,-1,2,-1,-1 5 | n,-1,1,-1,-1 6 | n,0,0.031450,2,3 7 | n,4,0.034487,1,4 8 | n,1,0.012957,0,5 9 | -------------------------------------------------------------------------------- /examples/cncLearnerOnEsp32C6/platformio.ini: -------------------------------------------------------------------------------- 1 | ; PlatformIO Project Configuration File 2 | ; 3 | ; Build options: build flags, source filter 4 | ; Upload options: custom upload port, speed and extra flags 5 | ; Library options: dependencies, extra library storages 6 | ; Advanced options: extra scripting 7 | ; 8 | ; Please visit documentation for the other options and examples 9 | ; https://docs.platformio.org/page/projectconf.html 10 | 11 | [env:esp32-c6-devkitc-1] 12 | platform = espressif32 13 | board = esp32-c6-devkitc-1 14 | monitor_speed = 115200 15 | framework = arduino 16 | build_flags = 17 | -D ARDUINO_USB_MODE=1 18 | -D ARDUINO_USB_CDC_ON_BOOT=1 19 | lib_deps = 20 | adafruit/Adafruit BNO055@^1.6.3 21 | bxparks/AceButton@^1.10.1 22 | -------------------------------------------------------------------------------- /examples/cncLearnerOnEsp32C6/src/computationFunctions.h: -------------------------------------------------------------------------------- 1 | #include "Arduino.h" 2 | #include "globals.h" 3 | #ifndef TDC_CF 4 | #define TDC_CF 5 | void computeFeatures(float** buffer,float *mean, float* stddev, float* avgDif,uint32_t column,uint32_t windowSize){ 6 | *mean=0; 7 | *avgDif=0; 8 | *stddev=0; 9 | for(uint32_t j=0;j clf(MAX_TREE_DEPTH,MIN_SAMPLES_SPLIT,TinyDecisionTreeClassifier::GINI); 22 | 23 | #endif -------------------------------------------------------------------------------- /examples/cncLearnerOnEsp32C6/src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include "FS.h" 7 | #include "SD.h" 8 | #include "SPI.h" 9 | #include 10 | // #define DTR_DEBUG_ 11 | #include "TinyDecisionTreeClassifier.h" 12 | #include "ProcessingFunctions.h" 13 | #include "globals.h" 14 | 15 | using namespace ace_button; 16 | #define LED_PIN 8 17 | #include "sdHelpFunctions.h" 18 | #include "computationFunctions.h" 19 | 20 | Adafruit_BNO055 bno = Adafruit_BNO055(55, 0x28, &Wire); 21 | 22 | enum SystemState{ 23 | IDLE=0x00, 24 | RECORDING_1=0x01, 25 | RECORDING_2=0x02, 26 | LEARNING=0x03, 27 | PREDICTING=0x04 28 | }systemState; 29 | 30 | enum ButtonEv{ 31 | B_IDLE=0x00, 32 | B_CLICKED=0x01, 33 | B_DOUBLE_CLICKED=0x02, 34 | B_LONG_PRESSED=0x03 35 | }buttonEv; 36 | 37 | AceButton button; 38 | void handleEvent(AceButton*, uint8_t, uint8_t); 39 | 40 | void setup() { 41 | Serial.begin(115200); 42 | pinMode(22,OUTPUT); 43 | digitalWrite(22,HIGH); 44 | pinMode(LED_PIN,OUTPUT); 45 | digitalWrite(LED_PIN,HIGH); 46 | delay(1000); 47 | 48 | Wire.begin(21,20); 49 | 50 | SPI.begin(6,2,7,5); 51 | // SPI.setFrequency(10000); 52 | if(!SD.begin(5)){ 53 | Serial.println("Card Mount Failed"); 54 | return; 55 | }else{ 56 | Serial.println("SD ok"); 57 | } 58 | if(!bno.begin()) 59 | { 60 | Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!"); 61 | // while(1); 62 | } 63 | 64 | delay(1000); 65 | bno.setExtCrystalUse(true); 66 | pinMode(GPIO_NUM_9, INPUT); 67 | button.init(GPIO_NUM_9, HIGH); 68 | ButtonConfig* buttonConfig = button.getButtonConfig(); 69 | buttonConfig->setEventHandler(handleEvent); 70 | buttonConfig->setFeature(ButtonConfig::kFeatureClick); 71 | buttonConfig->setFeature(ButtonConfig::kFeatureDoubleClick); 72 | buttonConfig->setFeature(ButtonConfig::kFeatureLongPress); 73 | buttonConfig->setFeature(ButtonConfig::kFeatureRepeatPress); 74 | buttonConfig->setDoubleClickDelay(2000); 75 | // buttonConfig->setPressedDelay(10000); 76 | 77 | systemState = IDLE; 78 | buttonEv = B_IDLE; 79 | } 80 | 81 | uint32_t windowCounter=0; 82 | Treetype Xsample[9]; 83 | bool treeChecked = false; 84 | void loop() { 85 | uint32_t i=0; 86 | switch (systemState) 87 | { 88 | case IDLE: 89 | digitalWrite(LED_PIN,HIGH); 90 | if(!treeChecked){ 91 | if(fileExists(SD,"/tree.csv")){ 92 | loadTree(SD,"/tree.csv"); 93 | systemState=PREDICTING; 94 | allocBuffer(&X_window,WINDOW_SIZE,TREE_NUMBER_OF_RECORDED_FEATURES); 95 | allocBuffer(&Y_window,WINDOW_SIZE,1); 96 | } 97 | treeChecked=true; 98 | } 99 | if(buttonEv==B_CLICKED){ 100 | for(i=0;i<100;i++){ 101 | delay(10); 102 | button.check(); 103 | } 104 | switch (buttonEv) 105 | { 106 | case B_CLICKED: 107 | systemState=RECORDING_1; 108 | buttonEv=B_IDLE; 109 | break; 110 | case B_DOUBLE_CLICKED: 111 | systemState=RECORDING_2; 112 | buttonEv=B_IDLE; 113 | break; 114 | case B_LONG_PRESSED: 115 | systemState=LEARNING; 116 | buttonEv=B_IDLE; 117 | break; 118 | } 119 | } 120 | if(buttonEv==B_DOUBLE_CLICKED){ 121 | systemState=RECORDING_2; 122 | buttonEv=B_IDLE; 123 | break; 124 | } 125 | if(buttonEv==B_LONG_PRESSED){ 126 | systemState=LEARNING; 127 | buttonEv=B_IDLE; 128 | break; 129 | } 130 | break; 131 | case RECORDING_1:{ 132 | allocBuffer(&X_train,TREE_NUMBER_OF_RECORDED_TRAINING_SAMPLES,TREE_NUMBER_OF_RECORDED_FEATURES); 133 | allocBuffer(&Y_train,TREE_NUMBER_OF_RECORDED_TRAINING_SAMPLES,1); 134 | 135 | Serial.println("Record class 1"); 136 | for(i=0;iclass1SamplesSize ? class1SamplesSize : class2SamplesSize;//doublecheck 219 | 220 | uint32_t numberOfWindowsNeeded = (minimumSampleSize/WINDOW_SIZE)*2; 221 | 222 | Serial.println(class1SamplesSize); 223 | Serial.println(class2SamplesSize); 224 | Serial.println(numberOfWindowsNeeded); 225 | 226 | if(numberOfWindowsNeeded0){ 243 | shuffleData(X_train,Y_train,samplesRead,TRAINING_FEATURES_SIZE); 244 | Serial.println("Fitting start"); 245 | uint32_t fitting_start=micros(); 246 | clf.fit(X_train+testSize,Y_train+testSize,samplesRead-testSize,TRAINING_FEATURES_SIZE); 247 | clf.plot(); 248 | Serial.println(micros()-fitting_start); 249 | while(clf.prune(X_train+testSize,Y_train+testSize,samplesRead-testSize)); 250 | clf.plot(); 251 | saveTree(SD,"/tree.csv"); 252 | Serial.print("Score:"); 253 | Serial.println(clf.score(X_train,Y_train,testSize)); 254 | } 255 | 256 | deallocBuffer(&X_train,numberOfWindowsNeeded); 257 | deallocBuffer(&Y_train,numberOfWindowsNeeded); 258 | deallocBuffer(&X_window,WINDOW_SIZE); 259 | deallocBuffer(&Y_window,WINDOW_SIZE); 260 | 261 | return samplesRead; 262 | } 263 | 264 | -------------------------------------------------------------------------------- /examples/irisTestTrainFromSDOnEsp32/iris_test_ok.csv: -------------------------------------------------------------------------------- 1 | SepalLengthCm,SepalWidthCm,PetalLengthCm,PetalWidthCm,Species 2 | 6.1,2.8,4.7,1.2,1 3 | 5.7,3.8,1.7,0.3,0 4 | 7.7,2.6,6.9,2.3,2 5 | 6.0,2.9,4.5,1.5,1 6 | 6.8,2.8,4.8,1.4,1 7 | 5.4,3.4,1.5,0.4,0 8 | 5.6,2.9,3.6,1.3,1 9 | 6.9,3.1,5.1,2.3,2 10 | 6.2,2.2,4.5,1.5,1 11 | 5.8,2.7,3.9,1.2,1 12 | 6.5,3.2,5.1,2.0,2 13 | 4.8,3.0,1.4,0.1,0 14 | 5.5,3.5,1.3,0.2,0 15 | 4.9,3.1,1.5,0.1,0 16 | 5.1,3.8,1.5,0.3,0 17 | 6.3,3.3,4.7,1.6,1 18 | 6.5,3.0,5.8,2.2,2 19 | 5.6,2.5,3.9,1.1,1 20 | 5.7,2.8,4.5,1.3,1 21 | 6.4,2.8,5.6,2.2,2 22 | 4.7,3.2,1.6,0.2,0 23 | 6.1,3.0,4.9,1.8,2 24 | 5.0,3.4,1.6,0.4,0 25 | 6.4,2.8,5.6,2.1,2 26 | 7.9,3.8,6.4,2.0,2 27 | 6.7,3.0,5.2,2.3,2 28 | 6.7,2.5,5.8,1.8,2 29 | 6.8,3.2,5.9,2.3,2 30 | 4.8,3.0,1.4,0.3,0 31 | 4.8,3.1,1.6,0.2,0 32 | 4.6,3.6,1.0,0.2,0 33 | 5.7,4.4,1.5,0.4,0 34 | 6.7,3.1,4.4,1.4,1 35 | 4.8,3.4,1.6,0.2,0 36 | 4.4,3.2,1.3,0.2,0 37 | 6.3,2.5,5.0,1.9,2 38 | 6.4,3.2,4.5,1.5,1 39 | 5.2,3.5,1.5,0.2,0 40 | 5.0,3.6,1.4,0.2,0 41 | 5.2,4.1,1.5,0.1,0 42 | 5.8,2.7,5.1,1.9,2 43 | 6.0,3.4,4.5,1.6,1 44 | 6.7,3.1,4.7,1.5,1 45 | 5.4,3.9,1.3,0.4,0 46 | 5.4,3.7,1.5,0.2,0 47 | -------------------------------------------------------------------------------- /examples/irisTestTrainFromSDOnEsp32/iris_train_ok.csv: -------------------------------------------------------------------------------- 1 | SepalLengthCm,SepalWidthCm,PetalLengthCm,PetalWidthCm,Species 2 | 5.5,2.4,3.7,1.0,1 3 | 6.3,2.8,5.1,1.5,2 4 | 6.4,3.1,5.5,1.8,2 5 | 6.6,3.0,4.4,1.4,1 6 | 7.2,3.6,6.1,2.5,2 7 | 5.7,2.9,4.2,1.3,1 8 | 7.6,3.0,6.6,2.1,2 9 | 5.6,3.0,4.5,1.5,1 10 | 5.1,3.5,1.4,0.2,0 11 | 7.7,2.8,6.7,2.0,2 12 | 5.8,2.7,4.1,1.0,1 13 | 5.2,3.4,1.4,0.2,0 14 | 5.0,3.5,1.3,0.3,0 15 | 5.1,3.8,1.9,0.4,0 16 | 5.0,2.0,3.5,1.0,1 17 | 6.3,2.7,4.9,1.8,2 18 | 4.8,3.4,1.9,0.2,0 19 | 5.0,3.0,1.6,0.2,0 20 | 5.1,3.3,1.7,0.5,0 21 | 5.6,2.7,4.2,1.3,1 22 | 5.1,3.4,1.5,0.2,0 23 | 5.7,3.0,4.2,1.2,1 24 | 7.7,3.8,6.7,2.2,2 25 | 4.6,3.2,1.4,0.2,0 26 | 6.2,2.9,4.3,1.3,1 27 | 5.7,2.5,5.0,2.0,2 28 | 5.5,4.2,1.4,0.2,0 29 | 6.0,3.0,4.8,1.8,2 30 | 5.8,2.7,5.1,1.9,2 31 | 6.0,2.2,4.0,1.0,1 32 | 5.4,3.0,4.5,1.5,1 33 | 6.2,3.4,5.4,2.3,2 34 | 5.5,2.3,4.0,1.3,1 35 | 5.4,3.9,1.7,0.4,0 36 | 5.0,2.3,3.3,1.0,1 37 | 6.4,2.7,5.3,1.9,2 38 | 5.0,3.3,1.4,0.2,0 39 | 5.0,3.2,1.2,0.2,0 40 | 5.5,2.4,3.8,1.1,1 41 | 6.7,3.0,5.0,1.7,1 42 | 4.9,3.1,1.5,0.2,0 43 | 5.8,2.8,5.1,2.4,2 44 | 5.0,3.4,1.5,0.2,0 45 | 5.0,3.5,1.6,0.6,0 46 | 5.9,3.2,4.8,1.8,1 47 | 5.1,2.5,3.0,1.1,1 48 | 6.9,3.2,5.7,2.3,2 49 | 6.0,2.7,5.1,1.6,1 50 | 6.1,2.6,5.6,1.4,2 51 | 7.7,3.0,6.1,2.3,2 52 | 5.5,2.5,4.0,1.3,1 53 | 4.4,2.9,1.4,0.2,0 54 | 4.3,3.0,1.1,0.1,0 55 | 6.0,2.2,5.0,1.5,2 56 | 7.2,3.2,6.0,1.8,2 57 | 4.6,3.1,1.5,0.2,0 58 | 5.1,3.5,1.4,0.3,0 59 | 4.4,3.0,1.3,0.2,0 60 | 6.3,2.5,4.9,1.5,1 61 | 6.3,3.4,5.6,2.4,2 62 | 4.6,3.4,1.4,0.3,0 63 | 6.8,3.0,5.5,2.1,2 64 | 6.3,3.3,6.0,2.5,2 65 | 4.7,3.2,1.3,0.2,0 66 | 6.1,2.9,4.7,1.4,1 67 | 6.5,2.8,4.6,1.5,1 68 | 6.2,2.8,4.8,1.8,2 69 | 7.0,3.2,4.7,1.4,1 70 | 6.4,3.2,5.3,2.3,2 71 | 5.1,3.8,1.6,0.2,0 72 | 6.9,3.1,5.4,2.1,2 73 | 5.9,3.0,4.2,1.5,1 74 | 6.5,3.0,5.2,2.0,2 75 | 5.7,2.6,3.5,1.0,1 76 | 5.2,2.7,3.9,1.4,1 77 | 6.1,3.0,4.6,1.4,1 78 | 4.5,2.3,1.3,0.3,0 79 | 6.6,2.9,4.6,1.3,1 80 | 5.5,2.6,4.4,1.2,1 81 | 5.3,3.7,1.5,0.2,0 82 | 5.6,3.0,4.1,1.3,1 83 | 7.3,2.9,6.3,1.8,2 84 | 6.7,3.3,5.7,2.1,2 85 | 5.1,3.7,1.5,0.4,0 86 | 4.9,2.4,3.3,1.0,1 87 | 6.7,3.3,5.7,2.5,2 88 | 7.2,3.0,5.8,1.6,2 89 | 4.9,3.6,1.4,0.1,0 90 | 6.7,3.1,5.6,2.4,2 91 | 4.9,3.0,1.4,0.2,0 92 | 6.9,3.1,4.9,1.5,1 93 | 7.4,2.8,6.1,1.9,2 94 | 6.3,2.9,5.6,1.8,2 95 | 5.7,2.8,4.1,1.3,1 96 | 6.5,3.0,5.5,1.8,2 97 | 6.3,2.3,4.4,1.3,1 98 | 6.4,2.9,4.3,1.3,1 99 | 5.6,2.8,4.9,2.0,2 100 | 5.9,3.0,5.1,1.8,2 101 | 5.4,3.4,1.7,0.2,0 102 | 6.1,2.8,4.0,1.3,1 103 | 4.9,2.5,4.5,1.7,2 104 | 5.8,4.0,1.2,0.2,0 105 | 5.8,2.6,4.0,1.2,1 106 | 7.1,3.0,5.9,2.1,2 107 | -------------------------------------------------------------------------------- /examples/irisTestTrainFromSDOnEsp32/platformio.ini: -------------------------------------------------------------------------------- 1 | ; PlatformIO Project Configuration File 2 | ; 3 | ; Build options: build flags, source filter 4 | ; Upload options: custom upload port, speed and extra flags 5 | ; Library options: dependencies, extra library storages 6 | ; Advanced options: extra scripting 7 | ; 8 | ; Please visit documentation for the other options and examples 9 | ; https://docs.platformio.org/page/projectconf.html 10 | 11 | [env:esp32dev] 12 | platform = espressif32 13 | framework = arduino 14 | board = esp32dev 15 | monitor_speed = 115200 -------------------------------------------------------------------------------- /examples/irisTestTrainFromSDOnEsp32/src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // #define DTR_DEBUG_ 3 | #include "TinyDecisionTreeClassifier.h" 4 | #include "FS.h" 5 | #include "SD.h" 6 | #include "SPI.h" 7 | 8 | #define MAX_TREE_DEPTH 4 9 | #define MIN_SAMPLES_SPLIT 10 10 | 11 | #define NUMBER_OF_FEATURES 4 12 | #define NUMBER_OF_TRAIN_SAMPLES 105 13 | #define NUMBER_OF_TEST_SAMPLES 45 14 | 15 | typedef float Treetype; 16 | Treetype X_train_dat[NUMBER_OF_TRAIN_SAMPLES][NUMBER_OF_FEATURES]; 17 | Treetype Y_train_dat[NUMBER_OF_TRAIN_SAMPLES][1]; 18 | Treetype **X_train_ptr; 19 | Treetype **Y_train_ptr; 20 | 21 | Treetype X_test_dat[NUMBER_OF_TEST_SAMPLES][NUMBER_OF_FEATURES]; 22 | Treetype Y_test_dat[NUMBER_OF_TEST_SAMPLES][1]; 23 | Treetype **X_test_ptr; 24 | Treetype **Y_test_ptr; 25 | 26 | #define BENCHMARK_AVERAGING 10 27 | void benchmark(void){ 28 | uint32_t timeBefore; 29 | uint32_t timeAfter; 30 | uint64_t benchmarkingTrainingTime = 0; 31 | uint64_t benchmarkingPredictionTime = 0; 32 | Serial.println("Bechmarking start"); 33 | for(uint32_t i=0;i clf(MAX_TREE_DEPTH,MIN_SAMPLES_SPLIT); 35 | timeBefore = micros(); 36 | clf.fit(X_train_ptr,Y_train_ptr,NUMBER_OF_TRAIN_SAMPLES,NUMBER_OF_FEATURES); 37 | // Serial.println("Tree before pruning: "); 38 | // clf.plot(); 39 | while(clf.prune(X_train_ptr,Y_train_ptr,NUMBER_OF_TRAIN_SAMPLES)); 40 | timeAfter = micros(); 41 | benchmarkingTrainingTime+=(timeAfter-timeBefore); 42 | Treetype rslt; 43 | for(uint32_t j=0;j"); 88 | Serial.println(Y_train_dat[i][0]); 89 | i++; 90 | } 91 | } 92 | } 93 | file.close(); 94 | } 95 | 96 | void readTest(fs::FS &fs, const char * path){ 97 | Serial.printf("Reading test file: %s\n", path); 98 | 99 | File file = fs.open(path); 100 | if(!file){ 101 | Serial.println("Failed to open file for reading"); 102 | return; 103 | } 104 | 105 | Serial.print("Read from file: "); 106 | uint32_t i=0; 107 | int32_t idx; 108 | while (file.available()) { // Check if more data is available to read 109 | String line = file.readStringUntil('\n'); // Read a line from the file 110 | if(!line.isEmpty()){ 111 | if(sscanf(line.c_str(),"%ld,%f,%f,%f,%f,%f\n",&idx,&X_test_dat[i][0],&X_test_dat[i][1],&X_test_dat[i][2],&X_test_dat[i][3],&Y_test_dat[i][0])){ 112 | Serial.print(X_train_dat[i][0]); 113 | Serial.print(","); 114 | Serial.print(X_train_dat[i][1]); 115 | Serial.print(","); 116 | Serial.print(X_train_dat[i][2]); 117 | Serial.print(","); 118 | Serial.print(X_train_dat[i][3]); 119 | Serial.print("->"); 120 | Serial.println(Y_train_dat[i][0]); 121 | i++; 122 | } 123 | } 124 | } 125 | file.close(); 126 | } 127 | 128 | void setup() { 129 | Serial.begin(115200); 130 | delay(1000); 131 | uint32_t i; 132 | X_train_ptr = new Treetype *[NUMBER_OF_TRAIN_SAMPLES]; 133 | Y_train_ptr = new Treetype *[NUMBER_OF_TRAIN_SAMPLES]; 134 | for(i=0;i 2 | #include "../lib/TinyDecisionTreeClassifier/src/TinyDecisionTreeClassifier.h" 3 | 4 | #define NUMBER_OF_FEATURES 5 5 | #define NUMBER_OF_SAMPLES 7 6 | #define MAX_TREE_DEPTH 3 7 | typedef float Treetype; 8 | Treetype X_const[NUMBER_OF_SAMPLES][NUMBER_OF_FEATURES] = 9 | { {1,2,3,1,1}, 10 | {1,2,1,1,1}, 11 | {1,1,2,3,1}, 12 | {1,2,3,1,2}, 13 | {3,2,1,1,1}, 14 | {1,2,3,1,2}, 15 | {3,2,3,1,2}, 16 | }; 17 | 18 | Treetype Y_const[NUMBER_OF_SAMPLES][1] = { 19 | {1}, 20 | {0}, 21 | {1}, 22 | {0}, 23 | {1}, 24 | {1}, 25 | {0}, 26 | }; 27 | 28 | Treetype **X; 29 | Treetype **Y; 30 | 31 | int random(int min, int max) { 32 | return min + rand() % (max - min + 1); 33 | } 34 | 35 | void fillBuffersWithRandom(void){ 36 | for(uint32_t i=0;i clf1(MAX_TREE_DEPTH,2); 51 | clf1.fit(X,Y,NUMBER_OF_SAMPLES,NUMBER_OF_FEATURES); 52 | clf1.plot(); 53 | while(clf1.prune(X,Y,NUMBER_OF_SAMPLES)); 54 | clf1.plot(); 55 | clf1.save(&outputdata,&outputdatasize); 56 | printf("Tree saved, load start\n\r"); 57 | 58 | TinyDecisionTreeClassifier clf2(MAX_TREE_DEPTH,2); 59 | clf2.load(outputdata); 60 | clf2.plot(); 61 | free(outputdata); 62 | printf("Finished\n\r"); 63 | } 64 | 65 | } 66 | 67 | 68 | int main () { 69 | printf("Begin\n\r"); 70 | X = new Treetype *[NUMBER_OF_SAMPLES]; 71 | Y = new Treetype *[NUMBER_OF_SAMPLES]; 72 | for(uint32_t i=0;i 2 | #define DTR_DEBUG_ 3 | #include "TinyDecisionTreeClassifier.h" 4 | 5 | #define NUMBER_OF_FEATURES 5 6 | #define NUMBER_OF_SAMPLES 7 7 | #define MAX_TREE_DEPTH 3 8 | typedef float Treetype; 9 | Treetype X_const[NUMBER_OF_SAMPLES][NUMBER_OF_FEATURES] = 10 | { {1,2,3,1,1}, 11 | {1,2,1,1,1}, 12 | {1,1,2,3,1}, 13 | {1,2,3,1,2}, 14 | {3,2,1,1,1}, 15 | {1,2,3,1,2}, 16 | {3,2,3,1,2}, 17 | }; 18 | 19 | Treetype Y_const[NUMBER_OF_SAMPLES][1] = { 20 | {1}, 21 | {0}, 22 | {1}, 23 | {0}, 24 | {1}, 25 | {1}, 26 | {0}, 27 | }; 28 | 29 | Treetype **X; 30 | Treetype **Y; 31 | 32 | #define BENCHMARK_AVERAGING 1 33 | void benchmark(void){ 34 | uint32_t timeBefore; 35 | uint32_t timeAfter; 36 | uint64_t benchmarkingTrainingTime = 0; 37 | uint64_t benchmarkingPredictionTime = 0; 38 | Serial.println("Bechmarking start"); 39 | for(uint32_t i=0;i clf(MAX_TREE_DEPTH,2); 41 | timeBefore = micros(); 42 | clf.fit(X,Y,NUMBER_OF_SAMPLES,NUMBER_OF_FEATURES); 43 | Serial.println("Tree before pruning: "); 44 | clf.plot(); 45 | while(clf.prune(X,Y,NUMBER_OF_SAMPLES)); 46 | timeAfter = micros(); 47 | benchmarkingTrainingTime+=(timeAfter-timeBefore); 48 | Treetype rslt; 49 | for(uint32_t j=0;j clf1(MAX_TREE_DEPTH,2); 77 | clf1.fit(X,Y,NUMBER_OF_SAMPLES,NUMBER_OF_FEATURES); 78 | clf1.plot(); 79 | while(clf1.prune(X,Y,NUMBER_OF_SAMPLES)); 80 | clf1.plot(); 81 | clf1.save(&outputdata,&outputdatasize); 82 | Serial.println("Tree saved, load start"); 83 | 84 | TinyDecisionTreeClassifier clf2(MAX_TREE_DEPTH,2); 85 | clf2.load(outputdata); 86 | // clf2.plot(); 87 | free(outputdata); 88 | } 89 | Serial.println(memBefore-ESP.getFreeHeap()); 90 | 91 | } 92 | 93 | 94 | void setup() { 95 | Serial.begin(115200); 96 | X = new Treetype *[NUMBER_OF_SAMPLES]; 97 | Y = new Treetype *[NUMBER_OF_SAMPLES]; 98 | for(uint32_t i=0;i 2 | // #define DTR_DEBUG_ 3 | #include "TinyDecisionTreeClassifier.h" 4 | 5 | #define NUMBER_OF_FEATURES 5 6 | #define NUMBER_OF_SAMPLES 7 7 | #define MAX_TREE_DEPTH 3 8 | typedef float Treetype; 9 | Treetype X_const[NUMBER_OF_SAMPLES][NUMBER_OF_FEATURES] = 10 | { {1,2,3,1,1}, 11 | {1,2,1,1,1}, 12 | {1,1,2,3,1}, 13 | {1,2,3,1,2}, 14 | {3,2,1,1,1}, 15 | {1,2,3,1,2}, 16 | {3,2,3,1,2}, 17 | }; 18 | 19 | Treetype Y_const[NUMBER_OF_SAMPLES][1] = { 20 | {1}, 21 | {0}, 22 | {1}, 23 | {0}, 24 | {1}, 25 | {1}, 26 | {0}, 27 | }; 28 | 29 | Treetype **X; 30 | Treetype **Y; 31 | 32 | void fillBuffersWithRandom(void){ 33 | for(uint32_t i=0;i clf(MAX_TREE_DEPTH,2); 50 | timeBefore = micros(); 51 | clf.fit(X,Y,NUMBER_OF_SAMPLES,NUMBER_OF_FEATURES); 52 | Serial.println("Tree before pruning: "); 53 | clf.plot(); 54 | while(clf.prune(X,Y,NUMBER_OF_SAMPLES)); 55 | timeAfter = micros(); 56 | benchmarkingTrainingTime+=(timeAfter-timeBefore); 57 | Treetype rslt; 58 | for(uint32_t j=0;j clf1(MAX_TREE_DEPTH,2); 87 | clf1.fit(X,Y,NUMBER_OF_SAMPLES,NUMBER_OF_FEATURES); 88 | clf1.plot(); 89 | while(clf1.prune(X,Y,NUMBER_OF_SAMPLES)); 90 | clf1.plot(); 91 | clf1.save(&outputdata,&outputdatasize); 92 | Serial.println("Tree saved, load start"); 93 | Serial.println(outputdata); 94 | 95 | TinyDecisionTreeClassifier clf2(MAX_TREE_DEPTH,2); 96 | clf2.load(outputdata); 97 | clf2.plot(); 98 | free(outputdata); 99 | Serial.println("Finished"); 100 | 101 | } 102 | 103 | } 104 | 105 | 106 | void setup() { 107 | Serial.begin(115200); 108 | X = new Treetype *[NUMBER_OF_SAMPLES]; 109 | Y = new Treetype *[NUMBER_OF_SAMPLES]; 110 | for(uint32_t i=0;i 3 | // #define __DTR_DEBUG_ 4 | #include "TinyDecisionTreeClassifier.h" 5 | #include 6 | #include 7 | 8 | MPU6050 mpu6050(Wire); 9 | #define WINDOW_SIZE_SECONDS 2 10 | #define SAMPLING_FREQENCY 20 11 | #define WINDOW_BUFFER_SIZE WINDOW_SIZE_SECONDS*SAMPLING_FREQENCY 12 | 13 | #define TRREE_TRAINING_TIME_PER_CLASS_SECONDS 120 14 | #define TRREE_TEST_TIME_PER_CLASS_SECONDS (uint32_t)(TRREE_TRAINING_TIME_PER_CLASS_SECONDS/4) 15 | #define TREE_NUMBER_OF_CLASSES 3 16 | #define TREE_NUMBER_OF_FEATURES 9 17 | #define TREE_NUMBER_OF_TRAINING_SAMPLES (uint32_t(TREE_NUMBER_OF_CLASSES*TRREE_TRAINING_TIME_PER_CLASS_SECONDS/WINDOW_SIZE_SECONDS))+1 18 | #define TREE_NUMBER_OF_TEST_SAMPLES (uint32_t(TREE_NUMBER_OF_CLASSES*TRREE_TEST_TIME_PER_CLASS_SECONDS/WINDOW_SIZE_SECONDS))+1 19 | 20 | #define MAX_TREE_DEPTH 4 21 | typedef float Treetype; 22 | Treetype X_train[TREE_NUMBER_OF_TRAINING_SAMPLES][TREE_NUMBER_OF_FEATURES]; 23 | Treetype Y_train[TREE_NUMBER_OF_TRAINING_SAMPLES][1]; 24 | 25 | Treetype X_test[TREE_NUMBER_OF_TEST_SAMPLES][TREE_NUMBER_OF_FEATURES]; 26 | Treetype Y_test[TREE_NUMBER_OF_TEST_SAMPLES][1]; 27 | 28 | Treetype **X; 29 | Treetype **Y; 30 | Treetype **X_t; 31 | Treetype **Y_t; 32 | 33 | #define STATUS_LED_PIN 2 //P0.13 34 | 35 | void setup() { 36 | 37 | Serial.begin(115200); 38 | Serial.println("Here we go!"); 39 | X = new Treetype *[TREE_NUMBER_OF_TRAINING_SAMPLES]; 40 | Y = new Treetype *[TREE_NUMBER_OF_TRAINING_SAMPLES]; 41 | for(uint32_t i=0;i(6)/((k+1)*(k+1))){ 100 | digitalWrite(STATUS_LED_PIN,ledstate); 101 | ledstate=!ledstate; 102 | blinkCtr=0; 103 | } 104 | } 105 | float mean; 106 | float variance; 107 | float avgDif; 108 | computeFeatures(aXbuffer,&mean,&variance,&avgDif); 109 | X[i*(k+1)][0]=mean; 110 | X[i*(k+1)][1]=avgDif; 111 | X[i*(k+1)][2]=variance; 112 | 113 | computeFeatures(aYbuffer,&mean,&variance,&avgDif); 114 | X[i*(k+1)][3]=mean; 115 | X[i*(k+1)][4]=avgDif; 116 | X[i*(k+1)][5]=variance; 117 | 118 | computeFeatures(aZbuffer,&mean,&variance,&avgDif); 119 | X[i*(k+1)][6]=mean; 120 | X[i*(k+1)][7]=avgDif; 121 | X[i*(k+1)][8]=variance; 122 | 123 | Y[i*(k+1)][0]=k; 124 | } 125 | Serial.println("Recording test data"); 126 | for(uint32_t i=0;i<(TRREE_TEST_TIME_PER_CLASS_SECONDS/WINDOW_SIZE_SECONDS);i++){ 127 | for(uint32_t j=0;j(6)/((k+1)*(k+1))){ 135 | digitalWrite(STATUS_LED_PIN,ledstate); 136 | ledstate=!ledstate; 137 | blinkCtr=0; 138 | } 139 | } 140 | float mean; 141 | float variance; 142 | float avgDif; 143 | computeFeatures(aXbuffer,&mean,&variance,&avgDif); 144 | X[i*(k+1)][0]=mean; 145 | X[i*(k+1)][1]=avgDif; 146 | X[i*(k+1)][2]=variance; 147 | 148 | computeFeatures(aYbuffer,&mean,&variance,&avgDif); 149 | X[i*(k+1)][3]=mean; 150 | X[i*(k+1)][4]=avgDif; 151 | X[i*(k+1)][5]=variance; 152 | 153 | computeFeatures(aZbuffer,&mean,&variance,&avgDif); 154 | X[i*(k+1)][6]=mean; 155 | X[i*(k+1)][7]=avgDif; 156 | X[i*(k+1)][8]=variance; 157 | 158 | Y[i*(k+1)][0]=k; 159 | } 160 | 161 | digitalWrite(STATUS_LED_PIN,0); 162 | delay(4000); 163 | 164 | for(uint32_t i=0;i<(TRREE_TRAINING_TIME_PER_CLASS_SECONDS/WINDOW_SIZE_SECONDS);i++){ 165 | for(uint32_t n=0;n clf(MAX_TREE_DEPTH,2); 174 | 175 | before = micros(); 176 | clf.fit(X,Y,TREE_NUMBER_OF_TRAINING_SAMPLES,TREE_NUMBER_OF_FEATURES); 177 | after = micros(); 178 | Serial.print("Training time: "); 179 | Serial.println(after-before); 180 | Serial.print("Accuracy:"); 181 | accuracy=clf.score(X_t,Y_t,TREE_NUMBER_OF_TEST_SAMPLES); 182 | Serial.println(accuracy); 183 | 184 | clf.plot(); 185 | Treetype k=0; 186 | while(1){ 187 | for(uint32_t j=0;j(6)/((k+1)*(k+1))){ 195 | digitalWrite(STATUS_LED_PIN,ledstate); 196 | ledstate=!ledstate; 197 | blinkCtr=0; 198 | } 199 | } 200 | float mean; 201 | float variance; 202 | float avgDif; 203 | computeFeatures(aXbuffer,&mean,&variance,&avgDif); 204 | Xp[0]=mean; 205 | Xp[1]=avgDif; 206 | Xp[2]=variance; 207 | 208 | computeFeatures(aYbuffer,&mean,&variance,&avgDif); 209 | Xp[3]=mean; 210 | Xp[4]=avgDif; 211 | Xp[5]=variance; 212 | 213 | computeFeatures(aZbuffer,&mean,&variance,&avgDif); 214 | Xp[6]=mean; 215 | Xp[7]=avgDif; 216 | Xp[8]=variance; 217 | 218 | k = clf.predict(Xp); 219 | Serial.print("Predicted label:"); 220 | Serial.println(k); 221 | Serial.println(accuracy); 222 | clf.plot(); 223 | } 224 | 225 | // digitalWrite(13,HIGH); 226 | // delay(100); 227 | // digitalWrite(13,LOW); 228 | // delay(1000); 229 | } 230 | -------------------------------------------------------------------------------- /examples/testForMemoryLeaksOnEsp32/platformio.ini: -------------------------------------------------------------------------------- 1 | ; PlatformIO Project Configuration File 2 | ; 3 | ; Build options: build flags, source filter 4 | ; Upload options: custom upload port, speed and extra flags 5 | ; Library options: dependencies, extra library storages 6 | ; Advanced options: extra scripting 7 | ; 8 | ; Please visit documentation for the other options and examples 9 | ; https://docs.platformio.org/page/projectconf.html 10 | 11 | [env:esp32dev] 12 | platform = espressif32 13 | framework = arduino 14 | board = esp32dev 15 | -------------------------------------------------------------------------------- /examples/testForMemoryLeaksOnEsp32/src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // #define DTR_DEBUG_ 3 | #include "TinyDecisionTreeClassifier.h" 4 | 5 | #define NUMBER_OF_FEATURES 5 6 | #define NUMBER_OF_SAMPLES 20 7 | #define MAX_TREE_DEPTH 3 8 | typedef float Treetype; 9 | Treetype X_const[NUMBER_OF_SAMPLES][NUMBER_OF_FEATURES]; 10 | Treetype Y_const[NUMBER_OF_SAMPLES][1]; 11 | 12 | Treetype **X; 13 | Treetype **Y; 14 | 15 | #define BENCHMARK_AVERAGING 10 16 | void fillBuffersWithRandom(void){ 17 | for(uint32_t i=0;i clf(MAX_TREE_DEPTH,2); 38 | fillBuffersWithRandom(); 39 | timeBefore = micros(); 40 | clf.fit(X,Y,NUMBER_OF_SAMPLES,NUMBER_OF_FEATURES); 41 | timeAfter = micros(); 42 | fillBuffersWithRandom(); 43 | while(clf.prune(X,Y,NUMBER_OF_SAMPLES)); 44 | benchmarkingTrainingTime+=(timeAfter-timeBefore); 45 | Treetype rslt; 46 | for(uint32_t j=0;j 4 | maintainer=Aleksei Karavaev 5 | sentence=TinyDecisionTreeClassifier is a simple but elegant standalone library for training decision trees directly on the edge. 6 | paragraph=Based around the simplified C4.5 algotithm. 7 | category=Data Processing 8 | url=https://github.com/allexoK/TinyDecisionTreeClassifier.git 9 | architectures=* -------------------------------------------------------------------------------- /robots.txt: -------------------------------------------------------------------------------- 1 | User-agent: * 2 | Disallow: /src/ 3 | Disallow: /examples/ 4 | Disallow: /include/ 5 | Disallow: /img/ -------------------------------------------------------------------------------- /src/ProcessingFunctions.h: -------------------------------------------------------------------------------- 1 | #ifndef TDC_PROCESSING_H 2 | #define TDC_PROCESSING_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | template< typename T> 9 | void shuffleData(T** X, T** y, uint32_t rows, uint32_t cols){ 10 | uint32_t i; 11 | uint32_t j; 12 | for (i=0;i 26 | void sampleBagging(typename TinyDecisionTreeClassifier::RowsSubIndexes* rsi, uint32_t totalRows, uint32_t neededRows){ 27 | uint32_t i; 28 | uint32_t j; 29 | uint32_t* indicies = new uint32_t[totalRows]; 30 | if(indicies!=NULL){ 31 | for(i=0;iindexes = (uint32_t*)realloc(rsi->indexes,neededRows*(sizeof(uint32_t))); 44 | rsi->size = neededRows; 45 | for(i=0;iindexes[i]=indicies[i]; 47 | } 48 | delete indicies; 49 | } 50 | } 51 | 52 | #endif -------------------------------------------------------------------------------- /src/TinyDecisionTreeClassifier.cpp: -------------------------------------------------------------------------------- 1 | /* TinyDecisionTreeClassifier library 2 | * Copyright (c) 2023-2024 Aleksei Karavaev 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef DECISION_TREE_CLASSIFIER_CPP 18 | #define DECISION_TREE_CLASSIFIER_CPP 19 | #include "TinyDecisionTreeClassifier.h" 20 | 21 | template < typename T > 22 | TinyDecisionTreeClassifier::TinyDecisionTreeClassifier(uint16_t maxDepth, uint16_t minSamplesSplit, Goodness_criterion gc){ 23 | this->maxDepth=maxDepth; 24 | this->minSamplesSplit=minSamplesSplit; 25 | this->root = NULL; 26 | this->gc = gc; 27 | }; 28 | 29 | template < typename T > 30 | TinyDecisionTreeClassifier::~TinyDecisionTreeClassifier(){ 31 | if(root!=NULL){ 32 | root->cleanup(); 33 | delete root; 34 | } 35 | }; 36 | 37 | // number of rows is the same for both 38 | template < typename T > 39 | void TinyDecisionTreeClassifier::fit(T** X,T** Y, uint32_t rows,uint32_t cols,RowsSubIndexes* rootRsi){ 40 | if(root!=NULL){ 41 | root->cleanup(); 42 | delete root; 43 | root=NULL; 44 | } 45 | root = new Node(); 46 | bool cleanRsi=false; 47 | if(rootRsi==NULL){ 48 | cleanRsi=true; 49 | rootRsi = new RowsSubIndexes; 50 | rootRsi->size = rows; 51 | rootRsi->indexes = (uint32_t *)malloc(rows*sizeof(uint32_t)); 52 | for(uint32_t i=0;iindexes[i]=i; 54 | } 55 | } 56 | countUniqueValuesAndOccurances(Y,rootRsi,0,&uniqueClassValuesAndOccurances); 57 | recurcisiveFit(root,X,Y,rootRsi,cols,1); 58 | this->cols = cols; 59 | if(cleanRsi)delete rootRsi; 60 | }; 61 | 62 | template < typename T > 63 | void TinyDecisionTreeClassifier::plot(void){ 64 | plot(root,0); 65 | } 66 | 67 | template < typename T > 68 | void TinyDecisionTreeClassifier::plot(Node* node,uint32_t depth){ 69 | if(node->thReady){ 70 | for(uint32_t i=0;inodeThColumn); 75 | DTR_PLOT_PRINT("]<="); 76 | DTR_PLOT_PRINT_F(node->nodeTh); 77 | DTR_PLOT_PRINTLN(")"); 78 | } 79 | if(node->decisionReady){ 80 | for(uint32_t i=0;idecision); 85 | DTR_PLOT_PRINTLN(")"); 86 | } 87 | 88 | if(node->children[0]!=NULL){ 89 | for(uint16_t i=0;i<2;i++){ 90 | plot(node->children[i],depth+1); 91 | } 92 | } 93 | } 94 | 95 | template < typename T > 96 | T TinyDecisionTreeClassifier::predict(T* X){ 97 | if(root==NULL)return 0; 98 | return root->decide(X); 99 | } 100 | 101 | template < typename T > 102 | float TinyDecisionTreeClassifier::score(T** X,T** Y,uint32_t rows){ 103 | float score = 0; 104 | for(uint32_t i=0;i 111 | TinyDecisionTreeClassifier::Node::Node(){} 112 | 113 | template < typename T > 114 | int16_t TinyDecisionTreeClassifier::recurcisiveFit(Node* node,T** X,T** Y, RowsSubIndexes* rsi, uint32_t cols, uint32_t currentDepth){ 115 | DTR_DEBUG_PRINTLN(); 116 | DTR_DEBUG_PRINT("Recursive fit for node:"); 117 | DTR_DEBUG_PRINTLN((uint32_t)this); 118 | DTR_DEBUG_PRINTLN("Input data:"); 119 | for(uint32_t i=0;isize;i++){ 120 | for(uint32_t j=0;jindexes[i]][j]); 122 | DTR_DEBUG_PRINT(' '); 123 | } 124 | DTR_DEBUG_PRINT("-> "); 125 | DTR_DEBUG_PRINTLN(Y[rsi->indexes[i]][0]); 126 | } 127 | countOccurances(Y,rsi,0,&uniqueClassValuesAndOccurances); 128 | //check only class 129 | if(onlyClassLeft(&uniqueClassValuesAndOccurances)==1){ 130 | node->decision = getMajorClass(&uniqueClassValuesAndOccurances); 131 | node->decisionReady = true; 132 | DTR_DEBUG_PRINT("Only unique class, finish splitting, decision is "); 133 | DTR_DEBUG_PRINTLN(node->decision); 134 | return 0; 135 | } 136 | else if (rsi->sizedecision = getMajorClass(&uniqueClassValuesAndOccurances); 138 | node->decisionReady = true; 139 | DTR_DEBUG_PRINTLN("Length of X and Y is less than min sample split, decision is "); 140 | DTR_DEBUG_PRINTLN(node->decision); 141 | return 0; 142 | } 143 | else if (currentDepth == maxDepth){ 144 | node->decision = getMajorClass(&uniqueClassValuesAndOccurances); 145 | node->decisionReady = true; 146 | DTR_DEBUG_PRINT("Max depth reached, decision is "); 147 | DTR_DEBUG_PRINTLN(node->decision); 148 | return 0; 149 | } 150 | 151 | RowsSubIndexes rsiAboveTh; 152 | RowsSubIndexes rsiBelowTh; 153 | rsiAboveTh.indexes=(uint32_t*)malloc((rsi->size)*sizeof(uint32_t)); 154 | rsiBelowTh.indexes=(uint32_t*)malloc((rsi->size)*sizeof(uint32_t)); 155 | 156 | T th; 157 | uint32_t thColumn; 158 | int16_t rslt; 159 | switch (gc) 160 | { 161 | case INFO_GAIN: 162 | rslt = getBestSplitInfoGain(X,Y,rsi,cols,&rsiAboveTh,&rsiBelowTh,&th,&thColumn); 163 | break; 164 | case GINI: 165 | rslt = getBestSplitGini(X,Y,rsi,cols,&rsiAboveTh,&rsiBelowTh,&th,&thColumn); 166 | break; 167 | default: 168 | rslt = getBestSplitInfoGain(X,Y,rsi,cols,&rsiAboveTh,&rsiBelowTh,&th,&thColumn); 169 | break; 170 | } 171 | 172 | 173 | if(rslt != CANT_SPLIT_ALL_THE_SAMPLES_HAVE_THE_SAME_VALUE){ 174 | node->children[0] = new Node(); 175 | node->children[1] = new Node(); 176 | 177 | node->nodeTh=th; 178 | node->nodeThColumn=thColumn; 179 | node->thReady = true; 180 | node->decision = getMajorClass(&uniqueClassValuesAndOccurances); 181 | 182 | recurcisiveFit(node->children[0],X,Y,&rsiBelowTh,cols,currentDepth+1); 183 | recurcisiveFit(node->children[1],X,Y,&rsiAboveTh,cols,currentDepth+1); 184 | }else{ 185 | node->decision = getMajorClass(&uniqueClassValuesAndOccurances); 186 | node->decisionReady = true; 187 | } 188 | return 0; 189 | } 190 | 191 | template < typename T > 192 | float TinyDecisionTreeClassifier::computeEntropy(T** Y, RowsSubIndexes* rsi){ 193 | float entropy=0; 194 | if(rsi->size<2){ 195 | return 0; 196 | } 197 | else{ 198 | countOccurances(Y,rsi,0,&uniqueClassValuesAndOccurances); 199 | uint32_t i; 200 | for(i = 0;isize; 202 | entropy += -(freq*(log(freq+1e-6)/log(2))); 203 | } 204 | } 205 | return entropy; 206 | } 207 | 208 | template < typename T > 209 | int16_t TinyDecisionTreeClassifier::getBestSplitInfoGain(T** X,T** Y, RowsSubIndexes* rsi, uint32_t cols, RowsSubIndexes* rsiAboveTh, RowsSubIndexes* rsiBelowTh, T* threshold, uint32_t* column){ 210 | float entropyBeforeTheSplit=computeEntropy(Y,rsi); 211 | float entropyAbove; 212 | float entropyBelow; 213 | float infoGain;//A few operations can be saved by using Entropy directly without computing Y entropy 214 | uint32_t k=0; 215 | 216 | //finding max 217 | float bestInfoGain=-FLT_MAX; 218 | RowsSubIndexes currentRsiBelowTh; 219 | RowsSubIndexes currentRsiAboveTh; 220 | currentRsiBelowTh.indexes=(uint32_t *)malloc(rsi->size*sizeof(uint32_t)); 221 | currentRsiAboveTh.indexes=(uint32_t *)malloc(rsi->size*sizeof(uint32_t)); 222 | 223 | for(uint32_t i=0;isize*sizeof(T)); 226 | uint32_t* idxs = (uint32_t *)malloc(rsi->size*sizeof(uint32_t)); 227 | 228 | for(uint32_t j=0;jsize;j++){ 229 | sorted[j]=X[rsi->indexes[j]][i]; 230 | idxs[j]=rsi->indexes[j]; 231 | } 232 | qsort(sorted,idxs,rsi->size); 233 | 234 | //Find where the values differ and check entropy (to find max for threshold generation) 235 | for(uint32_t j=1;jsize;j++){ 236 | if(sorted[j]!=sorted[j-1]){ 237 | currentRsiBelowTh.size=j; 238 | for(uint32_t k=0;ksize-j); 244 | for(uint32_t k=j;k<(rsi->size);k++){ 245 | currentRsiAboveTh.indexes[k-j]=idxs[k]; 246 | } 247 | entropyAbove = computeEntropy(Y,¤tRsiAboveTh); 248 | 249 | infoGain = entropyBeforeTheSplit - (entropyBelow*(((float)j)/((float)rsi->size))+entropyAbove*(((float)(rsi->size-j))/((float)rsi->size))); 250 | if(infoGain>bestInfoGain){ 251 | bestInfoGain=infoGain; 252 | *threshold=(sorted[j-1] + sorted[j])/2; 253 | *column=i; 254 | 255 | // if(rsiBelowTh->indexes)free(rsiBelowTh->indexes); 256 | // rsiBelowTh->indexes=(uint32_t*)malloc(j*sizeof(uint32_t)); 257 | rsiBelowTh->size=j; 258 | for(k=0;kindexes[k]=idxs[k]; 260 | } 261 | 262 | // if(rsiAboveTh->indexes)free(rsiAboveTh->indexes); 263 | // rsiAboveTh->indexes=(uint32_t*)malloc((rsi->size-j)*sizeof(uint32_t)); 264 | rsiAboveTh->size=(rsi->size-j); 265 | for(k=j;k<(rsi->size);k++){ 266 | rsiAboveTh->indexes[k-j]=idxs[k]; 267 | } 268 | } 269 | } 270 | } 271 | free(sorted); 272 | free(idxs); 273 | } 274 | if(bestInfoGain==-FLT_MAX){ 275 | DTR_DEBUG_PRINT("Can't split all the samples have the same value"); 276 | return CANT_SPLIT_ALL_THE_SAMPLES_HAVE_THE_SAME_VALUE; 277 | } 278 | DTR_DEBUG_PRINT("Best split in column "); 279 | DTR_DEBUG_PRINT(*column); 280 | DTR_DEBUG_PRINT(" with threhold "); 281 | DTR_DEBUG_PRINT(*threshold); 282 | DTR_DEBUG_PRINT(" and infogain "); 283 | DTR_DEBUG_PRINTLN(bestInfoGain); 284 | DTR_DEBUG_PRINT("Data below thehold "); 285 | for(uint32_t k=0;ksize;k++){ 286 | DTR_DEBUG_PRINT(" "); 287 | DTR_DEBUG_PRINT(X[rsiBelowTh->indexes[k]][*column]); 288 | } 289 | DTR_DEBUG_PRINTLN(); 290 | DTR_DEBUG_PRINT("Data above thehold "); 291 | for(uint32_t k=0;ksize;k++){ 292 | DTR_DEBUG_PRINT(" "); 293 | DTR_DEBUG_PRINT(X[rsiAboveTh->indexes[k]][*column]); 294 | } 295 | DTR_DEBUG_PRINTLN(); 296 | return 0; 297 | } 298 | 299 | template < typename T > 300 | float TinyDecisionTreeClassifier::computeGini(T** Y,RowsSubIndexes* rsi){ 301 | float gini=1; 302 | if(rsi->size<2){ 303 | return 0; 304 | } 305 | else{ 306 | countOccurances(Y,rsi,0,&uniqueClassValuesAndOccurances); 307 | uint32_t i; 308 | for(i = 0;isize; 310 | gini -= (float)((float)freq*(float)freq); 311 | } 312 | } 313 | return gini; 314 | } 315 | 316 | template < typename T > 317 | int16_t TinyDecisionTreeClassifier::getBestSplitGini(T** X,T** Y, RowsSubIndexes* rsi, uint32_t cols, RowsSubIndexes* rsiAboveTh, RowsSubIndexes* rsiBelowTh, T* threshold, uint32_t* column){ 318 | float giniAbove; 319 | float giniBelow; 320 | float giniSplit;//A few operations can be saved by using Entropy directly without computing Y entropy 321 | uint32_t k; 322 | 323 | //finding max 324 | float bestGiniSplit=0.5; 325 | struct RowsSubIndexes currentRsiBelowTh; 326 | struct RowsSubIndexes currentRsiAboveTh; 327 | currentRsiBelowTh.indexes=(uint32_t *)malloc(rsi->size*sizeof(uint32_t)); 328 | currentRsiAboveTh.indexes=(uint32_t *)malloc(rsi->size*sizeof(uint32_t)); 329 | 330 | // uint32_t totalSorting=0; 331 | // uint32_t total=micros(); 332 | // uint32_t totalGini=0; 333 | 334 | uint32_t tic=0; 335 | for(uint32_t i=0;isize*sizeof(T)); 337 | uint32_t* idxs = (uint32_t *)malloc(rsi->size*sizeof(uint32_t)); 338 | 339 | for(uint32_t j=0;jsize;j++){ 340 | sorted[j]=X[rsi->indexes[j]][i]; 341 | idxs[j]=rsi->indexes[j]; 342 | } 343 | qsort(sorted,idxs,rsi->size); 344 | 345 | //Find where the values differ and check entropy (to find max for threshold generation) 346 | for(uint32_t j=1;jsize;j++){ 347 | if(sorted[j]!=sorted[j-1]){ 348 | currentRsiBelowTh.size=j; 349 | for(k=0;ksize-j); 354 | for(k=j;k<(rsi->size);k++){ 355 | currentRsiAboveTh.indexes[k-j]=idxs[k]; 356 | } 357 | 358 | giniAbove = computeGini(Y,¤tRsiAboveTh); 359 | 360 | giniSplit = (giniBelow*(((float)j)/((float)rsi->size))+giniAbove*(((float)(rsi->size-j))/((float)rsi->size))); 361 | if(giniSplitsize=j; 367 | 368 | for(k=0;kindexes[k]=idxs[k]; 370 | } 371 | 372 | rsiAboveTh->size=(rsi->size-j); 373 | for(k=j;k<(rsi->size);k++){ 374 | rsiAboveTh->indexes[k-j]=idxs[k]; 375 | } 376 | } 377 | } 378 | } 379 | free(sorted); 380 | free(idxs); 381 | } 382 | 383 | if(bestGiniSplit==0.5){ 384 | DTR_DEBUG_PRINT("Can't split all the samples have the same value"); 385 | return CANT_SPLIT_ALL_THE_SAMPLES_HAVE_THE_SAME_VALUE; 386 | } 387 | DTR_DEBUG_PRINT("Best split in column "); 388 | DTR_DEBUG_PRINT(*column); 389 | DTR_DEBUG_PRINT(" with threhold "); 390 | DTR_DEBUG_PRINT(*threshold); 391 | DTR_DEBUG_PRINT(" and gini "); 392 | DTR_DEBUG_PRINT(bestGiniSplit); 393 | DTR_DEBUG_PRINTLN(""); 394 | DTR_DEBUG_PRINT("Data below thehold "); 395 | for(k=0;ksize;k++){ 396 | DTR_DEBUG_PRINT(" "); 397 | DTR_DEBUG_PRINT(X[rsiBelowTh->indexes[k]][*column]); 398 | } 399 | DTR_DEBUG_PRINTLN(""); 400 | DTR_DEBUG_PRINT("Data above thehold "); 401 | for(k=0;ksize;k++){ 402 | DTR_DEBUG_PRINTLN(" "); 403 | DTR_DEBUG_PRINT(X[rsiAboveTh->indexes[k]][*column]); 404 | } 405 | DTR_DEBUG_PRINTLN(""); 406 | return 0; 407 | } 408 | 409 | template < typename T > 410 | void TinyDecisionTreeClassifier::countUniqueValuesAndOccurances(T ** ar, RowsSubIndexes* rsi, uint32_t column, UniqueValues* uv){ 411 | T* sorted = (T *)malloc(rsi->size*sizeof(T)); 412 | 413 | for(uint32_t i=0;isize;i++){ 414 | sorted[i]=ar[rsi->indexes[i]][column]; 415 | } 416 | qsort(sorted,rsi->size); 417 | 418 | uv->uniqueValues = (T *)malloc(1*sizeof(T)); 419 | uv->uniqueValuesOccurances = (uint32_t *)malloc(1*sizeof(uint32_t)); 420 | uv->uniqueValues[0] = sorted[0]; 421 | uv->uniqueValuesSize = 1; 422 | uv->uniqueValuesOccurances[0]=1; 423 | 424 | for (uint16_t i=1;isize;i++){ 425 | if(sorted[i]!=sorted[i-1]){ 426 | uv->uniqueValues = (T *)realloc(uv->uniqueValues,(uv->uniqueValuesSize+1)*sizeof(T)); 427 | uv->uniqueValuesOccurances = (uint32_t *)realloc(uv->uniqueValuesOccurances,(uv->uniqueValuesSize+1)*sizeof(uint32_t)); 428 | uv->uniqueValuesOccurances[uv->uniqueValuesSize]=1; 429 | uv->uniqueValues[uv->uniqueValuesSize]=sorted[i]; 430 | uv->uniqueValuesSize++; 431 | }else{ 432 | uv->uniqueValuesOccurances[uv->uniqueValuesSize-1]++; 433 | } 434 | } 435 | free(sorted); 436 | } 437 | 438 | template < typename T > 439 | void TinyDecisionTreeClassifier::countOccurances(T ** ar, RowsSubIndexes* rsi, uint32_t column, UniqueValues* uv){ 440 | uint16_t i=0; 441 | uint16_t j=0; 442 | for(j=0;juniqueValuesSize;j++){ 443 | uv->uniqueValuesOccurances[j]=0; 444 | } 445 | for (i=0;isize;i++){ 446 | for(j=0;juniqueValuesSize;j++){ 447 | if(ar[rsi->indexes[i]][column]==uv->uniqueValues[j])uv->uniqueValuesOccurances[j]++; 448 | } 449 | } 450 | } 451 | 452 | template < typename T > 453 | bool TinyDecisionTreeClassifier::onlyClassLeft(UniqueValues* uv){ 454 | uint32_t i; 455 | uint32_t non0Ctr=0; 456 | for(i=0;iuniqueValuesSize;i++){ 457 | if(uv->uniqueValuesOccurances[i]!=0)non0Ctr++; 458 | } 459 | return non0Ctr==1; 460 | } 461 | 462 | template < typename T > 463 | void TinyDecisionTreeClassifier::qsort(T *ar, uint32_t n) 464 | { 465 | if (n < 2) 466 | return; 467 | T p = ar[n / 2]; 468 | T *l = ar; 469 | T *r = ar + n - 1; 470 | while (l <= r) { 471 | if (*l < p) { 472 | l++; 473 | } 474 | else if (*r > p) { 475 | r--; 476 | } 477 | else { 478 | T t = *l; 479 | *l = *r; 480 | *r = t; 481 | l++; 482 | r--; 483 | } 484 | } 485 | qsort(ar, r - ar + 1); 486 | qsort(l, ar + n - l); 487 | } 488 | 489 | template < typename T > 490 | void TinyDecisionTreeClassifier::qsort(T *ar, uint32_t *idx, uint32_t n) 491 | { 492 | if (n < 2) 493 | return; 494 | T p = ar[n / 2]; 495 | T *l = ar; 496 | T *r = ar + n - 1; 497 | uint32_t *li = idx; 498 | uint32_t *ri = idx + n - 1; 499 | 500 | 501 | while (l <= r) { 502 | if (*l < p) { 503 | l++; 504 | li++; 505 | } 506 | else if (*r > p) { 507 | r--; 508 | ri--; 509 | } 510 | else { 511 | T t = *l; 512 | *l = *r; 513 | *r = t; 514 | l++; 515 | r--; 516 | uint32_t ti = *li; 517 | *li = *ri; 518 | *ri = ti; 519 | li++; 520 | ri--; 521 | } 522 | } 523 | qsort(ar, idx, r - ar + 1); 524 | qsort(l, li, ar + n - l); 525 | } 526 | 527 | template < typename T > 528 | T TinyDecisionTreeClassifier::getMajorClass(UniqueValues* uv){ 529 | uint32_t maxOcc=0; 530 | uint32_t maxOccIdx=0; 531 | uint32_t i; 532 | for(i=0;iuniqueValuesSize;i++){ 533 | if(uv->uniqueValuesOccurances[i]>maxOcc){ 534 | maxOcc=uv->uniqueValuesOccurances[i]; 535 | maxOccIdx=i; 536 | } 537 | } 538 | return uv->uniqueValues[maxOccIdx]; 539 | } 540 | 541 | template < typename T > 542 | T TinyDecisionTreeClassifier::Node::decide(T* X){ 543 | if(decisionReady)return decision; 544 | else{ 545 | if(thReady){ 546 | if(children[0]!=NULL){ 547 | if(X[nodeThColumn]<=nodeTh){ 548 | return children[0]->decide(X); 549 | }else{ 550 | return children[1]->decide(X); 551 | } 552 | } 553 | else{ 554 | DTR_DEBUG_PRINTLN("Warning node have no children and no decision,returning 0"); 555 | return 0; 556 | } 557 | } 558 | else{ 559 | DTR_DEBUG_PRINTLN("Warning node have no threhold and no decision,returning 0"); 560 | return 0; 561 | } 562 | } 563 | } 564 | 565 | template < typename T > 566 | void TinyDecisionTreeClassifier::Node::decideBasedOnPreLeafNode(T *X,NodeDecisionPair* ndp){ 567 | if(decisionReady){ 568 | ndp->decision = decision; 569 | ndp->nodePtr = NULL; 570 | } 571 | else{ 572 | if(thReady){ 573 | if(children[0]!=NULL && children[1]!=NULL){ 574 | if(children[0]->children[0] == NULL && children[0]->children[1] == NULL && children[1]->children[0] == NULL && children[1]->children[1] == NULL){ 575 | DTR_DEBUG_PRINT("Node "); 576 | DTR_DEBUG_PRINT((uint32_t) this); 577 | DTR_DEBUG_PRINT("(Y="); 578 | DTR_DEBUG_PRINT(decision); 579 | DTR_DEBUG_PRINT(",th="); 580 | DTR_DEBUG_PRINT(nodeTh); 581 | DTR_DEBUG_PRINT("): "); 582 | // #endif 583 | ndp->decision = decision; 584 | ndp->nodePtr = this; 585 | }else{ 586 | if(children[0]!=NULL){ 587 | if(X[nodeThColumn]<=nodeTh){ 588 | children[0]->decideBasedOnPreLeafNode(X,ndp); 589 | }else{ 590 | children[1]->decideBasedOnPreLeafNode(X,ndp); 591 | } 592 | } 593 | } 594 | }else{ 595 | DTR_DEBUG_PRINTLN("Warning, node has no children and no decision, or just one child"); 596 | } 597 | } 598 | else{ 599 | DTR_DEBUG_PRINTLN("Warning, node has no threhold and no decision"); 600 | } 601 | } 602 | } 603 | 604 | template < typename T > 605 | void TinyDecisionTreeClassifier::Node::cleanup(){ 606 | if(children[0]!=NULL){ 607 | for(uint32_t i=0;i<2;i++){ 608 | children[i]->cleanup(); 609 | delete children[i]; 610 | decisionReady=true; 611 | thReady=false; 612 | children[i] = NULL; 613 | } 614 | } 615 | } 616 | 617 | template < typename T > 618 | T TinyDecisionTreeClassifier::predictBasedOnPreLeafNode(T *X,typename Node::NodeDecisionPair* ndp){ 619 | if(root==NULL)return 0; 620 | root->decideBasedOnPreLeafNode(X,ndp); 621 | return 0; 622 | } 623 | 624 | template < typename T > 625 | bool TinyDecisionTreeClassifier::prune(T** X,T** Y,uint32_t rows){ 626 | bool prunedSuccess = false; 627 | Node** nodesUnderPruning = NULL; 628 | int32_t* nodesUnderPruningLeavesScore = NULL; 629 | uint32_t nodesUnderPruningLen = 0; 630 | DTR_DEBUG_PRINTLN("Cost-complexity pruning start"); 631 | 632 | for(uint32_t i=0;icleanup(); 737 | } 738 | } 739 | free(nodesUnderPruning); 740 | free(nodesUnderPruningLeavesScore); 741 | return prunedSuccess; 742 | } 743 | 744 | template < typename T > 745 | int32_t TinyDecisionTreeClassifier::getRootLine(Node* node,int32_t linenow){ 746 | if(node->decisionReady){ 747 | linenow = linenow + 1; 748 | return linenow; 749 | } 750 | if(node->thReady){ 751 | int32_t lineofnode0 = getRootLine(node->children[0],linenow); 752 | int32_t lineofnode1 = getRootLine(node->children[1],lineofnode0); 753 | return (lineofnode1+1); 754 | } 755 | return linenow; 756 | } 757 | 758 | template < typename T > 759 | int32_t TinyDecisionTreeClassifier::nodesToChar(char* outdata, uint32_t* outdataOffset, Node* node,int32_t linenow){ 760 | if(node->decisionReady){ 761 | (*outdataOffset)+=sprintf(outdata+(*outdataOffset),"n,-1,%ld,-1,-1\n",(int32_t)node->decision); 762 | linenow = linenow + 1; 763 | return linenow; 764 | } 765 | if(node->thReady){ 766 | int32_t lineofnode0 = nodesToChar(outdata,outdataOffset,node->children[0],linenow); 767 | int32_t lineofnode1 = nodesToChar(outdata,outdataOffset,node->children[1],lineofnode0); 768 | (*outdataOffset)+=sprintf(outdata+(*outdataOffset),"n,%lu,%f,%ld,%ld\n",node->nodeThColumn,(double)node->nodeTh,lineofnode0-1,lineofnode1-1); 769 | return (lineofnode1+1); 770 | } 771 | return linenow; 772 | } 773 | 774 | template < typename T > 775 | int TinyDecisionTreeClassifier::save(char** outdata, uint32_t* outdataMaxSize){ 776 | uint32_t outdataOffset=0; 777 | uint32_t linenow = 0; 778 | int32_t rootline=0; 779 | if(root!=NULL){ 780 | rootline = getRootLine(root,rootline)-1; 781 | outdataOffset+=sprintf(*outdata,"r,%ld\n",rootline); 782 | if((outdataOffset+100)>(*outdataMaxSize)){ 783 | (*outdataMaxSize)+=100; 784 | *outdata = (char*)realloc(*outdata,(*outdataMaxSize)); 785 | } 786 | nodesToChar(*outdata,&outdataOffset,root,linenow); 787 | (*outdata)[outdataOffset]=0; 788 | } 789 | return 0; 790 | } 791 | 792 | template < typename T > 793 | void TinyDecisionTreeClassifier::buildDescendents(Node* ptr,int32_t index,float** nodesData){ 794 | if(nodesData[index][0]!=-1){ 795 | ptr->decisionReady=false; 796 | ptr->nodeThColumn=(uint32_t)nodesData[index][0]; 797 | ptr->nodeTh=nodesData[index][1]; 798 | ptr->thReady=true; 799 | 800 | if(nodesData[index][2]!=-1){ 801 | ptr->children[0]=(Node*)malloc(sizeof(Node)); 802 | buildDescendents(ptr->children[0],(int32_t )nodesData[index][2],nodesData); 803 | } 804 | else ptr->children[0]=NULL; 805 | if(nodesData[index][3]!=-1){ 806 | ptr->children[1]=(Node*)malloc(sizeof(Node)); 807 | buildDescendents(ptr->children[1],(int32_t )nodesData[index][3],nodesData); 808 | } 809 | else ptr->children[1]=NULL; 810 | }else{ 811 | ptr->decisionReady=true; 812 | ptr->decision=nodesData[index][1]; 813 | ptr->thReady=false; 814 | ptr->children[0]=NULL; 815 | ptr->children[1]=NULL; 816 | } 817 | } 818 | 819 | template < typename T > 820 | void TinyDecisionTreeClassifier::countNodesAndRoots(uint32_t* roots,uint32_t* nodes,char* data){ 821 | char* newline_position; 822 | char* line_position = data; 823 | int32_t rootline=0; 824 | int32_t feature=0; 825 | *nodes=0; 826 | *roots=0; 827 | while(1){ 828 | newline_position = strchr(line_position, 'r'); 829 | if(newline_position==NULL)break; 830 | sscanf(newline_position,"r,%ld",&rootline); 831 | (*roots)++; 832 | line_position = newline_position+1; 833 | } 834 | line_position = data; 835 | while(1){ 836 | newline_position = strchr(line_position, 'n'); 837 | if(newline_position==NULL)break; 838 | sscanf(newline_position,"n,%ld",&feature); 839 | (*nodes)++; 840 | line_position = newline_position+1; 841 | } 842 | } 843 | template < typename T > 844 | void TinyDecisionTreeClassifier::fillInNodesData(uint32_t* roots,uint32_t* nodes,char* inputdata,float** nodesData,float** rootsData){ 845 | char* newline_position; 846 | char* line_position = inputdata; 847 | uint32_t ctr=0; 848 | uint32_t rootsctr=0; 849 | 850 | while(1){ 851 | int32_t rootline=0; 852 | newline_position = strchr(line_position, 'r'); 853 | if(newline_position==NULL)break; 854 | sscanf(newline_position,"r,%ld",&rootline); 855 | rootsData[rootsctr][0]=rootline; 856 | rootsctr++; 857 | line_position = newline_position+1; 858 | } 859 | line_position = inputdata; 860 | while(1){ 861 | newline_position = strchr(line_position, 'n'); 862 | if(newline_position==NULL)break; 863 | 864 | int32_t feature=0; 865 | float threhold=0; 866 | int32_t left=0; 867 | int32_t right=0; 868 | sscanf(newline_position,"n,%ld,%f,%ld,%ld",&feature,&threhold,&left,&right); 869 | nodesData[ctr][0]=feature; 870 | nodesData[ctr][1]=threhold; 871 | nodesData[ctr][2]=left; 872 | nodesData[ctr][3]=right; 873 | ctr++; 874 | line_position = newline_position+1; 875 | } 876 | } 877 | 878 | template < typename T > 879 | int TinyDecisionTreeClassifier::load(char* inputdata){ 880 | if(root==NULL){ 881 | root = new Node(); 882 | uint32_t nodesSize=0; 883 | uint32_t rootsSize=0; 884 | uint32_t i=0; 885 | countNodesAndRoots(&rootsSize,&nodesSize,inputdata); 886 | if(rootsSize!=1)return -1; 887 | float ** nodesData = (float**)malloc(sizeof(float*)*(nodesSize)); 888 | float ** rootsData = (float**)malloc(sizeof(float*)*(rootsSize)); 889 | for(i=0;i 21 | #include 22 | #include 23 | #include "math.h" 24 | #include "float.h" 25 | 26 | // #define DTR_DEBUG_ 27 | #ifdef ARDUINO 28 | #include "Arduino.h" 29 | #define DTR_PLOT_PRINT(X) Serial.print(X); 30 | #define DTR_PLOT_PRINTLN(X) Serial.println(X); 31 | #define DTR_PLOT_PRINTLN_F(X) Serial.println(X,5); 32 | #define DTR_PLOT_PRINT_F(X) Serial.print(X,5); 33 | #define DTR_PLOT_PRINT_U(X) Serial.print(X); 34 | #ifdef DTR_DEBUG_ 35 | #define DTR_DEBUG_PRINT(X) Serial.print(X); 36 | #define DTR_DEBUG_PRINTLN(X) Serial.println(X); 37 | #else 38 | #define DTR_DEBUG_PRINT(X); 39 | #define DTR_DEBUG_PRINTLN(X); 40 | #endif 41 | #else 42 | #ifdef MBED_H 43 | #include "mbed.h" 44 | #define DTR_PLOT_PRINT(X) printf(X); 45 | #define DTR_PLOT_PRINTLN(X) printf(X);printf("\n\r"); 46 | #define DTR_PLOT_PRINTLN_F(X) printf("%.5f\n\r",X); 47 | #define DTR_PLOT_PRINT_F(X) printf("%.5f",X); 48 | #define DTR_PLOT_PRINT_U(X) printf("%lu",X); 49 | 50 | #ifdef DTR_DEBUG_ 51 | #define DTR_DEBUG_PRINT(X); 52 | #define DTR_DEBUG_PRINTLN(X); 53 | #else 54 | #define DTR_DEBUG_PRINT(X); 55 | #define DTR_DEBUG_PRINTLN(X); 56 | #endif 57 | 58 | #else 59 | #define DTR_DEBUG_PRINT(X); 60 | #define DTR_DEBUG_PRINTLN(X); 61 | #define DTR_PLOT_PRINT(X); 62 | #define DTR_PLOT_PRINTLN(X); 63 | #endif 64 | #endif 65 | 66 | #define CANT_SPLIT_ALL_THE_SAMPLES_HAVE_THE_SAME_VALUE -1 67 | 68 | /** @brief The main classifier class, the tempate T allows changing the datatype of the input data. Also 8-bit MCUs work faster with int8_t data type**/ 69 | template 70 | class TinyDecisionTreeClassifier{ 71 | public: 72 | enum Goodness_criterion 73 | { 74 | INFO_GAIN=0x00, 75 | GINI=0x01, 76 | 77 | }gc; 78 | 79 | /** @brief Used to pass information about which data to work with.**/ 80 | struct RowsSubIndexes 81 | { 82 | uint32_t size=0; 83 | uint32_t* indexes=NULL; 84 | ~RowsSubIndexes(){ 85 | if(indexes)free(indexes); 86 | } 87 | }; 88 | 89 | protected: 90 | 91 | struct UniqueValues 92 | { 93 | T* uniqueValues=NULL; 94 | uint32_t uniqueValuesSize=0; 95 | uint32_t* uniqueValuesOccurances=NULL; 96 | ~UniqueValues(){ 97 | if(uniqueValues)free(uniqueValues); 98 | if(uniqueValuesOccurances)free(uniqueValuesOccurances); 99 | } 100 | }uniqueClassValuesAndOccurances; 101 | 102 | /** @brief Compute Shannon's entropy. 103 | * @param Y Input column. 104 | * @param rowsToProcess Which rows to process. 105 | **/ 106 | float computeEntropy(T** Y,RowsSubIndexes* rowsToProcess); 107 | 108 | /** @brief Compute Gini impurity entropy. 109 | * @param Y Input column. 110 | * @param rowsToProcess Which rows to process. 111 | **/ 112 | float computeGini(T** Y,RowsSubIndexes* rowsToProcess); 113 | 114 | /** @brief Returns the most frequent class. 115 | * @param uv A pointer to array of data to sort. 116 | **/ 117 | T getMajorClass(UniqueValues* uv); 118 | 119 | /** @brief Checks how many unique values does the columm have. Used to calculate Shannons entropy. 120 | * @param ar All the input data. 121 | * @param rsi Which rows to process. 122 | * @param column Which column to process. 123 | * @param uv A pointer to the output variable to fill in the data. 124 | **/ 125 | void countUniqueValuesAndOccurances(T** ar, RowsSubIndexes* rsi, uint32_t column, UniqueValues* uv); 126 | 127 | /** @brief Checks how many unique values does the columm have. Used to calculate Shannons entropy. 128 | * @param ar All the input data. 129 | * @param rsi Which rows to process. 130 | * @param column Which column to process. 131 | * @param uv A pointer to the output variable to fill in the data. 132 | **/ 133 | void countOccurances(T** ar, RowsSubIndexes* rsi, uint32_t column, UniqueValues* uv); 134 | 135 | /** @brief Checks If only one class is left in the column, should be called after counting. 136 | * @param uv A pointer to the output variable to fill in the data. 137 | **/ 138 | bool onlyClassLeft(UniqueValues* uv); 139 | 140 | /** @brief Quicksort is used for sorting the data to split the data by threholds. The data are sorted in place. 141 | * @param ar A pointer to array of data to sort. 142 | * @param n Array size 143 | **/ 144 | void qsort(T * ar,uint32_t n); 145 | 146 | /** @brief Quicksort is used for sorting the data to split the data by threholds. The data are sorted in place. 147 | * @param ar A pointer to array of data to sort. 148 | * @param n Array size 149 | * @param idx Pointer to an array of indices, that describes which index ended up where after the sort 150 | **/ 151 | void qsort(T * ar, uint32_t* idx,uint32_t n); 152 | 153 | /** @brief Generates the split that maximizes information gain. 154 | * @param X Input samples. 155 | * @param Y Input classes. 156 | * @param rowsToProcess Which rows to process. 157 | * @param cols Total number of input samples columns (basically the number of input features). 158 | * @param rsiAboveTh Output variable, rows above threhold 159 | * @param rsiBelowTh Output variable, rows below threhold 160 | * @param threshold Output variable, a pointer to the best threhold.(returned after method ends) 161 | * @param column Output variable, a column of the best split(returned after method ends) 162 | **/ 163 | int16_t getBestSplitInfoGain(T** X,T** Y, RowsSubIndexes* rowsToProcess, uint32_t cols, RowsSubIndexes* rsiAboveTh, RowsSubIndexes* rsiBelowTh, T* threshold, uint32_t* column); 164 | 165 | /** @brief Generates the split that minimizes Gini impurity. 166 | * @param X Input samples. 167 | * @param Y Input classes. 168 | * @param rowsToProcess Which rows to process. 169 | * @param cols Total number of input samples columns (basically the number of input features). 170 | * @param rsiAboveTh Output variable, rows above threhold 171 | * @param rsiBelowTh Output variable, rows below threhold 172 | * @param threshold Output variable, a pointer to the best threhold.(returned after method ends) 173 | * @param column Output variable, a column of the best split(returned after method ends) 174 | **/ 175 | int16_t getBestSplitGini(T** X,T** Y, RowsSubIndexes* rowsToProcess, uint32_t cols, RowsSubIndexes* rsiAboveTh, RowsSubIndexes* rsiBelowTh, T* threshold, uint32_t* column); 176 | 177 | public: 178 | uint16_t maxDepth; 179 | uint16_t minSamplesSplit; 180 | uint16_t cols; 181 | 182 | /** @brief Nested node class**/ 183 | class Node{ 184 | public: 185 | 186 | /** @brief Child nodes.**/ 187 | Node* children[2] = {NULL,NULL}; 188 | bool decisionReady = false; 189 | T decision; 190 | struct NodeDecisionPair{ 191 | T decision; 192 | Node* nodePtr=NULL; 193 | }; 194 | 195 | bool thReady = false; 196 | T nodeTh; 197 | uint32_t nodeThColumn; 198 | 199 | /** @brief Recursively builds the tree, generating the best split by maximizing information gain. 200 | * @param minSamplesSplit If the number of samples is less than this number the splitting process stops. 201 | * @param maxDepth Maximum possible depth of a tree. 202 | **/ 203 | Node(void); 204 | 205 | /** @brief Recursively make a decision about the output class. 206 | * @param X Input sample. 207 | **/ 208 | T decide(T *X); 209 | 210 | /** @brief Recursively make a decision about the output class, but use a pre-leaf node decision instead of leaf. Used for cost complexity pruning. 211 | * @param X Input sample. 212 | **/ 213 | void decideBasedOnPreLeafNode(T *X,NodeDecisionPair* ndp); 214 | 215 | /** @brief Recursively destroys the nodes and deallocates the memory**/ 216 | void cleanup(void); 217 | }; 218 | 219 | Node* root; 220 | 221 | /** @brief The class constructor. 222 | * @param minSamplesSplit If the number of samples is less than this number the splitting process stops. 223 | * @param maxDepth Maximum possible depth of a tree. 224 | **/ 225 | TinyDecisionTreeClassifier(uint16_t maxDepth, uint16_t minSamplesSplit = 2,Goodness_criterion gc=INFO_GAIN); 226 | 227 | /** @brief The class destructor.Cleans all the memory 228 | **/ 229 | ~TinyDecisionTreeClassifier(); 230 | 231 | /** @brief Recursively plots the tree. 232 | * @param node Pointer to the root node. 233 | * @param depth Current depth. 234 | **/ 235 | void plot(Node* node,uint32_t depth); 236 | 237 | /** @brief Recursively plots the tree.**/ 238 | void plot(); 239 | 240 | /** @brief Recursively builds the tree, generating the best split by maximizing information gain. 241 | * @param X Input samples. 242 | * @param Y Input classes. 243 | * @param rsi Indicies of rows to work with. 244 | * @param cols Total number of input samples columns (basically the number of input features). 245 | * @param current_depth Since the method is called recursively this argument tracks the current depth. 246 | **/ 247 | int16_t recurcisiveFit(Node* node, T** X,T** Y, RowsSubIndexes* rsi, uint32_t cols, uint32_t current_depth); 248 | 249 | /** @brief Fits the tree to input data. 250 | * @param X Input samples. 251 | * @param Y Input classes. 252 | * @param rows Number or samples. 253 | * @param Xcols Number of features. 254 | * **/ 255 | void fit(T** X,T** Y, uint32_t rows,uint32_t Xcols, RowsSubIndexes* rootRsi=NULL); 256 | 257 | /** @brief Classifies the input. The tree should be trained using fit method first. 258 | * @param X Input samples. 259 | * **/ 260 | T predict(T* X); 261 | 262 | /** @brief Checks the accuracy of trained tree. 263 | * @param X Input samples. 264 | * @param Y Input features. 265 | * @param rows Number of samples 266 | * **/ 267 | float score(T** X,T** Y,uint32_t rows); 268 | 269 | /** @brief Classifies the data, but uses pre-leaf value instead of leaf value. Used for cost-complexity pruning. 270 | * @param X A pointer to array of data to classify. 271 | * @param ndp Decision and Node address pair. 272 | **/ 273 | T predictBasedOnPreLeafNode(T *X,typename Node::NodeDecisionPair* ndp); 274 | 275 | /** @brief Prunes the decision tree. Cost-complexity pruning is used 276 | * @param X Input samples. 277 | * @param Y Input features. 278 | * @param rows Number of samples 279 | * @return True if at least one node was removed as a result of pruning, false otherwise 280 | * **/ 281 | bool prune(T** X,T** Y,uint32_t rows); 282 | 283 | /** @brief Saves the decision tree to file. 284 | * @param outdata output array. 285 | * @param outdataMaxSize the maximum size that can be occupied. 286 | * **/ 287 | int save(char** outdata, uint32_t* outdataMaxSize); 288 | 289 | /** @brief Loads the decision tree from file. 290 | * @param inputdata char array with the saved tree. 291 | * **/ 292 | int load(char* inputdata); 293 | 294 | private: 295 | int32_t getRootLine(Node* node,int32_t linenow); 296 | 297 | int32_t nodesToChar(char* outdata, uint32_t* outdataOffset, Node* node,int32_t linenow); 298 | 299 | void countNodesAndRoots(uint32_t* roots,uint32_t* nodes,char* data); 300 | 301 | void fillInNodesData(uint32_t* roots,uint32_t* nodes,char* inputdata,float** nodesData,float** rootsData); 302 | 303 | void buildDescendents(Node* ptr,int32_t index,float** nodesData); 304 | 305 | }; 306 | 307 | #include "TinyDecisionTreeClassifier.cpp" 308 | 309 | #endif --------------------------------------------------------------------------------