Skip to content

Instantly share code, notes, and snippets.

@nickinack
Last active November 22, 2020 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickinack/0c971fa5c2099867b7c4d45c5d34b0b3 to your computer and use it in GitHub Desktop.
Save nickinack/0c971fa5c2099867b7c4d45c5d34b0b3 to your computer and use it in GitHub Desktop.
class FeatureSolver(AbstractSolver):
def __init__(
self,
problem_type=float,
fitness_func= lambda a : fitness_func(a),
pop_cnt: int = 40,
gene_size: int = 50,
max_gen: int = 2,
mutation_ratio: float = 0.2,
selection_ratio: float = 0.2,
selection_type: str = "roulette_wheel",
mutation_type: str = "insert",
crossover_type: str = "one_point",
excluded_genes: Sequence = None,
variables_limits=(-10, 10),
verbose: bool = False,
cv=0,
**kwargs
):
"""
:param fitness_function: can either be a fitness function or
a class implementing a fitness function + methods to override
the default ones: create_offspring, mutate_population, initialize_population
:param n_genes: number of genes (variables) to have in each chromosome
:param max_gen: maximum number of generations to perform the optimization
:param pop_size: population size
:param mutation_rate: rate at which random mutations occur
:param selection_rate: percentage of the population to be selected for crossover
:param selection_strategy: strategy to use for selection
:param verbose: whether to print iterations status
:param show_stats: whether to print stats at the end
:param plot_results: whether to plot results of the run at the end
:param variables_limits: limits for each variable [(x1_min, x1_max), (x2_min, x2_max), ...].
If only one tuple is provided, then it is assumed the same for every variable
:param problem_type: whether problem is of float or integer type
"""
AbstractSolver.__init__(
self,
problem_type=problem_type,
gene_size=gene_size,
fitness_func=fitness_func,
pop_cnt=pop_cnt,
max_gen=max_gen,
mutation_ratio=mutation_ratio,
selection_ratio=selection_ratio,
selection_type=selection_type,
mutation_type=mutation_type,
crossover_type=crossover_type,
excluded_genes=excluded_genes,
verbose=verbose,
cv=cv,
**kwargs
)
def initialize_population(self):
"""
Initializes the population of the problem according to the
population size and number of genes and according to the problem
type (either integers or floats).
:return: a numpy array with a randomized initialized population
"""
population = np.empty(shape=(self.pop_cnt, self.gene_size))
for i in range(0,self.pop_cnt):
population[i] = random.sample(range(0,99) , self.gene_size)
return population
random.seed(10)
solver = FeatureSolver(
gene_size=50,
cv=0
)
list(solver.solve())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment