├── README.md ├── CONTRIBUTING.md ├── CODE_OF_CONDUCT.md ├── symbolic_regeression.py └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | **Please note:** The code in these repos is sourced from the DataRobot user community and is not owned or maintained by DataRobot, Inc. You may need to make edits or updates for this code to function properly in your environment. 2 | 3 | # Symbolic Regression from Scratch with Python 4 | 5 | This repository contains Python code to accompany the article _Symbolic Regression from Scratch with Python_. 6 | The code implements a basic symbolic regression system which uses genetic programming to 7 | find a program that describes the relationship between some features and a target variable. 8 | More specifically, this code uses the ["Auto MPG Data Set" from UCI](http://archive.ics.uci.edu/ml/datasets/Auto%2BMPG) 9 | to find a relationship between vehicle characteristics and **mpg** (miles per gallon). 10 | 11 | ## Depedencies 12 | - Pandas 13 | - auto-mpg.data 14 | 15 | ## Usage 16 | 17 | ```python symbolic_regression.py``` 18 | 19 | ## Setup/Installation 20 | ``` 21 | pip install python 22 | wget http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data 23 | ``` 24 | 25 | ## Development and Contributing 26 | 27 | If you'd like to report an issue or bug, suggest improvements, or contribute code to this project, please refer to [CONTRIBUTING.md](CONTRIBUTING.md). 28 | 29 | 30 | # Code of Conduct 31 | 32 | This project has adopted the Contributor Covenant for its Code of Conduct. 33 | See [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) to read it in full. 34 | 35 | # License 36 | 37 | Licensed under the Apache License 2.0. 38 | See [LICENSE](LICENSE) to read it in full. 39 | 40 | 41 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Guidelines for developing and contributing to this project. 4 | 5 | ## List of project maintainers 6 | 7 | - [Glen Koundry](https://github.com/gkoundry) 8 | 9 | ## Opening new issues 10 | 11 | - Before opening a new issue check if there are any existing FAQ entries (if one exists), issues or pull requests that match your case 12 | - Open an issue, and make sure to label the issue accordingly - bug, improvement, feature request, etc... 13 | - Be as specific and detailed as possible 14 | 15 | 16 | ## Setting up the development environment 17 | 18 | - Install pandas 19 | - Download [example dataset](http://archive.ics.uci.edu/ml/datasets/Auto%2BMPG) 20 | - Checkout the project 21 | 22 | ## Project structure 23 | 24 | - Currently there is one script in the top level folder 25 | 26 | ## Making a pull request 27 | 28 | - Have a branch with a descriptive name 29 | - Squash / rebase your commits before opening your pull request 30 | - Pull the latest changes from `master` 31 | - Provide sufficient description of the pull request. Include whether it relates to an existing issue, and specify what the pull request does - (bug fix, documentation correction, dependency update, new functionality, etc...). When in doubt, overcommunicate 32 | 33 | ## Responding to issues and pull requests 34 | 35 | This project's maintainers will make every effort to respond to any open issues as soon as possible. 36 | 37 | If you don't get a response within 7 days of creating your issue or pull request, please send us an email at community@datarobot.com. 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at community@datarobot.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /symbolic_regeression.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | # Read in data 4 | data = pd.read_csv( 5 | "auto-mpg.data", delim_whitespace=True, na_values="?", header=None, 6 | names=["mpg", "cylinders", "displacement", "horsepower", "weight", 7 | "acceleration", "model year", "origin", "car name", ]) 8 | # Drop string feature 9 | data.pop("car name") 10 | # Replace N/A values in horsepower 11 | data["horsepower"].fillna(data["horsepower"].median(), inplace=True) 12 | # Separate target feature 13 | target = data.pop("mpg") 14 | 15 | import operator 16 | 17 | val1 = {"feature_name": "horsepower"} 18 | val2 = {"feature_name": "cylinders"} 19 | val3 = {"feature_name": "weight"} 20 | node1 = { 21 | "func": operator.add, 22 | "children": [val1, val2], 23 | "format_str": "({} + {})", 24 | } 25 | program = { 26 | "func": operator.mul, 27 | "children": [node1, val3], 28 | "format_str": "({} * {})", 29 | } 30 | 31 | def render_prog(node): 32 | if "children" not in node: 33 | return node["feature_name"] 34 | return node["format_str"].format(*[render_prog(c) for c in node["children"]]) 35 | 36 | print(render_prog(program)) 37 | 38 | def evaluate(node, row): 39 | if "children" not in node: 40 | return row[node["feature_name"]] 41 | return node["func"](*[evaluate(c, row) for c in node["children"]]) 42 | 43 | print(evaluate(program, data.iloc[0])) 44 | 45 | def safe_div(a, b): 46 | return a / b if b else a 47 | 48 | operations = ( 49 | {"func": operator.add, "arg_count": 2, "format_str": "({} + {})"}, 50 | {"func": operator.sub, "arg_count": 2, "format_str": "({} - {})"}, 51 | {"func": operator.mul, "arg_count": 2, "format_str": "({} * {})"}, 52 | {"func": safe_div, "arg_count": 2, "format_str": "({} / {})"}, 53 | {"func": operator.neg, "arg_count": 1, "format_str": "-({})"}, 54 | ) 55 | 56 | from random import randint, random, seed 57 | 58 | seed(0) 59 | 60 | def random_prog(depth): 61 | # favor adding function nodes near the tree root and 62 | # leaf nodes as depth increases 63 | if randint(0, 10) >= depth * 2: 64 | op = operations[randint(0, len(operations) - 1)] 65 | return { 66 | "func": op["func"], 67 | "children": [random_prog(depth + 1) for _ in range(op["arg_count"])], 68 | "format_str": op["format_str"], 69 | } 70 | else: 71 | return {"feature_name": data.columns[randint(0, data.shape[1] - 1)]} 72 | 73 | 74 | POP_SIZE = 300 75 | population = [random_prog(0) for _ in range(POP_SIZE)] 76 | 77 | print(render_prog(population[0])) 78 | 79 | def select_random_node(selected, parent, depth): 80 | if "children" not in selected: 81 | return parent 82 | # favor nodes near the root 83 | if randint(0, 10) < 2*depth: 84 | return selected 85 | child_count = len(selected["children"]) 86 | return select_random_node( 87 | selected["children"][randint(0, child_count - 1)], 88 | selected, depth+1) 89 | 90 | print(render_prog(select_random_node(program, None, 0))) 91 | 92 | from copy import deepcopy 93 | 94 | def do_mutate(selected): 95 | offspring = deepcopy(selected) 96 | mutate_point = select_random_node(offspring, None, 0) 97 | child_count = len(mutate_point["children"]) 98 | mutate_point["children"][randint(0, child_count - 1)] = random_prog(0) 99 | return offspring 100 | 101 | 102 | print(render_prog(do_mutate(program))) 103 | 104 | def do_xover(selected1, selected2): 105 | offspring = deepcopy(selected1) 106 | xover_point1 = select_random_node(offspring, None, 0) 107 | xover_point2 = select_random_node(selected2, None, 0) 108 | child_count = len(xover_point1["children"]) 109 | xover_point1["children"][randint(0, child_count - 1)] = xover_point2 110 | return offspring 111 | 112 | 113 | print(render_prog(do_xover(population[0], population[1]))) 114 | 115 | TOURNAMENT_SIZE = 3 116 | 117 | def get_random_parent(population, fitness): 118 | # randomly select population members for the tournament 119 | tournament_members = [ 120 | randint(0, POP_SIZE - 1) for _ in range(TOURNAMENT_SIZE)] 121 | # select tournament member with best fitness 122 | member_fitness = [(fitness[i], population[i]) for i in tournament_members] 123 | return min(member_fitness, key=lambda x: x[0])[1] 124 | 125 | XOVER_PCT = 0.7 126 | 127 | def get_offspring(population, fitness): 128 | parent1 = get_random_parent(population, fitness) 129 | if random() > XOVER_PCT: 130 | parent2 = get_random_parent(population, fitness) 131 | return do_xover(parent1, parent2) 132 | else: 133 | return do_mutate(parent1) 134 | 135 | REG_STRENGTH = 0.5 136 | 137 | def node_count(x): 138 | if "children" not in x: 139 | return 1 140 | return sum([node_count(c) for c in x["children"]]) 141 | 142 | 143 | def compute_fitness(program, prediction): 144 | mse = ((pd.Series(prediction) - target) ** 2).mean() 145 | penalty = node_count(program) ** REG_STRENGTH 146 | return mse * penalty 147 | 148 | MAX_GENERATIONS = 10 149 | 150 | global_best = float("inf") 151 | for gen in range(MAX_GENERATIONS): 152 | fitness = [] 153 | for prog in population: 154 | prediction = [ 155 | evaluate(prog, row) for _, row in data.iterrows()] 156 | score = compute_fitness(prog, prediction) 157 | fitness.append(score) 158 | if score < global_best: 159 | global_best = score 160 | best_pred = prediction 161 | best_prog = prog 162 | print( 163 | "Generation: %d\nBest Score: %.2f\nMedian score: %.2f\nBest program: %s\n" 164 | % ( 165 | gen, 166 | global_best, 167 | pd.Series(fitness).median(), 168 | render_prog(best_prog), 169 | ) 170 | ) 171 | population = [ 172 | get_offspring(population, fitness) 173 | for _ in range(POP_SIZE)] 174 | 175 | print("Best score: %f" % global_best) 176 | print("Best program: %s" % render_prog(best_prog)) 177 | output = {"target": target, "pred": best_pred} 178 | pd.DataFrame(output).to_csv("best_pred.csv") 179 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------