### Install TheFittest with pip Source: https://github.com/sherstpasha/thefittest/blob/main/README.rst This snippet demonstrates how to install TheFittest library using pip, ensuring the necessary dependencies are managed for usage. ```bash pip install thefittest ``` -------------------------------- ### SHADE Optimizer Example Source: https://github.com/sherstpasha/thefittest/blob/main/README.rst This example uses the SHADE optimizer to minimize a custom objective function. It highlights the key components required to set up and run an optimization using TheFittest. ```python from thefittest.optimizers import SHADE # Define the objective function to minimize def custom_problem(x): return (5 - x[:, 0])**2 + (12 - x[:, 1])**2 # Initialize the SHADE optimizer with custom parameters optimizer = SHADE( fitness_function=custom_problem, iters=25, pop_size=10, left_border=-100, right_border=100, num_variables=2, show_progress_each=10, minimization=True, ) # Run the optimization optimizer.fit() # Retrieve and print the best solution found fittest = optimizer.get_fittest() print('The fittest individ:', fittest['phenotype']) print('with fitness', fittest['fitness']) ``` -------------------------------- ### MLPEAClassifier with SHAGA Optimizer Source: https://github.com/sherstpasha/thefittest/blob/main/README.rst This example trains a machine learning model on the Iris dataset using the MLPEAClassifier with the SHAGA evolutionary optimizer, demonstrating integration with scikit-learn. ```python from thefittest.optimizers import SHAGA from thefittest.benchmarks import IrisDataset from thefittest.classifiers import MLPEAClassifier from sklearn.model_selection import train_test_split from sklearn.preprocessing import minmax_scale from sklearn.metrics import confusion_matrix, f1_score # Load the Iris dataset data = IrisDataset() X = data.get_X() y = data.get_y() # Scale features to the [0, 1] range X_scaled = minmax_scale(X) # Split the data into training and test sets X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.1) # Initialize the MLPEAClassifier with SHAGA as the optimizer model = MLPEAClassifier( n_iter=500, pop_size=500, hidden_layers=[5, 5], weights_optimizer=SHAGA, weights_optimizer_args={"show_progress_each": 10} ) # Train the model model.fit(X_train, y_train) # Make predictions on the test set predict = model.predict(X_test) # Evaluate the model print("confusion_matrix: \n", confusion_matrix(y_test, predict)) print("f1_score: \n", f1_score(y_test, predict, average="macro") ``` -------------------------------- ### Tournament Selection Implementation - Python Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/selections.html Demonstrates how to use tournament selection for genetic algorithms. This example shows importing the tournament_selection function, preparing fitness and rank data, and selecting the desired number of individuals based on tournament competition. ```python >>> from thefittest.utils.selections import tournament_selection >>> import numpy as np >>> >>> # Example >>> fitness_values = np.array([0.8, 0.5, 0.9, 0.3], dtype=np.float64) >>> rank_values = np.array([3, 2, 4, 1], dtype=np.float64) >>> tournament_size = 2 >>> num_selected = 2 >>> selected_individuals = tournament_selection(fitness_values, rank_values, tournament_size, num_selected) >>> print("Selected Individuals:", selected_individuals) Selected Individuals: ... ``` -------------------------------- ### Run SHADE Differential Evolution Optimization with Python Source: https://context7.com/sherstpasha/thefittest/llms.txt Demonstrates how to minimize a continuous function using the SHADE optimizer from thefittest. The example imports the optimizer, defines an objective, configures parameters, runs, and prints the best phenotype and fitness. Requires NumPy and thefittest library; suitable for low‑dimensional continuous problems. ```python from thefittest.optimizers import SHADE # Define the objective function to minimize def custom_problem(x): return (5 - x[:, 0])**2 + (12 - x[:, 1])**2 # Initialize the SHADE optimizer optimizer = SHADE( fitness_function=custom_problem, iters=25, pop_size=10, left_border=-100, right_border=100, num_variables=2, show_progress_each=10, minimization=True, ) # Run the optimization optimizer.fit() # Retrieve and print the best solution found fittest = optimizer.get_fittest() print('The fittest individual:', fittest['phenotype']) print('with fitness:', fittest['fitness']) # Expected output: phenotype close to [5.0, 12.0], fitness close to 0.0 # Access optimization history stats = optimizer.get_stats() print('Fitness history:', stats['max_fitness']) print('Remaining function evaluations:', optimizer.get_remains_calls()) ``` -------------------------------- ### Symbolic Regression Initialization and Point Mutation Example (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/source/modules/utils/mutations.md Demonstrates initializing a universal set for symbolic regression and performing a point mutation on a generated tree. Requires numpy. ```python >>> import numpy as np >>> from thefittest.base import Tree >>> from thefittest.base import init_symbolic_regression_uniset >>> from thefittest.utils.mutations import point_mutation >>> # Example Parameters >>> X = np.array([[0.3, 0.7], [0.3, 1.1], [3.5, 11.0]], dtype=np.float64) >>> functional_set_names = ("add", "mul") >>> max_tree_level = 4 >>> mutation_probability = 0.5 >>> # Initialize Universal Set for Symbolic Regression >>> universal_set = init_symbolic_regression_uniset(X, functional_set_names) >>> # Generate a Random Tree >>> tree = Tree.random_tree(universal_set, max_tree_level) >>> # Perform Point Mutation >>> mutated_tree = point_mutation(tree, universal_set, mutation_probability, max_tree_level) >>> print("Original Tree:", tree) Original Tree: ... >>> print("Mutated Tree:", mutated_tree) Mutated Tree: ... ``` -------------------------------- ### Retrieve SamplingGrid parameter values (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/transformations.html After initializing or fitting a SamplingGrid instance, this code prints key configuration values: the total number of variables, the step size for each variable, and the number of bits allocated per variable. These queries help verify the grid setup before performing transformations. ```Python print(\"Number of Variables:\", grid.get_num_variables())\nprint(\"Step Size per Variable:\", grid.get_h_per_variable())\nprint(\"Bits per Variable:\", grid.get_bits_per_variable()) ``` -------------------------------- ### GrayCode Class Usage (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/transformations.html This provides an example of how to use the GrayCode class for transforming populations between gray code and floating point representations. It demonstrates initialization, fitting the sampling grid, generating populations, and transforming between representations. ```Python import numpy as np from thefittest.utils.transformations import GrayCode # Fit the sampling grid with gray code transformation grid = GrayCode() grid.fit(left_border=-5.0, right_border=5.0, num_variables=3, h_per_variable=0.1) # Generate a binary population using gray code string_length = grid.get_bits_per_variable().sum() gray_population = np.random.randint(2, size=(5, string_length), dtype=np.byte) print("Gray Code Population:", gray_population) # Transform the gray code population to a floating-point array print("Transformed Population:", grid.transform(gray_population)) # Generate a floating-point population floating_population = np.random.rand(5, 3) print("Floating-point Population:", floating_population) # Inverse transform the floating-point population to a gray code array inverse_transformed_population = grid.inverse_transform(floating_population) print("Inverse Transformed Population (Gray Code):", inverse_transformed_population) ``` -------------------------------- ### Execute Uniform Crossover with TheFittest (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/crossovers.html Shows how to use uniform_crossover to create offspring by randomly selecting genes from each parent. The example initializes binary parent arrays along with fitness and rank data, then produces and prints the resulting offspring. Uniform crossover ensures each gene is independently chosen from one of the parents. ```Python import numpy as np\nfrom thefittest.utils.crossovers import uniform_crossover\n\n# Example\n# Define the parents, fitness values, and ranks\nparents = np.array([[1, 0, 1, 0], [0, 1, 1, 1]], dtype=np.byte) # First and second parent\nfitness_values = np.array([0.5, 0.8], dtype=np.float64)\nranks = np.array([2.0, 1.0], dtype=np.float64)\n\n# Perform uniform crossover\noffspring = uniform_crossover(parents, fitness_values, ranks)\n\n# Display results\nprint(\"Original Individuals:\", parents)\nprint(\"Offspring After Uniform Crossover:\", offspring) ``` -------------------------------- ### Perform Uniform Rank Crossover for Genetic Programming (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/crossovers.html Demonstrates how to use uniform_rank_crossover_GP to combine three parent trees into an offspring tree using rank‑based probabilities. Requires NumPy, thefittest's Tree class, and a symbolic regression universal set. The example shows initialization, parent generation, and printing of results. ```Python import numpy as np from thefittest.utils.crossovers import uniform_rank_crossover_GP from thefittest.base import Tree from thefittest.base import init_symbolic_regression_uniset # Example X = np.array([[0.3, 0.7], [0.3, 1.1], [3.5, 11.0]], dtype=np.float64) functional_set_names = ("add", "mul") max_tree_level = 5 # Initialize Universal Set for Symbolic Regression universal_set = init_symbolic_regression_uniset(X, functional_set_names) parent1 = Tree.random_tree(universal_set, max_tree_level) parent2 = Tree.random_tree(universal_set, max_tree_level) parent3 = Tree.random_tree(universal_set, max_tree_level) fitness_values = np.array([0.5, 0.8, 0.6], dtype=np.float64) ranks = np.array([2.0, 1.0, 3.0], dtype=np.float64) max_depth = 7 # Set the maximum allowed depth # Perform uniform rank crossover offspring = uniform_rank_crossover_GP(np.array([parent1, parent2, parent3]), fitness_values, ranks, max_depth) # Display results print("Parent 1:", parent1) print("Parent 2:", parent2) print("Parent 3:",print("Offspring After Uniform Rank Crossover:", offspring) ``` -------------------------------- ### Generate Cauchy-distributed numbers using thefittest.utils.random.cauchy_distribution (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/random.html This example demonstrates how to import the cauchy_distribution function and generate an array of random numbers from a Cauchy distribution. It requires NumPy and the Thefittest library. The resulting array can be used for statistical simulations or testing. ```Python import numpy as np from thefittest.utils.random import cauchy_distribution loc_value = 0.0 scale_value = 1.0 size_value = 10 cauchy_result = cauchy_distribution(loc_value, scale_value, size_value) print("Cauchy Distribution Result:", cauchy_result) ``` -------------------------------- ### Convert Gray Code to Binary (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/transformations.html This code snippet showcases the usage of the `gray_to_bit` function to convert a gray code array into its binary equivalent. It leverages NumPy for array manipulation and provides a simplified example for understanding the conversion process. ```Python import numpy as np from thefittest.utils.transformations import GrayCode # Example: Convert gray code array to binary array using GrayCode.gray_to_bit method gray_array = np.array([[1, 0, 1], [0, 1, 0]], dtype=np.byte) result = GrayCode.gray_to_bit(gray_array) print("Converted Binary Array:", result) ``` -------------------------------- ### Convert integer array to binary using SamplingGrid.int_to_bit (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/transformations.html This example demonstrates how to convert a one‑dimensional NumPy integer array into a binary using the SamplingGrid.int_to_bit static method. It includes a basic conversion and a variant with custom power-of-two values to avoid recomputation. The code requires NumPy and the SamplingGrid class from thefittest.utils.transformations. ```Python import numpy as np\nfrom thefittest.utils.transformations import SamplingGrid\n\n# Example 1: Convert one-dimensional integer array to binary array\ninteger_array = np.array([5, 3], dtype=np.int64)\nresult = SamplingGrid.int_to_bit(integer_array)\nprint(\"Converted Binary Array:\", result)\n\n# Example 2: Convert one-dimensional integer array to binary array with powers\ncustom_powers = np.array([1, 2, 4], dtype=np.int64)\ninteger_array = np.array([5, 3], dtype=np.int64)\nresult_custom_powers = SamplingGrid.int_to_bit(integer_array, powers=custom_powers)\nprint(\"Converted Binary Array (Define Powers):\", result_custom_powers) ``` -------------------------------- ### Apply Rand-2 mutation with thefittest library (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/mutations.html This example demonstrates using the rand_2 function to perform Rand-2 mutation on a candidate solution. It imports NumPy, defines the current and best individuals, a larger population array, and a mutation factor. The resulting mutated individual is printed. ```Python from thefittest.utils.mutations import rand_2 import numpy as np # Example current_individual = np.array([0.5, 0.3, 0.8], dtype=np.float64) best_individual = np.array([0.6, 0.4, 0.7], dtype=np.float64) population = np.array([[0.2, 0.1, 0.5], [0.8, 0.6, 0.9], [0.3, 0.7, 0.4], [0.9, 0.5, 0.2], [0.4, 0.2, 0.6]], dtype=np.float64) mutation_scale_factor = 0.7 mutated_individual = rand_2(current_individual, best_individual, population, mutation_scale_factor) print("Current Individual:", current_individual) print("Mutated Individual:", mutated_individual) ``` -------------------------------- ### Current-to-pbest-1-Archive Mutation Example in Python Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/mutations.html Shows the current_to_pbest_1_archive mutation, incorporating a randomly selected top individual (via pbest indices) and differences from population and archive members scaled by F. Depends on NumPy; inputs include current individual, population, pbest indices, F, and archive; returns mutated array. Supports archive for diversity but requires archive size compatibility with population. ```python from thefittest.utils.mutations import current_to_pbest_1_archive import numpy as np # Example current_individual = np.array([0.5, 0.3, 0.8], dtype=np.float64) population = np.array([[0.2, 0.1, 0.5], [0.8, 0.6, 0.9], [0.3, 0.7, 0.4], [0.9, 0.5, 0.2]], dtype=np.float64) pbest_indices = np.array([1, 3], dtype=np.int64) mutation_scale_factor = 0.7 pop_archive = np.array([[0.1, 0.3, 0.6], [0.7, 0.4, 0.8], [0.4, 0.2, 0.5]], dtype=np.float64) mutated_individual = current_to_pbest_1_archive(current_individual, population, pbest_indices, mutation_scale_factor, pop_archive) print("Current Individual:", current_individual) print("Mutated Individual:", mutated_individual) ``` -------------------------------- ### Generate random integers with Python Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/random.html Demonstrates generating random integers using thefittest.utils.random.randint. It relies on thefittest.utils.random and NumPy for setup. Inputs: low, high, and size. Output: ndarray of integers. Limitation: distribution is discrete uniform over [low, high). ```Python from numba import jit import numpy as np from thefittest.utils.random import randint # Example of generating random integers result = randint(low=1, high=10, size=5) print("Random Integers:", result) ``` -------------------------------- ### Current-to-Best-1 Mutation Example in Python Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/mutations.html Demonstrates the current_to_best_1 mutation strategy, which combines the current individual with the best individual and random population differences scaled by factor F. Requires NumPy for array handling; inputs are current and best individuals, full population, and F; outputs a mutated NumPy array. Limited to float64 dtype and assumes valid population size greater than 2. ```python from thefittest.utils.mutations import current_to_best_1 import numpy as np # Example current_individual = np.array([0.5, 0.3, 0.8], dtype=np.float64) best_individual = np.array([0.6, 0.4, 0.7], dtype=np.float64) population = np.array([[0.2, 0.1, 0.5], [0.8, 0.6, 0.9], [0.3, 0.7, 0.4]], dtype=np.float64) mutation_scale_factor = 0.7 mutated_individual = current_to_best_1(current_individual, best_individual, population, mutation_scale_factor) print("Current Individual:", current_individual) print("Mutated Individual:", mutated_individual) ``` -------------------------------- ### Scale Data with MinMax Normalization in Python Source: https://github.com/sherstpasha/thefittest/blob/main/docs/source/modules/utils/transformations.md Demonstrates how to use the minmax_scale function from thefittest.utils.transformations to normalize data arrays using min-max scaling. The function scales input data to a range between 0 and 1, preserving the original distribution. Dependencies include numpy and the thefittest package. The example shows complete workflow from data creation to result display. ```python >>> import numpy as np >>> from thefittest.utils.transformations import minmax_scale >>> >>> # Example data >>> example_data = np.array([2, 5, 10, 8, 3], dtype=np.int64) >>> >>> # Scale the data using the minmax_scale function >>> scaled_data = minmax_scale(example_data) >>> >>> # Display original and scaled data >>> print("Original Data:", example_data) Original Data: [ 2 5 10 8 3] >>> print("Scaled Data:", scaled_data) Scaled Data: [0. 0.375 1. 0.75 0.125] ``` -------------------------------- ### Differential Evolution Rand-to-Best-1 Mutation Example (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/source/modules/utils/mutations.md Shows an example of the Rand-to-Best-1 mutation strategy used in differential evolution. This strategy uses the best individual in the population to guide the mutation. Requires numpy. ```python >>> from thefittest.utils.mutations import rand_to_best1 >>> import numpy as np >>> >>> # Example Parameters >>> current_individual = np.array([0.5, 0.3, 0.8], dtype=np.float64) >>> best_individual = np.array([0.6, 0.4, 0.7], dtype=np.float64) >>> population = np.array([[0.2, 0.1, 0.5], [0.8, 0.6, 0.9], [0.3, 0.7, 0.4]], dtype=np.float64) >>> mutation_scale_factor = 0.7 >>> >>> # Perform Rand-to-Best-1 Mutation >>> mutated_individual = rand_to_best1(current_individual, best_individual, population, mutation_scale_factor) >>> >>> print("Current Individual:", current_individual) Current Individual: [0.5 0.3 0.8] >>> print("Mutated Individual:", mutated_individual) Mutated Individual: ... ``` -------------------------------- ### Initialize PDPGA optimizer Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/optimizers.html Configures a Probability Distribution based Parameterless Genetic Algorithm with adaptive operator selection. Supports multiple selection, crossover, and mutation strategies simultaneously. Based on Niehaus & Banzhaf's adaptive operator probabilities approach. ```python class PDPGA: def __init__(self, fitness_function: Callable[[ndarray[Any, dtype[Any]]], ndarray[Any, dtype[float64]]], iters: int, pop_size: int, str_len: int, tour_size: int = 2, mutation_rate: float = 0.05, parents_num: int = 2, elitism: bool = True, selections: Tuple[str, ...] = ('proportional', 'rank', 'tournament_3', 'tournament_5', 'tournament_7'), crossovers: Tuple[str, ...] = ('empty', 'one_point', 'two_point', 'uniform_2', 'uniform_7', 'uniform_prop_2', 'uniform_prop_7', 'uniform_rank_2', 'uniform_rank_7', 'uniform_tour_3', 'uniform_tour_7'), mutations: Tuple[str, ...] = ('weak', 'average', 'strong'), init_population: ndarray[Any, dtype[int8]] | None = None, genotype_to_phenotype: Callable[[ndarray[Any, dtype[int8]]], ndarray[Any, dtype[Any]]] | None = None, optimal_value: float | None = None, termination_error_value: float = 0.0, no_increase_num: int | None = None, minimization: bool = False, show_progress_each: int | None = None, keep_history: bool = False, n_jobs: int = 1, fitness_function_args: Dict | None = None, genotype_to_phenotype_args: Dict | None = None, random_state: int | RandomState | None = None, on_generation: Callable | None = None): pass ``` -------------------------------- ### Initialize Genetic Programming optimizer Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/optimizers.html Configures a Genetic Programming optimizer with comprehensive parameters for evolutionary computation. Supports various selection, crossover, and mutation strategies. Requires a fitness function and universal set for genetic operations. ```python class GeneticProgramming: def __init__(self, fitness_function: Callable[[ndarray[Any, dtype[Any]]], ndarray[Any, dtype[float64]]], uniset: UniversalSet, iters: int, pop_size: int, tour_size: int = 2, mutation_rate: float = 0.05, parents_num: int = 7, elitism: bool = True, selection: str = 'rank', crossover: str = 'gp_standard', mutation: str = 'gp_weak_grow', max_level: int = 16, init_level: int = 5, init_population: ndarray[Any, dtype[_ScalarType_co]] | None = None, genotype_to_phenotype: Callable[[ndarray[Any, dtype[Any]]], ndarray[Any, dtype[Any]]] | None = None, optimal_value: float | None = None, termination_error_value: float = 0.0, no_increase_num: int | None = None, minimization: bool = False, show_progress_each: int | None = None, keep_history: bool = False, n_jobs: int = 1, fitness_function_args: Dict | None = None, genotype_to_phenotype_args: Dict | None = None, random_state: int | RandomState | None = None, on_generation: Callable | None = None): pass ``` -------------------------------- ### Load ML datasets in Python Source: https://context7.com/sherstpasha/thefittest/llms.txt Demonstrates loading various machine learning datasets (Iris, Wine, Breast Cancer, Digits, Banknote) from thefittest.benchmarks module. Shows how to access feature matrices, target vectors, and their metadata. ```python from thefittest.benchmarks import ( IrisDataset, WineDataset, BreastCancerDataset, DigitsDataset, BanknoteDataset ) # Load Iris dataset iris = IrisDataset() X_iris = iris.get_X() y_iris = iris.get_y() feature_names = iris.get_X_names() target_names = iris.get_y_names() print("Iris Dataset:") print(f" Features: {X_iris.shape}, Names: {feature_names}") print(f" Targets: {y_iris.shape}, Classes: {target_names}") # Load Wine dataset wine = WineDataset() X_wine = wine.get_X() y_wine = wine.get_y() print("\nWine Dataset:") print(f" Features: {X_wine.shape}") print(f" Targets: {y_wine.shape}") # Load Breast Cancer dataset cancer = BreastCancerDataset() X_cancer = cancer.get_X() y_cancer = cancer.get_y() print("\nBreast Cancer Dataset:") print(f" Features: {X_cancer.shape}") print(f" Targets: {y_cancer.shape}") # Load Digits dataset (for multi-class classification) digits = DigitsDataset() X_digits = digits.get_X() y_digits = digits.get_y() print("\nDigits Dataset:") print(f" Features: {X_digits.shape}") print(f" Targets: {y_digits.shape}") print(f" Unique classes: {len(np.unique(y_digits))}") # Load Banknote authentication dataset banknote = BanknoteDataset() X_bank = banknote.get_X() y_bank = banknote.get_y() print("\nBanknote Dataset:") print(f" Features: {X_bank.shape}") print(f" Targets: {y_bank.shape}") ``` -------------------------------- ### Differential Evolution Rand-2 Mutation Example (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/source/modules/utils/mutations.md Demonstrates the Rand-2 mutation strategy for differential evolution. This strategy involves a more complex combination of individuals to create the mutation. Requires numpy. ```python >>> from thefittest.utils.mutations import rand_2 >>> import numpy as np >>> >>> # Example >>> current_individual = np.array([0.5, 0.3, 0.8], dtype=np.float64) >>> best_individual = np.array([0.6, 0.4, 0.7], dtype=np.float64) >>> population = np.array([[0.2, 0.1, 0.5], [0.8, 0.6, 0.9], [0.3, 0.7, 0.4], [0.9, 0.5, 0.2], [0.4, 0.2, 0.6]], dtype=np.float64) >>> mutation_scale_factor = 0.7 >>> mutated_individual = rand_2(current_individual, best_individual, population, mutation_scale_factor) >>> print("Current Individual:", current_individual) Current Individual: [0.5 0.3 0.8] >>> print("Mutated Individual:", mutated_individual) Mutated Individual: ... ``` -------------------------------- ### Demonstrate Standard Crossover with TheFittest (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/crossovers.html Shows how to create a universal set for symbolic regression, generate random trees, and apply the standard_crossover function. Requires numpy and thefittest base and utils modules. Returns offspring trees based on provided fitness, rank, and depth constraints. ```Python import numpy as np\nfrom thefittest.utils.crossovers import standard_crossover\nfrom thefittest.base import Tree\nfrom thefittest.base import init_symbolic_regression_uniset\n\n# Example\n\nX = np.array([[0.3, 0.7], [0.3, 1.1], [3.5, 11.0]], dtype=np.float64)\nfunctional_set_names = ("add", "mul")\nmax_tree_level = 5\n\n# Initialize Universal Set for Symbolic Regression\nuniversal_set = init_symbolic_regression_uniset(X, functional_set_names)\n\nparent1 = Tree.random_tree(universal_set, max_tree_level)\nparent2 = Tree.random_tree(universal_set, max_tree_level)\n\nfitness_values = np.array([0.5, 0.8], dtype=np.float64)\nranks = np.array([2.0, 1.0], dtype=np.float64)\nmax_depth = 7 # Set the maximum allowed depth\n\n# Perform standard crossover\noffspring = standard_crossover(np.array([parent1, parent2]), fitness_values, ranks, max_depth)\n\n# Display results\nprint(\"Parent 1:\", parent1)\nprint(\"Parent 2:\", parent2)\nprint(\"Offspring After Standard Crossover:\", offspring) ``` -------------------------------- ### Convert Binary Array to Integer Array (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/source/modules/utils/transformations.md Demonstrates the usage of the bit_to_int function to convert a binary array to an integer array. Includes examples with and without specifying custom powers. ```Python import numpy as np from thefittest.utils.transformations import SamplingGrid binary_array = np.array([[1, 0, 1], [0, 1, 1]], dtype=np.int64) result = SamplingGrid.bit_to_int(binary_array) print("Converted Integer Array:", result) custom_powers = np.array([1, 2, 4], dtype=np.int64) result_custom_powers = SamplingGrid.bit_to_int(binary_array, powers=custom_powers) print("Converted Integer Array (Define Powers):", result_custom_powers) ``` -------------------------------- ### Differential Evolution Rand-1 Mutation Example (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/source/modules/utils/mutations.md Illustrates the Rand-1 mutation strategy for differential evolution. It mutates an individual by combining three randomly selected individuals from the population. Requires numpy. ```python >>> from thefittest.utils.mutations import rand_1 >>> import numpy as np >>> >>> # Example >>> current_individual = np.array([0.5, 0.3, 0.8], dtype=np.float64) >>> best_individual = np.array([0.6, 0.4, 0.7], dtype=np.float64) >>> population = np.array([[0.2, 0.1, 0.5], [0.8, 0.6, 0.9], [0.3, 0.7, 0.4]], dtype=np.float64) >>> mutation_scale_factor = 0.7 >>> mutated_individual = rand_1(current_individual, best_individual, population, mutation_scale_factor) >>> print("Current Individual:", current_individual) Current Individual: [0.5 0.3 0.8] >>> print("Mutated Individual:", mutated_individual) Mutated Individual: ... ``` -------------------------------- ### Execute Binary Genetic Algorithm Optimization using Python Source: https://context7.com/sherstpasha/thefittest/llms.txt Shows a classic genetic algorithm applied to binary string optimization, maximizing the count of ones. The snippet creates an initial binary population, sets selection, crossover, and mutation strategies, runs the evolution, and reports the best genotype and its fitness. Requires NumPy and thefittest; suitable for large binary strings and configurable evolutionary operators. ```python from thefittest.optimizers import GeneticAlgorithm import numpy as np # Define fitness function (maximize number of 1s) def fitness_function(x): return np.sum(x, axis=1, dtype=np.float64) # Create initial population initial_population = GeneticAlgorithm.binary_string_population( pop_size=50, str_len=200 ) # Configure genetic algorithm optimizer = GeneticAlgorithm( fitness_function=fitness_function, iters=100, pop_size=50, str_len=200, selection="tournament_5", crossover="uniform_2", mutation="weak", tour_size=5, parents_num=2, mutation_rate=0.05, elitism=True, show_progress_each=10, keep_history=True, init_population=initial_population, random_state=42 ) # Run optimization optimizer.fit() # Get results fittest = optimizer.get_fittest() print('Best solution:', fittest['genotype']) print('Fitness:', fittest['fitness']) stats = optimizer.get_stats() print('Mean fitness per generation:', stats['mean_fitness']) ``` -------------------------------- ### Inverse transform floating-point population to binary with SamplingGrid (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/transformations.html The snippet fits a SamplingGrid to a specified range and number of variables, generates a random floating‑point population, and then uses the inverse_transform method to obtain a binary representation. It illustrates the required imports, grid configuration, and how to print both the original and transformed populations. ```Python import numpy as np\nfrom thefittest.utils.transformations import SamplingGrid\n\n# Fit the sampling grid\ngrid = SamplingGrid()\ngrid.fit(left_border=0.0, right_border=1.0, num_variables=3, h_per_variable=0.1)\n\n# Generate a floating-point population\nfloating_population = np.random.rand(5, 3)\nprint(\"Floating-point Population:\", floating_population)\n\n# Inverse transform the floating-point population to a binary array\ninverse_population = grid.inverse_transform(floating_population)\nprint(\"Inverse Transformed Population:\", inverse_population) ``` -------------------------------- ### Initialize SamplingGrid with Borders and Fit in Python Source: https://github.com/sherstpasha/thefittest/blob/main/docs/source/modules/utils/transformations.md Demonstrates creating a SamplingGrid instance, fitting it with left and right borders, number of variables, and step sizes or bits per variable. It shows how the grid calculates internal parameters like bits and steps automatically. Dependencies include numpy and thefittest.utils.transformations.SamplingGrid. Inputs are border arrays and variable settings; outputs are grid properties. Limited to numeric borders and does not handle non-numeric variables. ```python >>> import numpy as np >>> from thefittest.utils.transformations import SamplingGrid >>> >>> grid = SamplingGrid() >>> grid.fit(left_border=0.0, right_border=1.0, num_variables=3, h_per_variable=0.1) >>> print("Grid Left Border:", grid.get_left_border()) Grid Left Border: [0. 0. 0.] >>> print("Grid Right Border:", grid.get_right_border()) Grid Right Border: [1. 1. 1.] >>> print("Number of Variables:", grid.get_num_variables()) Number of Variables: 3 >>> print("Step Size per Variable:", grid.get_h_per_variable()) Step Size per Variable: [0.06666667 0.06666667 0.06666667] >>> print("Bits per Variable:", grid.get_bits_per_variable()) Bits per Variable: [4 4 4] >>> >>> grid = SamplingGrid() >>> grid.fit(left_border=-1.0, right_border=1.0, num_variables=2, bits_per_variable=4) >>> print("Grid Left Border:", grid.get_left_border()) Grid Left Border: [-1. -1.] >>> print("Grid Right Border:", grid.get_right_border()) Grid Right Border: [1. 1.] >>> print("Number of Variables:", grid.get_num_variables()) Number of Variables: 2 >>> print("Step Size per Variable:", grid.get_h_per_variable()) Step Size per Variable: [0.13333333 0.13333333] >>> print("Bits per Variable:", grid.get_bits_per_variable()) Bits per Variable: [4 4] >>> >>> grid = SamplingGrid() >>> grid.fit( ... left_border=np.array([-1.0, 0.5, -2.0], dtype=np.float64), ... right_border=np.array([1.0, 5.0, 2.0], dtype=np.float64), ... num_variables=3, ... h_per_variable=np.array([0.05, 1.0, 0.1], dtype=np.float64), ... ) >>> print("Grid Left Border:", grid.get_left_border()) Grid Left Border: [-1. 0.5 -2. ] >>> print("Grid Right Border:", grid.get_right_border()) Grid Right Border: [1. 5. 2.] >>> print("Number of Variables:", grid.get_num_variables()) Number of Variables: 3 >>> print("Step Size per Variable:", grid.get_h_per_variable()) Step Size per Variable: [0.03174603 0.64285714 0.06349206] >>> print("Bits per Variable:", grid.get_bits_per_variable()) Bits per Variable: [6 3 6] >>> >>> grid = SamplingGrid() >>> grid.fit( ... left_border=np.array([-3.5, -2.0, 10.0, 0.9], dtype=np.float64), ... right_border=np.array([3.5, 7.0, 25.0, 1.5], dtype=np.float64), ... num_variables=4, ... bits_per_variable=np.array([8, 16, 3, 40], dtype=np.int64), ... ) >>> print("Grid Left Border:", grid.get_left_border()) Grid Left Border: [-3.5 -2. 10. 0.9] >>> print("Grid Right Border:", grid.get_right_border()) Grid Right Border: [ 3.5 7. 25. 1.5] >>> print("Number of Variables:", grid.get_num_variables()) Number of Variables: 4 >>> print("Step Size per Variable:", grid.get_h_per_variable()) Step Size per Variable: [2.74509804e-02 1.37331197e-04 2.14285714e+00 5.45696821e-13] >>> print("Bits per Variable:", grid.get_bits_per_variable()) Bits per Variable: [ 8 16 3 40] ``` -------------------------------- ### Convert Binary to Gray Code (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/transformations.html This code snippet demonstrates the use of the `bit_to_gray` function to convert a binary array to a gray code array. It utilizes NumPy for array operations and provides a clear example of how to apply the transformation. ```Python import numpy as np from thefittest.utils.transformations import GrayCode # Example: Convert binary array to gray code array using GrayCode.bit_to_gray method binary_array = np.array([[1, 0, 1], [0, 1, 0]], dtype=np.byte) result = GrayCode.bit_to_gray(binary_array) print("Converted Gray Code Array:", result) ``` -------------------------------- ### Parallel fitness evaluation in Python Source: https://context7.com/sherstpasha/thefittest/llms.txt Shows how to configure DifferentialEvolution optimizer for parallel fitness evaluation using all CPU cores (n_jobs=-1). Includes comparison with sequential evaluation and demonstrates an expensive fitness function. ```python from thefittest.optimizers import DifferentialEvolution import numpy as np # Define computationally expensive fitness function def expensive_fitness(x): # Simulate expensive computation result = np.zeros(len(x)) for i in range(len(x)): result[i] = np.sum(np.sin(x[i]) * np.cos(x[i]**2)) return result # Initialize with parallel evaluation (n_jobs=-1 uses all cores) optimizer = DifferentialEvolution( fitness_function=expensive_fitness, iters=50, pop_size=100, left_border=-10, right_border=10, num_variables=20, F=0.8, CR=0.9, minimization=False, n_jobs=-1, # Use all available CPU cores show_progress_each=10, random_state=42 ) # Run optimization with parallel evaluation optimizer.fit() fittest = optimizer.get_fittest() print("Best solution:", fittest['phenotype']) print("Best fitness:", fittest['fitness']) # Compare with sequential evaluation (n_jobs=1) optimizer_seq = DifferentialEvolution( fitness_function=expensive_fitness, iters=50, pop_size=100, left_border=-10, right_border=10, num_variables=20, F=0.8, CR=0.9, minimization=False, n_jobs=1, # Sequential evaluation show_progress_each=10, random_state=42 ) optimizer_seq.fit() print("\nSequential result:", optimizer_seq.get_fittest()['fitness']) ``` -------------------------------- ### Run Self-Adaptive Genetic Algorithm (SHAGA) Source: https://context7.com/sherstpasha/thefittest/llms.txt Implements a genetic algorithm with success history-based parameter adaptation using the Rastrigin benchmark function. Features elitism, tournament selection, and convergence tracking. Returns the best solution found and optimization statistics. ```Python from thefittest.optimizers import SHAGA import numpy as np # Define complex optimization problem (Rastrigin function) def rastrigin(x): A = 10 n = x.shape[1] return A * n + np.sum(x**2 - A * np.cos(2 * np.pi * x), axis=1) # Initialize SHAGA optimizer optimizer = SHAGA( fitness_function=rastrigin, iters=200, pop_size=100, str_len=320, # 10 variables * 32 bits each elitism=True, selection="tournament_5", crossover="uniform_2", mutation="weak", show_progress_each=20, keep_history=True, minimization=True, termination_error_value=0.01, random_state=42 ) # Run optimization optimizer.fit() # Get results fittest = optimizer.get_fittest() print("Best solution:", fittest['phenotype']) print("Fitness value:", fittest['fitness']) # Check convergence stats = optimizer.get_stats() print("Generations run:", len(stats['max_fitness'])) print("Best fitness per generation:", stats['max_fitness']) print("Mean fitness per generation:", stats['mean_fitness']) ``` -------------------------------- ### Train MLP Regressor with SHADE Optimizer Source: https://context7.com/sherstpasha/thefittest/llms.txt Initializes and trains a multi-layer perceptron evolutionary regressor using SHADE optimizer. Demonstrates model fitting, prediction, and evaluation using MSE and R² metrics. Requires scikit-learn for evaluation metrics. ```Python # Initialize regressor model = MLPEARegressor( n_iter=200, pop_size=500, hidden_layers=(100,), activation="sigma", offset=True, weights_optimizer=SHADE, weights_optimizer_args={ "show_progress_each": 20, "keep_history": True }, random_state=42, device="cpu" # Use "cuda" for GPU acceleration ) # Train model model.fit(X_train, y_train) # Predict y_pred = model.predict(X_test) # Evaluate mse = mean_squared_error(y_test, y_pred) r2 = r2_score(y_test, y_pred) print("Mean Squared Error:", mse) print("R² Score:", r2) # Get model details net = model.get_net() stats = model.get_stats() print("Final fitness:", stats['max_fitness'][-1]) ``` -------------------------------- ### Initialize SHADE Optimizer - Python Source: https://github.com/sherstpasha/thefittest/blob/main/docs/source/modules/optimizers.md Initializes the SHADE (Success-History based Adaptive Differential Evolution) optimizer for continuous optimization problems. Configurable parameters include population size, iteration count, and boundary conditions for variables. ```Python class thefittest.optimizers.SHADE(fitness_function: Callable[[ndarray[Any, dtype[Any]]], ndarray[Any, dtype[float64]]], iters: int, pop_size: int, left_border: float | int | number | ndarray[Any, dtype[number]], right_border: float | int | number | ndarray[Any, dtype[number]], num_variables: int, elitism: bool = True, init_population: ndarray[Any, dtype[float64]] | None = None, genotype_to_phenotype: Callable[[ndarray[Any, dtype[float64]]], ndarray[Any, dtype[Any]]] | None = None, optimal_value: float | None = None, termination_error_value: float = 0.0, no_increase_num: int | None = None, minimization: bool = False, show_progress_each: int | None = None, keep_history: bool = False, n_jobs: int = 1, fitness_function_args: Dict | None = None, genotype_to_phenotype_args: Dict | None = None, random_state: int | RandomState | None = None, on_generation: Callable | None = None) ``` -------------------------------- ### Compare optimization results in Python Source: https://context7.com/sherstpasha/thefittest/llms.txt Prints formatted comparison of optimization results including fitness values and solution dimensions. Works with dictionary-structured results containing 'best_fitness' and 'best_solution' keys. ```python for name, result in results.items(): print(f"\n{name}:") print(f" Fitness: {result['best_fitness']}") print(f" Solution: {result['best_solution'][:3]}... (first 3 dims)") ``` -------------------------------- ### Perform Two-Point Crossover using TheFittest (Python) Source: https://github.com/sherstpasha/thefittest/blob/main/docs/modules/utils/crossovers.html Provides an example of applying two_point_crossover on binary parent chromosomes. It sets up parent arrays, fitness values, and ranks, then generates offspring by swapping segments between parents. The function returns a randomly selected offspring from the two possible results. ```Python import numpy as np\nfrom thefittest.utils.crossovers import two_point_crossover\n\n# Example\n# Define the parents, fitness values, and ranks\nparents = np.array([[1, 0, 1, 0], [0, 1, 1, 1]], dtype=np.byte) # First and second parent\nfitness_values = np.array([0.5, 0.8], dtype=np.float64)\nranks = np.array([2.0, 1.0], dtype=np.float64)\n\n# Perform two-point crossover\noffspring = two_point_crossover(parents, fitness_values, ranks)\n\n# Display results\nprint(\"Original Individuals:\", parents)\nprint(\"Offspring After Two-Point Crossover:\", offspring) ```