Skip to content

Instantly share code, notes, and snippets.

@audhiaprilliant
Last active March 28, 2023 07:56
Show Gist options
  • Select an option

  • Save audhiaprilliant/f507d629a5322ca7f1ceaea027df0f6f to your computer and use it in GitHub Desktop.

Select an option

Save audhiaprilliant/f507d629a5322ca7f1ceaea027df0f6f to your computer and use it in GitHub Desktop.
Manual calculation of Genetic Algorithm using Roulette Wheel selection
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"id": "suburban-replacement",
"metadata": {},
"source": [
"# Genetic Algorithm"
]
},
{
"cell_type": "markdown",
"id": "adult-hormone",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"id": "funky-birmingham",
"metadata": {},
"source": [
"## Import packages"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "operational-characteristic",
"metadata": {},
"outputs": [],
"source": [
"# Genetic algorithm\n",
"import pygad\n",
"\n",
"# Matrix calculation\n",
"import numpy as np\n",
"\n",
"# Latex\n",
"from IPython.display import Math"
]
},
{
"cell_type": "markdown",
"id": "eight-metabolism",
"metadata": {},
"source": [
"## Function for Genetic Algorithm"
]
},
{
"cell_type": "markdown",
"id": "confident-tolerance",
"metadata": {},
"source": [
"$$ f(x) = 3x_{1} + 2x_{2} + 4x_{3} + 2x_{4} + 5x_{5} - 100$$"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "generic-factory",
"metadata": {},
"outputs": [],
"source": [
"# Objective function\n",
"inputValue = [3, 2, 4, 2, 5]\n",
"outputValue = 100"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "shaped-management",
"metadata": {},
"outputs": [],
"source": [
"# Fitness function\n",
"def fitnessFunction(solution, solutionIndex):\n",
" outputExpected = np.sum(solution * inputValue)\n",
" fitnessValue = 1 / (np.abs(outputExpected - outputValue) + 0.000001)\n",
" return fitnessValue"
]
},
{
"cell_type": "markdown",
"id": "endless-acrylic",
"metadata": {},
"source": [
"## Run the Genetic Algorithm"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "necessary-tyler",
"metadata": {},
"outputs": [],
"source": [
"# Prepare the parameters\n",
"\n",
"# Generation\n",
"numberGeneration = 500 # Number of generation\n",
"numberParentsMating = 5\n",
"solutionPerPopulation = 50 # Number of chromosomes in each generation\n",
"parents = -1\n",
"\n",
"# Genes\n",
"numberGenes = len(inputValue) # Number of genes in each chromosome\n",
"geneType = int # Data type in each gene\n",
"\n",
"# Range of values\n",
"minValue = 0 # Minimum value of solution\n",
"maxValue = 9 # Maximum value of solution\n",
"\n",
"# Selection\n",
"selectionType = 'rws' # Selection using Roulette Wheel method\n",
"\n",
"# Cross over\n",
"crossoverType = 'single_point' # Cross over using single point method\n",
"crossoverRate = 0.25 # Cross over rate (Pc)\n",
"\n",
"# Mutation rate\n",
"# Mutation\n",
"mutationType = 'random' # Mutation using random method\n",
"mutationReplacement = True # Replace gene with random value\n",
"mutationMin = 0\n",
"mutationMax = 9\n",
"mutationRate = 10 # Mutation rate (Pm)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "general-concentration",
"metadata": {},
"outputs": [],
"source": [
"# Set the parameters into Genetic Algorithm function\n",
"geneticAlgorithm = pygad.GA(\n",
" # Number of generation\n",
" num_generations = numberGeneration,\n",
" \n",
" # Number of parents mating\n",
" num_parents_mating = numberParentsMating,\n",
" \n",
" # Number of gene each chromosome\n",
" num_genes = numberGenes,\n",
" \n",
" # Gene type\n",
" gene_type = geneType,\n",
" \n",
" # Fitness function\n",
" fitness_func = fitnessFunction,\n",
" \n",
" # Number solution per population\n",
" sol_per_pop = solutionPerPopulation,\n",
" \n",
" # Min and max value\n",
" init_range_low = minValue,\n",
" init_range_high = maxValue,\n",
" \n",
" # Selection\n",
" parent_selection_type = selectionType,\n",
" keep_parents = parents,\n",
" \n",
" # Cross over\n",
" crossover_type = crossoverType,\n",
" #crossover_probability = crossoverRate,\n",
" \n",
" # Mutation\n",
" mutation_type = mutationType,\n",
" mutation_by_replacement = mutationReplacement,\n",
" random_mutation_min_val = mutationMin,\n",
" random_mutation_max_val = mutationMax,\n",
" mutation_percent_genes = mutationRate,\n",
" \n",
" # Solutions\n",
" save_solutions = True,\n",
" save_best_solutions = True,\n",
" suppress_warnings = True,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "delayed-continent",
"metadata": {},
"outputs": [],
"source": [
"# Run the Genetic Algorithm\n",
"geneticAlgorithm.run()"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "oriented-reviewer",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Parameters of the best solution : [4 8 8 5 6]\n",
"Fitness value of the best solution : 1000000.0\n",
"Index of the best solution : 0\n"
]
}
],
"source": [
"# Solution\n",
"solution, solutionFitness, solutionIndex = geneticAlgorithm.best_solution()\n",
"print('Parameters of the best solution : {solution}'.format(solution = solution))\n",
"print('Fitness value of the best solution : {solutionFitness}'.format(solutionFitness = round(solutionFitness, ndigits = 2)))\n",
"print('Index of the best solution : {solutionIndex}'.format(solutionIndex = solutionIndex))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
@ZHAOYANZHOU
Copy link

Thanks for your instituion, it helps me a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment