Saravanan666/pypi-org huggingface dataset:
Package: genetic-algo
genetic-algoA framework for developing Genetic-Algorithm programs to solve problems dynamically and explicitly.first of allspecifics:writen and owned by: Shahaf Frank-Shapirall the rights are saved for: Shahaf Frank-Shapirprogramming languages: python 3.9.12 (100%)before we startdescription:visit the docs to learn more about this project and how to develop with it.dependencies:opening:
As for this is a really complex program, which uses a lot of modules, there are required dependencies needed
in order to run the program. keep in mined the program was writen in python 3.9, so any python version lower
than 3.8 might not work properly. Moreover, built-in python modules are being used, so keep that in mind.install app dependencies by writing the "-r" option to install the requirements
writen in a file, and write the following line in the project directory:pip install -r requirements.txtrun a testrun from windows command line (inside the project directory)run with python by writing to the command line in the project directory:python test.py
Package: genetic-algorithm
Genetic AlgorithmA black-box optimization package published inpypi.Installationpip install genetic_algorithmExampleThe original example code can be found intest.py.import numpy as np
import matplotlib.pyplot as plt
from genetic_algorithm import GeneticAlgorithmDefine the function to be optimizedx = np.linspace(0, 5, 1000)

ground_truth = x**3 - 2*(x**2) + 1


def func(a,b,c):
return x**a - b*(x**2) + cDeclare the fitness function as the negative RMSE of the predicted
values.def fitness(params):
return -np.sqrt(np.mean((ground_truth-func(**params))**2))The parameter space to be searched should come as a dictionary as follows:param_space = {"a": {'type': 'float', 'range':[0, 5]},
"b": {'type': 'float', 'range':[-1, 5]},
"c": {'type': 'int', 'range':[0, 3]}
}Run genetic algorithm.ga = GeneticAlgorithm(model=fitness,
                    param_space=param_space,
                    pop_size=100,
                    parent_pool_size=10,
                    keep_parent=False,
                    max_iter=100,
                    mutation_prob=0.3,
                    crossover_prob=0.7,
                    max_stop_rounds=5,
                    verbose=False)Get the best parameters as well as the history.result = ga.evolve()
