[go: up one dir, main page]

0% found this document useful (0 votes)
3 views9 pages

SoftComputing5 Ipynb

Soft computing python codes

Uploaded by

Siddhi Bhardwaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views9 pages

SoftComputing5 Ipynb

Soft computing python codes

Uploaded by

Siddhi Bhardwaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

{

"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "4ahoHutkJVH_",
"outputId": "e968ef0a-e1d3-4c45-fb33-2a500c54bdb0"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Initial Population:\n",
"['01000', '10001', '00001', '01110', '10111', '11111']\n",
"Initial Fitness Scores: [8, 17, 1, 14, 23, 31]\n",
"\n",
"Selected Parents (Generation 1):\n",
"['00001', '00001', '01000', '01000', '01110', '01110']\n",
"Offspring After Crossover:\n",
"['00001', '00001', '01000', '01000', '01110', '01110']\n",
"Offspring After Mutation:\n",
"['00000', '00101', '01001', '01000', '01110', '01110']\n",
"Best Chromosome This Generation: 00001, Fitness = 1\n",
"\n",
"Selected Parents (Generation 2):\n",
"['01001', '01000', '00001', '00101', '00001', '00001']\n",
"Offspring After Crossover:\n",
"['01000', '01001', '00101', '00001', '00001', '00001']\n",
"Offspring After Mutation:\n",
"['01000', '01001', '00101', '00001', '00001', '00001']\n",
"Best Chromosome This Generation: 00001, Fitness = 1\n",
"\n",
"Selected Parents (Generation 3):\n",
"['00001', '00001', '00001', '00001', '00001', '00001']\n",
"Offspring After Crossover:\n",
"['00001', '00001', '00001', '00001', '00001', '00001']\n",
"Offspring After Mutation:\n",
"['00001', '00001', '00001', '00001', '00001', '00001']\n",
"Best Chromosome This Generation: 00001, Fitness = 1\n",
"\n",
"Selected Parents (Generation 4):\n",
"['00001', '00001', '00001', '00001', '00001', '00001']\n",
"Offspring After Crossover:\n",
"['00001', '00001', '00001', '00001', '00001', '00001']\n",
"Offspring After Mutation:\n",
"['00001', '00001', '00001', '00001', '00001', '00001']\n",
"Best Chromosome This Generation: 00001, Fitness = 1\n",
"\n",
"Selected Parents (Generation 5):\n",
"['00001', '00001', '00001', '00001', '00001', '00001']\n",
"Offspring After Crossover:\n",
"['00001', '00001', '00001', '00001', '00001', '00001']\n",
"Offspring After Mutation:\n",
"['00001', '00001', '10011', '00101', '00001', '00001']\n",
"Best Chromosome This Generation: 00001, Fitness = 1\n",
"\n",
"Selected Parents (Generation 6):\n",
"['00001', '00001', '00001', '00001', '00001', '00001']\n",
"Offspring After Crossover:\n",
"['00001', '00001', '00001', '00001', '00001', '00001']\n",
"Offspring After Mutation:\n",
"['00001', '00001', '00001', '00000', '00001', '00011']\n",
"Best Chromosome This Generation: 00000, Fitness = 0\n",
"\n",
"Selected Parents (Generation 7):\n",
"['00000', '00000', '00001', '00001', '00000', '00000']\n",
"Offspring After Crossover:\n",
"['00000', '00000', '00001', '00001', '00000', '00000']\n",
"Offspring After Mutation:\n",
"['00000', '00000', '00001', '00001', '00000', '00000']\n",
"Best Chromosome This Generation: 00000, Fitness = 0\n",
"\n",
"Selected Parents (Generation 8):\n",
"['00000', '00000', '00000', '00000', '00000', '00000']\n",
"Offspring After Crossover:\n",
"['00000', '00000', '00000', '00000', '00000', '00000']\n",
"Offspring After Mutation:\n",
"['00000', '00000', '00010', '00000', '00000', '00000']\n",
"Best Chromosome This Generation: 00000, Fitness = 0\n",
"\n",
"Selected Parents (Generation 9):\n",
"['00000', '00000', '00000', '00000', '00000', '00000']\n",
"Offspring After Crossover:\n",
"['00000', '00000', '00000', '00000', '00000', '00000']\n",
"Offspring After Mutation:\n",
"['10000', '00000', '00100', '01000', '10000', '00000']\n",
"Best Chromosome This Generation: 00000, Fitness = 0\n",
"\n",
"Selected Parents (Generation 10):\n",
"['00000', '00000', '00000', '00000', '00000', '00000']\n",
"Offspring After Crossover:\n",
"['00000', '00000', '00000', '00000', '00000', '00000']\n",
"Offspring After Mutation:\n",
"['01000', '00000', '00000', '00001', '00000', '00000']\n",
"Best Chromosome This Generation: 00000, Fitness = 0\n",
"\n",
"Best Chromosome Found: 00000 with fitness: 0\n"
]
}
],
"source": [
"import numpy as np\n",
"import random\n",
"import matplotlib.pyplot as plt\n",
"\n",
"def validate_binary_ga(pop_size, chrom_length, selection_method,
crossover_rate, mutation_rate):\n",
" if pop_size <= 0:\n",
" raise ValueError(\"Population size must be a positive integer.\")\
n",
" if chrom_length <= 0:\n",
" raise ValueError(\"Chromosome length must be greater than
zero.\")\n",
" if selection_method not in ['roulette', 'tournament']:\n",
" raise ValueError(\"Selection method must be either 'roulette' or
'tournament'.\")\n",
" if not (0 <= crossover_rate <= 1):\n",
" raise ValueError(\"Crossover rate must be between 0 and 1.\")\n",
" if not (0 <= mutation_rate <= 1):\n",
" raise ValueError(\"Mutation rate must be between 0 and 1.\")\n",
"\n",
"def generate_binary_population(pop_size, chrom_length):\n",
" return np.random.randint(0, 2, (pop_size, chrom_length))\n",
"\n",
"def fitness_min_binary(chrom):\n",
" return int(\"\".join(map(str, chrom)), 2)\n",
"\n",
"def tournament_selection_binary(population, fitness_scores, k=3):\n",
" selected = []\n",
" for _ in range(len(population)):\n",
" participants = np.random.choice(len(population), k,
replace=False)\n",
" winner = participants[np.argmin([fitness_scores[i] for i in
participants])] # minimize\n",
" selected.append(population[winner])\n",
" return np.array(selected)\n",
"\n",
"def single_point_crossover(p1, p2):\n",
" point = random.randint(1, len(p1) - 1)\n",
" c1 = np.concatenate([p1[:point], p2[point:]])\n",
" c2 = np.concatenate([p2[:point], p1[point:]])\n",
" return c1, c2\n",
"\n",
"def mutate_binary(chrom, mutation_rate):\n",
" for i in range(len(chrom)):\n",
" if random.random() < mutation_rate:\n",
" chrom[i] = 1 - chrom[i]\n",
" return chrom\n",
"\n",
"def binary_ga(pop_size, chrom_length, selection_method, crossover_rate,
mutation_rate, generations=10):\n",
" validate_binary_ga(pop_size, chrom_length, selection_method,
crossover_rate, mutation_rate)\n",
"\n",
" np.random.seed(42)\n",
" random.seed(42)\n",
"\n",
" population = generate_binary_population(pop_size, chrom_length)\n",
" fitness_scores = [fitness_min_binary(chrom) for chrom in population]\
n",
"\n",
" print(\"Initial Population:\")\n",
" print([''.join(map(str, c)) for c in population])\n",
" print(\"Initial Fitness Scores:\", fitness_scores)\n",
"\n",
" best_idx = np.argmin(fitness_scores)\n",
" best_chrom = population[best_idx]\n",
" best_fit = fitness_scores[best_idx]\n",
"\n",
" for gen in range(generations):\n",
" # Selection\n",
" selected = tournament_selection_binary(population, fitness_scores)
if selection_method == 'tournament' else population\n",
" print(f\"\\nSelected Parents (Generation {gen+1}):\")\n",
" print([''.join(map(str, c)) for c in selected])\n",
"\n",
" # Crossover\n",
" offspring = []\n",
" for i in range(0, pop_size, 2):\n",
" p1 = selected[i]\n",
" p2 = selected[i+1 if i+1 < pop_size else 0]\n",
" if random.random() < crossover_rate:\n",
" c1, c2 = single_point_crossover(p1, p2)\n",
" else:\n",
" c1, c2 = p1.copy(), p2.copy()\n",
" offspring.extend([c1, c2])\n",
"\n",
" print(\"Offspring After Crossover:\")\n",
" print([''.join(map(str, c)) for c in offspring])\n",
"\n",
" # Mutation\n",
" offspring = np.array([mutate_binary(c, mutation_rate) for c in
offspring])\n",
" print(\"Offspring After Mutation:\")\n",
" print([''.join(map(str, c)) for c in offspring])\n",
"\n",
" # Elitism\n",
" offspring[0] = best_chrom\n",
" population = offspring\n",
" fitness_scores = [fitness_min_binary(chrom) for chrom in
population]\n",
"\n",
" current_best_idx = np.argmin(fitness_scores)\n",
" current_best_fit = fitness_scores[current_best_idx]\n",
"\n",
" if current_best_fit < best_fit:\n",
" best_fit = current_best_fit\n",
" best_chrom = population[current_best_idx]\n",
"\n",
" print(f\"Best Chromosome This Generation: {''.join(map(str,
best_chrom))}, Fitness = {best_fit}\")\n",
"\n",
" print(\"\\nBest Chromosome Found:\", ''.join(map(str,
best_chrom)), \"with fitness:\", best_fit)\n",
"\n",
"binary_ga(pop_size=6, chrom_length=5,
selection_method='tournament',crossover_rate=0.8, mutation_rate=0.05,
generations=10)"
]
},
{
"cell_type": "code",
"source": [
"import numpy as np\n",
"import random\n",
"import matplotlib.pyplot as plt\n",
"\n",
"def validate_binary_ga(pop_size, chrom_length, selection_method,
crossover_rate, mutation_rate):\n",
" if pop_size <= 0:\n",
" raise ValueError(\"Population size must be a positive integer.\")\
n",
" if chrom_length <= 0:\n",
" raise ValueError(\"Chromosome length must be greater than
zero.\")\n",
" if selection_method not in ['roulette', 'tournament']:\n",
" raise ValueError(\"Selection method must be either 'roulette' or
'tournament'.\")\n",
" if not (0 <= crossover_rate <= 1):\n",
" raise ValueError(\"Crossover rate must be between 0 and 1.\")\n",
" if not (0 <= mutation_rate <= 1):\n",
" raise ValueError(\"Mutation rate must be between 0 and 1.\")\n",
"\n",
"def generate_binary_population(pop_size, chrom_length):\n",
" return np.random.randint(0, 2, (pop_size, chrom_length))\n",
"\n",
"def fitness_max_binary(chrom):\n",
" return np.sum(chrom) # count of 1's\n",
"\n",
"def tournament_selection_binary_max(population, fitness_scores, k=3):\n",
" selected = []\n",
" for _ in range(len(population)):\n",
" participants = np.random.choice(len(population), k,
replace=False)\n",
" winner = participants[np.argmax([fitness_scores[i] for i in
participants])] # maximize\n",
" selected.append(population[winner])\n",
" return np.array(selected)\n",
"\n",
"def single_point_crossover(p1, p2):\n",
" point = random.randint(1, len(p1)-1)\n",
" c1 = np.concatenate([p1[:point], p2[point:]])\n",
" c2 = np.concatenate([p2[:point], p1[point:]])\n",
" return c1, c2\n",
"\n",
"def mutate_binary(chrom, mutation_rate):\n",
" for i in range(len(chrom)):\n",
" if random.random() < mutation_rate:\n",
" chrom[i] = 1 - chrom[i]\n",
" return chrom\n",
"\n",
"\n",
"def binary_ga_max(pop_size, chrom_length, selection_method,
crossover_rate, mutation_rate, generations=10):\n",
" validate_binary_ga(pop_size, chrom_length, selection_method,
crossover_rate, mutation_rate)\n",
"\n",
" np.random.seed(42)\n",
" random.seed(42)\n",
"\n",
" population = generate_binary_population(pop_size, chrom_length)\n",
" fitness_scores = [fitness_max_binary(chrom) for chrom in population]\
n",
"\n",
" print(\"Initial Population:\")\n",
" print([''.join(map(str, c)) for c in population])\n",
" print(\"Initial Fitness Scores:\", fitness_scores)\n",
"\n",
" best_idx = np.argmax(fitness_scores)\n",
" best_chrom = population[best_idx]\n",
" best_fit = fitness_scores[best_idx]\n",
"\n",
" for gen in range(generations):\n",
" # Selection\n",
" selected = tournament_selection_binary_max(population,
fitness_scores) if selection_method == 'tournament' else population\n",
" print(f\"\\nSelected Parents (Generation {gen+1}):\")\n",
" print([''.join(map(str, c)) for c in selected])\n",
"\n",
" # Crossover\n",
" offspring = []\n",
" for i in range(0, pop_size, 2):\n",
" p1 = selected[i]\n",
" p2 = selected[i+1 if i+1 < pop_size else 0]\n",
" if random.random() < crossover_rate:\n",
" c1, c2 = single_point_crossover(p1, p2)\n",
" else:\n",
" c1, c2 = p1.copy(), p2.copy()\n",
" offspring.extend([c1, c2])\n",
"\n",
" print(\"Offspring After Crossover:\")\n",
" print([''.join(map(str, c)) for c in offspring])\n",
"\n",
" # Mutation\n",
" offspring = np.array([mutate_binary(c, mutation_rate) for c in
offspring])\n",
" print(\"Offspring After Mutation:\")\n",
" print([''.join(map(str, c)) for c in offspring])\n",
"\n",
" # Elitism\n",
" offspring[0] = best_chrom\n",
" population = offspring\n",
" fitness_scores = [fitness_max_binary(chrom) for chrom in
population]\n",
"\n",
" current_best_idx = np.argmax(fitness_scores)\n",
" current_best_fit = fitness_scores[current_best_idx]\n",
"\n",
" if current_best_fit > best_fit:\n",
" best_fit = current_best_fit\n",
" best_chrom = population[current_best_idx]\n",
"\n",
" print(f\"Best Chromosome This Generation: {''.join(map(str,
best_chrom))}, Fitness = {best_fit}\")\n",
"\n",
" print(\"\\nBest Chromosome Found:\", ''.join(map(str,
best_chrom)), \"with fitness:\", best_fit)\n",
"\n",
"binary_ga_max(pop_size=10, chrom_length=8,
selection_method='tournament',crossover_rate=0.7, mutation_rate=0.01,
generations=10)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "SE9WQq1iLAcn",
"outputId": "4c390dc6-7543-46f8-ece2-9a4cf2b6f67f"
},
"execution_count": 13,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Initial Population:\n",
"['01000100', '01000010', '11101011', '11111100', '11101000',
'00111110', '11010101', '10000000', '01101111', '01011101']\n",
"Initial Fitness Scores: [np.int64(2), np.int64(2), np.int64(6),
np.int64(6), np.int64(4), np.int64(5), np.int64(5), np.int64(1), np.int64(6),
np.int64(5)]\n",
"\n",
"Selected Parents (Generation 1):\n",
"['01101111', '11101011', '11101011', '11101011', '11101011',
'11111100', '11101011', '01000100', '11111100', '01101111']\n",
"Offspring After Crossover:\n",
"['01101011', '11101111', '11101011', '11101011', '11111100',
'11101011', '11101011', '01000100', '11111111', '01101100']\n",
"Offspring After Mutation:\n",
"['01101011', '11100111', '11101011', '11101011', '11111100',
'11101011', '11101011', '01000100', '11111111', '01101100']\n",
"Best Chromosome This Generation: 11111111, Fitness = 8\n",
"\n",
"Selected Parents (Generation 2):\n",
"['11111111', '11111111', '11101011', '11100111', '11100111',
'11101011', '11101011', '11101011', '11101011', '11100111']\n",
"Offspring After Crossover:\n",
"['11111111', '11111111', '11101011', '11100111', '11100111',
'11101011', '11101011', '11101011', '11101011', '11100111']\n",
"Offspring After Mutation:\n",
"['11111111', '11111111', '11101011', '11100110', '11100111',
'11101011', '11101011', '11101011', '11101011', '11100111']\n",
"Best Chromosome This Generation: 11111111, Fitness = 8\n",
"\n",
"Selected Parents (Generation 3):\n",
"['11111111', '11111111', '11111111', '11101011', '11101011',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Crossover:\n",
"['11111111', '11111111', '11111111', '11101011', '11111111',
'11101011', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Mutation:\n",
"['11111111', '11111111', '11111111', '11101111', '11111111',
'11101011', '11111111', '11111111', '11111111', '10111111']\n",
"Best Chromosome This Generation: 11111111, Fitness = 8\n",
"\n",
"Selected Parents (Generation 4):\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Crossover:\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Mutation:\n",
"['11101111', '11111111', '11111111', '01111110', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Best Chromosome This Generation: 11111111, Fitness = 8\n",
"\n",
"Selected Parents (Generation 5):\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Crossover:\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Mutation:\n",
"['11111111', '11111110', '11111111', '11111111', '11111111',
'10111111', '11111111', '11111111', '11111111', '11011111']\n",
"Best Chromosome This Generation: 11111111, Fitness = 8\n",
"\n",
"Selected Parents (Generation 6):\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Crossover:\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Mutation:\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'10111111', '11111111', '11111111', '11111111', '11111111']\n",
"Best Chromosome This Generation: 11111111, Fitness = 8\n",
"\n",
"Selected Parents (Generation 7):\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Crossover:\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Mutation:\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Best Chromosome This Generation: 11111111, Fitness = 8\n",
"\n",
"Selected Parents (Generation 8):\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Crossover:\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Mutation:\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111101', '11111111']\n",
"Best Chromosome This Generation: 11111111, Fitness = 8\n",
"\n",
"Selected Parents (Generation 9):\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Crossover:\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Mutation:\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111101', '11111111', '11111111', '11111111']\n",
"Best Chromosome This Generation: 11111111, Fitness = 8\n",
"\n",
"Selected Parents (Generation 10):\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Crossover:\n",
"['11111111', '11111111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Offspring After Mutation:\n",
"['11111111', '11101111', '11111111', '11111111', '11111111',
'11111111', '11111111', '11111111', '11111111', '11111111']\n",
"Best Chromosome This Generation: 11111111, Fitness = 8\n",
"\n",
"Best Chromosome Found: 11111111 with fitness: 8\n"
]
}
]
}
]
}

You might also like