{"id":15288206,"url":"https://github.com/albarsil/geneticml","last_synced_at":"2025-04-13T07:38:47.350Z","repository":{"id":43655757,"uuid":"434600363","full_name":"albarsil/geneticml","owner":"albarsil","description":"A simple and lightweight genetic algorithm for optimization of any machine learning model","archived":false,"fork":false,"pushed_at":"2022-03-02T13:38:31.000Z","size":62,"stargazers_count":8,"open_issues_count":2,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-26T23:42:48.284Z","etag":null,"topics":["automl","data-science","genetic-algorithm","machine-learning"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/albarsil.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null}},"created_at":"2021-12-03T13:09:25.000Z","updated_at":"2022-08-10T17:31:03.000Z","dependencies_parsed_at":"2022-08-28T04:41:29.954Z","dependency_job_id":null,"html_url":"https://github.com/albarsil/geneticml","commit_stats":null,"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/albarsil%2Fgeneticml","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/albarsil%2Fgeneticml/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/albarsil%2Fgeneticml/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/albarsil%2Fgeneticml/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/albarsil","download_url":"https://codeload.github.com/albarsil/geneticml/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248680138,"owners_count":21144614,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["automl","data-science","genetic-algorithm","machine-learning"],"created_at":"2024-09-30T15:44:42.180Z","updated_at":"2025-04-13T07:38:47.241Z","avatar_url":"https://github.com/albarsil.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# geneticml\n\n[![Actions Status](https://github.com/albarsil/geneticml/workflows/Tests/badge.svg?branch=main)](https://github.com/albarsil/geneticml/actions/workflows/tests.yml)\n[![CodeQL](https://github.com/albarsil/geneticml/workflows/CodeQL/badge.svg?branch=main)](https://github.com/albarsil/geneticml/actions?query=workflow%3ACodeQL)\n[![PyPI](https://img.shields.io/pypi/v/geneticml?color=g)](https://pypi.org/project/geneticml/)\n[![License](https://img.shields.io/badge/license-MIT-purple)](https://github.com/albarsil/geneticml/blob/master/LICENSE)\n\nThis package contains a simple and lightweight genetic algorithm for optimization of any machine learning model.\n\n## Installation\n\nUse pip to install the package from PyPI:\n\n```bash\npip install geneticml\n```\n\n## Usage\n\nThis package provides a easy way to create estimators and perform the optimization with genetic algorithms. The example below describe in details how to create a simulation with genetic algorithms using evolutionary approach to train a `sklearn.neural_network.MLPClassifier`. A full list of examples could be found [here](https://github.com/albarsil/geneticml/tree/main/examples).\n\n\n```python\nfrom geneticml.algorithms import (DataLoader, DefaultEstimatorMethods,EstimatorBuilder)\nfrom geneticml.optimizers import GeneticOptimizer\nfrom geneticml.strategy import EvolutionaryStrategy, StrategyParameters\nimport sklearn.metrics as metrics\nfrom sklearn.datasets import load_iris\nfrom sklearn.exceptions import ConvergenceWarning, UndefinedMetricWarning\nfrom sklearn.neural_network import MLPClassifier\n\nif __name__ == \"__main__\":\n\n    seed = 11412\n\n    # Creates an estimator\n    estimator = EstimatorBuilder()\\\n        .of(model_type=MLPClassifier)\\\n        .fit_with(DefaultEstimatorMethods.fit)\\\n        .predict_with(DefaultEstimatorMethods.predict)\\\n        .build()\n\n    # Defines a strategy for the optimization\n    strategy = EvolutionaryStrategy(\n        estimatort=estimator,\n        parameters=parameters,\n        retain=0.4,\n        random_select=0.1,\n        mutate_chance=0.2,\n        max_children=2,\n        random_state=seed\n    )\n\n    # Creates the optimizer\n    optimizer = GeneticOptimizer(strategy=strategy)\n\n    # Loads the data\n    data = load_iris()\n\n    # Defines the metric\n    greater_is_better = True\n\n    # Create the simulation using the optimizer and the strategy\n    models = optimizer.simulate(\n        train_data=DataLoader(data=data.data, target=data.target),\n        generations=generations,\n        population=population,\n        evaluation_function=metrics.accuracy_score,\n        greater_is_better=greater_is_better,\n        verbose=True\n    )\n```\n\nThe estimator is the way you define an algorithm or a class that will be used for model instantiation\n\n```python\nestimator = EstimatorBuilder().of(model_type=MLPClassifier).fit_with(func=fit).predict_with(func=predict).build()\n```\n\nYou can use the default functions provided by the `geneticml.algorithms.DefaultEstimatorMethods` or you can speficy your own functions to perform the operations. If you want to create your own, please note that these functions need to use the same signature than the below ones. This happens because the algorithm is generic and needs to know how to perform the fit and predict functions for the models.\n\n```python\n# Creates a custom fit method\ndef fit(model, x, y):\n    return model.fit(x, y)\n\n# Creates a custom predict method\ndef predict(model, x):\n    return model.predict(x)\n```\n\n## Custom strategy\n\nYou can create custom strategies for the optimizers by extending the `geneticml.strategy.BaseStrategy` and implementing the `execute(...)` function.\n\n```python\nclass MyCustomStrategy(BaseStrategy):\n    def __init__(self, estimator_type: Type[BaseEstimator]) -\u003e None:\n        super().__init__(estimator_type)\n\n    def execute(self, population: List[Type[T]]) -\u003e List[T]:\n        return population\n```\n\nThe custom strategies will allow you to create optimization strategies to archive your goals. We currently have the evolutionary strategy but you can define your own :)\n\n## Custom optimizer\n\nYou can create custom optimizers by extending the `geneticml.optimizers.BaseOptimizer` and implementing the `simulate(...)` function.\n\n```python\nclass MyCustomOptimizer(BaseOptimizer):\n    def __init__(self, strategy: Type[BaseStrategy]) -\u003e None:\n        super().__init__(strategy)\n\n    def simulate(self, data, target, verbose: bool = True) -\u003e List[T]:\n        \"\"\"\n        Generate a network with the genetic algorithm.\n\n        Parameters:\n            data (?): The data used to train the algorithm\n            target (?): The targets used to train the algorithm\n            verbose (bool): True if should verbose or False if not\n\n        Returns:\n            (List[BaseEstimator]): A list with the final population sorted by their loss\n        \"\"\"\n        estimators = self._strategy.create_population()\n        for x in estimators:\n            x.fit(data, target)\n            y_pred = x.predict(target)\n        pass \n```\n\nCustom optimizers will let you define how you want your algorithm to optimize the selected strategy. You can also combine custom strategies and optimizers to archive your desire objective.\n\n\n## Testing\n\nThe following are the steps to create a virtual environment into a folder named \"venv\" and install the requirements.\n\n```bash\n# Create virtualenv\npython3 -m venv venv\n# activate virtualenv\nsource venv/bin/activate\n# update packages\npip install --upgrade pip setuptools wheel\n# install requirements\npython setup.py install\n```\n\nTests can be run with `python setup.py test` when the virtualenv is active.\n\n# Contributing\nAll contributions, bug reports, bug fixes, documentation improvements, enhancements, and ideas are welcome.\n\nA detailed overview on how to contribute can be found in the contributing guide. There is also an overview on GitHub.\n\nIf you are simply looking to start working with the geneticml codebase, navigate to the GitHub \"issues\" tab and start looking through interesting issues. Or maybe through using geneticml you have an idea of your own or are looking for something in the documentation and thinking ‘this can be improved’...you can do something about it!\n\nFeel free to ask questions on the mailing the contributors.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falbarsil%2Fgeneticml","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falbarsil%2Fgeneticml","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falbarsil%2Fgeneticml/lists"}