print(result)Visualize the difference between predicted and ground truth data:predicted = func(**result["best params"])
plt.scatter(x, ground_truth, s=3, label="ground truth")
plt.scatter(x, predicted, s=3, c='r', label="predicted")
plt.legend(loc='upper left')
plt.show()population size = 100population size = 500There is still quite some difference between the predicted ones and the ground truth.
If the population size goes 100 to 500, the optimizer is then working better than before. There are other parameters such as
cross-over rate and mutation rate which can also affect the optimization performance.
Package: geneticalgs
geneticalgsImplementation of standard, migration and diffusion models of genetic algorithms (GA) inpython 3.5.Benchmarking was conducted byCOCO platformv15.03.The project summary may be found inproject_summary.pdf.Link toGitHubLink toPyPI.Link toRead The Docs.Implemented featuresstandard, diffusion and migration modelswith real values (searching for global minimum or maximum of the specified function)with binary encoding combination of some input dataold population is completely replaced with a new computed one at the end of each generation (generational population model)two types of fitness value optimalizationminimizationmaximizationthree parent selection typesroulette wheel selectionrank wheel selectiontournamentmay be specified mutation probabilitymay be specified any amount of random bits to be mutatedmay be specified crossover probabilitydifferent types of crossoversingle-pointtwo-pointmultiple point up to uniform crossoverelitism may be turned on/off (the best individual may migrate to the next generation)Content description/geneticalgs/contains source codes/docs/containssphinxsource codes/2.7/contains files converted frompython 3.5topython 2.7using3to2 moduleasCOCO platformused in benchmarking supports only this version of python. These files (not installed packagegeneticalgs) are used in benchmarking. Must be copied in the directory withmy_experiment.pyormy_timing.py./2.7/benchmark/contains the following files:my_experiment.pyis used for running benchmarking. Read morehere.my_timing.pyis used for time complexity measurements. It has the same run conditions as the previous file.pproc.pyis a modified file from COCO platform distribution that must be copied tobbob.v15.03/python/bbob_pproc/in order to post-process measured data of migration GA (other models don’t need it). It is necessary due to unexpected format of records in case of migration GA./benchmarking/contains measured results and the appropriate plots of benchmarking./time_complexity/contains time results measured usingmy_timing.py./examples/contains examples of using the implemented genetic algorithms./tests/containspytesttestsRequirementspython 3.5+NumPybitstringsphinxfor documentationpytestfor testsInstallationInstall package by typing the commandpython-mpip install geneticalgsIf you have problems installing NumPy it isstronglyrecommended to useAnaconda.Running testsYou may run tests by typing from the package directorypython setup.py testDocumentationGo to the package directory and then todocs/and typepip install-rrequirements.txtThen type the following command in order to generate documentation in HTMLmake htmlAnd run doctestmake doctestLicenseLicensed underApache License Version 2.0.
Package: genetic-collections
Genetic CollectionsA Python library for connecting genetic records with specimen data.InstallationThis software requires a working installation of Python 3.5 or higher. Your Python installation should come with a command-line tool called “pip”, which is used to download packages from PyPI, the Python Package Index. Run the command below, and you should be good to go!pipinstallgenetic_collectionsCommand Line UsageThe installation from pip should also install several command line programs that act as wrappers for the code contained here.Here are the available command line tools:ncbi_inst_search$ncbi_inst_search"Smithsonian"6matchingresultsfound.Fetchingbiocollectionentries.[{"Collection Type":"museum","gb_count":20697,"Country":"USA","Institution Code":"USNM","NCBI Link":"https://www.ncbi.nlm.nih.gov/biocollections/53","Institution Name":"National Museum of Natural History, Smithsonian Institution"},{"Collection Type":"herbarium","gb_count":5269,"Country":"USA","Institution Code":"US","NCBI Link":"https://www.ncbi.nlm.nih.gov/biocollections/7399","Institution Name":"Smithsonian Institution, Department of Botany"},...gb_search$gb_search-inst_codeUSNMYoursearchfound20697hitsinGenBankYoucanseeyousearchresultsonlineathttps://www.ncbi.nlm.nih.gov/nuccore/?term=%22collection+USNM%22%5Bprop%5Dgb_fetchbold_inst_searchbold_searchbold_fetchPython Library UsageThe best way to illustrate how the Python library can be used is to view the example workflow in the Jupyter notebook in the “examples” directory.How to contributeImposter syndrome disclaimer: I want your help. No really, I do.There might be a little voice inside that tells you you’re not ready; that you need to do one more tutorial, or learn another framework, or write a few more blog posts before you can help me with this project.I assure you, that’s not the case.This project has some clear Contribution Guidelines and expectations that you can read here (link).The contribution guidelines outline the process that you’ll need to follow to get a patch merged. By making expectations and process explicit, I hope it will make it easier for you to contribute.And you don’t just have to write code. You can help out by writing documentation, tests, or even by giving feedback about this work. (And yes, that includes giving feedback about the contribution guidelines.)Thank you for contributing!Next StepsIncorporate MIXS standardsAdd the ability to translate GenBank and BOLD results to DwC format in order to compareAdd iDigBio and GBIF APIs as data sources for specimen data (and GenBank accessions)Credits“How to contribute” was taken fromhttps://github.com/adriennefriend/imposter-syndrome-disclaimer.This package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.1.0 (2017-10-05)First release on PyPI.
Package: geneticocolor
Genetic Opposite Color (geneticocolor)Geneticocolor is a python package for color sets generation.InstallUsing shell just write the following line:$ pip install geneticocolorHow to useOnce installed, you can import and use the library in any python file.import geneticocolor.color_generator as generator
import matplotlib.pyplot as plt

colors = generator.generate(x, y, point_classes)
plt.scatter(x, y, colors)More about the implementantion
Package: genetic-optimizer
Genetic OptimizerGenetic algorithm optimizer using K-Means clustering with one way ANOVA algorithmsBefore:After:Installation:Use the package managerpipto install genetic_optimizer.pip3installgenetic-optimizerNote:Package require =>Python 3.6.5, using genetic_optimizer in Python 2.x.x projects may not work correctly.
If you are not sure about your python version, try:python3--versionUsageimportgenetic_optimizersome_object=genetic_optimizer.Optimizer()some_object.generate(population_size=46,chromosome_size=8,equal_chromosomes=True,initialization_method='Random',representation='Binary',saving_method='csv')These are default options for generator, you can change them in DEFAULTS.ini file in package directorysome_object.optimize(data=None,iterations=12,shuffle_scale=0.6,variety=0.8,chromosome_weight=0.0000001)These are default options for optimizer, you can change them in STANDARDS.conf file in package directoryNoteIf optimizer got stuck at the beginning, that usually means that your dataframe with population is to small to find appropiate parents in order to create next generations.For more description, please check out project wiki.ProsThere is no mutation and crossover probability. Program matches parents according to group differences and create new child, built from themost successfulpairs of genes from them.
That means new generations are closer to each one and every child isnot worsethatgenetic worseparent.You can play off with options to achive more precised results.ConsFitness and parent selection process takes place recursively. If you are not using some RDD computing, program execution may be longer.ContributingPull requests are welcome.
For major changes, please open an issue first to discuss what you would like to change.LicenseMITToolsmicro editorUnix consoleCode is mostly written in accordance withGoogle PEP style guide
Package: geneticpotion
Генетическое зельеварениеПродукт "Генетическое зельеварение" проект в рамках зимней школыCompTech School 2022НазначениеПродукт "Генетическое зельеварение" в рамках зимней школыCompTech School 2022разрабатывается с целью улучшения работы линейной модели классификации, на основе использования генетического алгоритма.Папки репозиторияdocs- папка, содержащая документацию проекта;main.py- файл, содержащий алгоритм.Обзор продуктаАлгоритм, создающий признаки, которые улучшают результаты работы линейной модели классификации. Данный алгоритм является эффективным способом оптимизации решений с большим числом параметров. Идея заключается в комбинировании существующих параметров, путем создания новых, с возможностью дальнейшей визуализации.Структура продуктаСначала формируется начальное поколение - популяция деревьев.Затем осуществляется селекция, то есть выбор подходящих индивидов на основе fitness-функции.Затем на стадии рекомбинации происходит обмен частями деревьев.На этапе мутаций случайно меняются части деревьев и на выходе получается новая популяция.Если цель не была достигнута, то операции повторяются сначала до ее достижения.ПрименениеЛюбая область, где могут быть применены методы машинного обучения для обработки данных. От банковской сферы до медицины.Может быть применен для решения различных комбинаторных задач, к которым относятся задачи компоновки, задачи на графах и прочие.Применяется для ускорения настройки нейронных сетей.Уcтановка и настройкаПорядок установки и настройки описан в документеруководство пользователяРоли в командеКосарецкий Егор - Data ScientistГераскин Степан - Data ScientistКристина Светова - ВизуализаторШперлинг Софья - Data ScientistВалерия - Data ScientistНовикова Валентина - Технический писательКураторРадеев Никита Андреевич, Machine Learning Engineer,
Новосибирский Исследовательский центр
ООО "Техкомпания Хуавей"
Package: genetic-prompt-compiler
Genetic Prompt CompilerOptimize a prompt for a language model using a genetic algorithm.Installationpipinstallgenetic-prompt-compilerUsageYou can find complete examples in theexamplesfolder.importgenetic_prompt_compilerfromgenetic_prompt_compilerimportGeneticCompilerArgsfromgenetic_prompt_compiler.mutateimportrule_based_mutate,RuleBasedMutateConfig,Techniquefromgenetic_prompt_compiler.rankingimporttop_n_ranking,TopNRankingConfigfromgenetic_prompt_compiler.fitnessimportrule_based_fitness,RuleBasedFitnessConfiginitial_prompt="Answer my question about the universe"rules=["It should be a good answer","It should be factually correct","It should be in english",]test_data["Why is the sky blue?","Who is the president of the United States?","What is the capital of France?",]# The default techniques to use to mutate the promptsDEFAULT_TECHNIQUES=[Technique(prompt="Use the expert technique `You are an expert in{topic}`",presence=0.3,),Technique(prompt="Use the Chain of Thought technique `Let's think step by step...`",presence=0.3,),Technique(prompt="Use some examples `Here are some examples of answers:{examples}`",presence=0.3,),]args=GeneticCompilerArgs(# Mutation function to usemutate=rule_based_mutate,# Ranking function to use, will be used to select the prompts to keep in each generationranking=top_n_ranking,# Fitness function to use, will be used to rank the prompts in each generationfitness=rule_based_fitness,# Ranking function argumentsranking_config=TopNRankingConfig(# Top n prompts to keep in each generationtop_n=5,),mutation_config=RuleBasedMutateConfig(# The llm function to use to mutate the promptsmutation_llm=lambdaq:"",# Rules to generate the mutated prompts onrules=rules,# This is the default techniques used to mutate the prompts, you can omit this argumenttechniques=DEFAULT_TECHNIQUES,),fitnes_config=RuleBasedFitnessConfig(# The llm function to use to rank the promptsfitness_llm=lambdaq:"",# The llm function that you need to optimizestudent=lambdaq:"",# Rules to test the prompts onrules=rules,# The rating notation to use (X/10, X/5 etc.)rating_notation=10,# Test data to test the prompts ontrain_examples=test_data,# Amount of examples to test on prompts in each generationexample_amount=3,),# Amount of prompts to generate in each generationpopultation_size=10,# Amount of generations to runiterations=5,# Initial prompts to start with.# This prompts will be kept for the first generation, alongside propulation_size - len(initial_prompts) mutated versions of itinitial_prompts=[initial_prompt],)forpopulationingenetic_prompt_compiler.run(args):print(f"Top prompts:")forpromptinpopulation:print(f"\t-{prompt}")
Package: geneticpy
GeneticPyGeneticPy is an optimizer that uses a genetic algorithm to quickly search through custom parameter spaces for optimal solutions.InstallationGeneticPy requires Python 3.7+pipinstallgeneticpyOptimize Example:A brief example to get you started is included below:importgeneticpydefloss_function(params):ifparams['type']=='add':returnparams['x']+params['y']elifparams['type']=='multiply':returnparams['x']*params['y']param_space={'type':geneticpy.ChoiceDistribution(choice_list=['add','multiply']),'x':geneticpy.UniformDistribution(low=5,high=10,q=1),'y':geneticpy.GaussianDistribution(mean=0,standard_deviation=1)}results=geneticpy.optimize(loss_function,param_space,size=200,generation_count=500,verbose=True)best_params=results['top_params']loss=results['top_score']total_time=results['total_time']GeneticSearchCV Example:You can use theGeneticSearchCVclass as a drop-in replacement for Scikit-Learn'sGridSearchCV. This
allows for faster and more complete optimization of your hyperparameters when using Scikit-Learn estimators
and/or pipelines.fromsklearnimportdatasetsfromsklearn.decompositionimportPCAfromsklearn.linear_modelimportLogisticRegressionfromsklearn.pipelineimportPipelinefromgeneticpyimportGeneticSearchCV,ChoiceDistribution,LogNormalDistribution,UniformDistribution# Define a pipeline to search for the best combination of PCA truncation# and classifier regularization.pca=PCA()# set the tolerance to a large value to make the example fasterlogistic=LogisticRegression(max_iter=10000,tol=0.1,solver='saga')pipe=Pipeline(steps=[('pca',pca),('logistic',logistic)])X_digits,y_digits=datasets.load_digits(return_X_y=True)# Parameters of pipelines can be set using ‘__’ separated parameter names:param_grid={'pca__n_components':UniformDistribution(low=5,high=64,q=1),'logistic__C':LogNormalDistribution(mean=1,sigma=0.5,low=0.001,high=2),'logistic__penalty':ChoiceDistribution(choice_list=['l1','l2'])}search=GeneticSearchCV(pipe,param_grid)search.fit(X_digits,y_digits)print("Best parameter (CV score=%0.3f):"%search.best_score_)print(search.best_params_)PyPi Projecthttps://pypi.org/project/geneticpy/ContactPlease feel free to email me atbrandonschabell@gmail.comwith any questions or feedback.
Package: geneticpython
geneticpythonA simple and friendly Python framework for genetic-based algorithms (strongly supports tree-encoding)Supported algorithms: Genetic Algorithm (GAEngine), NSGA-ii (NSGAIIEngine).Anexampleon ZDT1 problem:InstallationThis package requirespython 3.6or later.pip install geneticpythonGetting startedWe can quickly design a genetic algorithm in the following steps:define a individual template with specific encodingfromgeneticpython.modelsimportBinaryIndividualindv_temp=BinaryIndividual(length=100)define population based on created individual template. This population can uniformly initialize a population or you can define your own by passinginit_populationargument functionfromgeneticpythonimportPopulationpopulation=Population(indv_temp,pop_size=100)define some core operators in genetic algorithmfromgeneticpython.core.operatorsimportRouletteWheelSelection,UniformCrossover,\FlipBitMutation,RouletteWheelReplacementselection=RouletteWheelSelection()crossover=UniformCrossover(pc=0.8,pe=0.5)mutation=FlipBitMutation(pm=0.1)# this function decides which individuals will be survivedreplacement=RouletteWheelReplacement()create an engine and register the defined population and operatorsfromgeneticpythonimportGAEngineengine=GAEngine(population,selection=selection,selection_size=100,crossover=crossover,mutation=mutation,replacement=replacement)register fitness function which gets an individual and returns its fitness value@engine.maximize_objectivedeffitness(indv):returnfitness_of_indvrun engineengine.create_seed(seed)history=engine.run(generations=1000)get results and plot historyans=engine.get_best_indv()print(ans)plot_single_objective_history({'geneticpython':history})You can find more exampleshereIssuesThis project is in development, if you find any issues, please create an issuehere.TODOCreate extensive documentation and docs and comments in source-codeImplement other algorithms:PSO, DE, MOED/A, MOPSO, MODE,...Implement other operators:PMX crossover, ...Create unit tests.ContributingThe goal of this project is to be able to build a simple and novice-friendly library yet functional enough to experiment with research projects. It is spontaneous and non-profit and also flawed.We appreciate all contributions. If you are interested in contributing this project (including functional implementation or standard examples), please checkContribution page.If you plan to contribute new features, utility functions, fix bugs, or extensions to the core, please first open an issue and discuss the feature with us.ContributorsNgoc Bui (ngocjr7)AcknowledgementsSpecial thanks tohttps://github.com/PytLab/gaftfor getting me started a great API design.This repository includes some parts of the following repos:https://github.com/msu-coinlab/pymoohttps://github.com/tensorflow/tensorflow
Package: genetictabler
GeneticTablerTime Table scheduling using genetic algorithm.Developed byDipan NandaandAshish Shah(c) 2021Example of UsagefromgenetictablerimportGenerateTimeTabletotal_classes=6no_courses=6slots=6total_days=7daily_repetition=3"""Variable Definitions::param total_classes: It is the count of total number of timetables you want.Suppose If you 4 batches/student groups for CS freshmenall studying the same courses/modules/subjects you cangenerate 4 different yet coherent yet timetables withouthaving any clashes.:param no_courses: It is the count of total number of courses/modules/subjectsthat a class or classes are going to be taught. For exampleif a class is going to be taught only maths, physics,chemistry and CS then total count will be 4.:param slots: It is the count of total lectures that are to be scheduled eachday.:param total_days: It is the count of total number of days for which you wantto schedule the timetable. For example a weekly timetablewill have total 5/6 days. A monthly schedule can be of 25days.:param daily_repetition: It is the maximum allowed number of times acourse/subject/module can have lectures per day. Itis used when the slots count is more than no_courses.Note:- The table returned by the above function call is a 3-dimensionallist/array. Which is a list of timetables for each class which in itself are2d arrays."""table=GenerateTimeTable(total_classes,no_courses,slots,total_days,daily_repetition)forsingle_tableintable.run():fordaysinsingle_table:print(days)print("-----------------------------------")ChangelogGohereto checkout the complete changelog.LicenseThis is under BSD 3 Clause License
Package: genetic-tree
Genetic TreeThe main objective of the package is to allow creating decision trees that are better in some aspects than trees made by greedy algorithms.The creation of trees is made by genetic algorithm.
In order to achive as fast as possible evolution of trees the most time consuming components are wrtitten in Cython.
Also there are implemented mechanisms for using old trees to create new ones without need to classify all observations from beggining (currently in developmnet).
There is planned to allow multithreading evolution.The created trees should have smaller sizes with comparable accuracy to the trees made by greedy algorithms.Project is currently in development (before first version).
The first working official version should be developed in the January 2021 (with documentation and installation by pip).InstallationTo download the latest official release of the package use a pip command below:pipinstallgenetic-treeUsageExample usage:fromgenetic_treeimportGeneticTreefromsklearnimportdatasetsiris=datasets.load_iris()# get iris datagt=GeneticTree()gt.fit(iris.data,iris.target)y_pred=gt.predict(iris.data)# it is recommended to predict on another subset of data than trainingThey_predcontains an array with classes predicted by theGeneticTreeLicenseThe work is a banchelor thesis on Warsaw University of Technology. Commercial use forbidden.High-level interface of package is inspired by sklearn (https://github.com/scikit-learn/scikit-learn).
Especially there are methods like: fit(), predict(), predict_proba(), apply(), set_params(), check_X(), check_input() which are inspired and / or copied from sklearn.A low-level interface is inspired by sklearn decision_tree. The structure of tree (tree/tree.pyx) and some utils (tree/_utils.pyx) were copied from sklearn tree (https://github.com/scikit-learn/scikit-learn/tree/master/sklearn/tree).