Newer
Older
"display_visual(romania_graph_data, user_input=False, \n",
" algorithm=astar_search, \n",
" problem=romania_problem)"
"source": [
"all_node_colors = []\n",
"# display_visual(romania_graph_data, user_input=True, algorithm=breadth_first_tree_search)\n",
"algorithms = { \"Breadth First Tree Search\": breadth_first_tree_search,\n",
" \"Depth First Tree Search\": depth_first_tree_search,\n",
" \"Breadth First Search\": breadth_first_search,\n",
" \"Depth First Graph Search\": depth_first_graph_search,\n",
" \"Uniform Cost Search\": uniform_cost_search,\n",
" \"A-star Search\": astar_search}\n",
"display_visual(romania_graph_data, algorithm=algorithms, user_input=True)"
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Different heuristics provide different efficiency in solving A* problems which are generally defined by the number of explored nodes as well as the branching factor. With the classic 8 puzzle we can show the efficiency of different heuristics through the number of explored nodes.\n",
"The *8 Puzzle Problem* consists of a 3x3 tray in which the goal is to get the initial configuration to the goal state by shifting the numbered tiles into the blank space.\n",
" Initial State Goal State\n",
" | 7 | 2 | 4 | | 0 | 1 | 2 |\n",
" | 5 | 0 | 6 | | 3 | 4 | 5 |\n",
" | 8 | 3 | 1 | | 6 | 7 | 8 |\n",
" \n",
"We have a total of 9 blank tiles giving us a total of 9! initial configuration but not all of these are solvable. The solvability of a configuration can be checked by calculating the Inversion Permutation. If the total Inversion Permutation is even then the initial configuration is solvable else the initial configuration is not solvable which means that only 9!/2 initial states lead to a solution.\n",
"1) Manhattan Distance:- For the 8 puzzle problem Manhattan distance is defined as the distance of a tile from its goal state( for the tile numbered '1' in the initial configuration Manhattan distance is 4 \"2 for left and 2 for upward displacement\").\n",
"2) No. of Misplaced Tiles:- The heuristic calculates the number of misplaced tiles between the current state and goal state.\n",
"3) Sqrt of Manhattan Distance:- It calculates the square root of Manhattan distance.\n",
"4) Max Heuristic:- It assign the score as the maximum between \"Manhattan Distance\" and \"No. of Misplaced Tiles\". "
"metadata": {
"collapsed": true
},
"def linear(state,goal):\n",
" return sum([1 if state[i] != goal[i] else 0 for i in range(8)])\n",
"\n",
"def manhanttan(state,goal):\n",
" index_goal = {0:[2,2], 1:[0,0], 2:[0,1], 3:[0,2], 4:[1,0], 5:[1,1], 6:[1,2], 7:[2,0], 8:[2,1]}\n",
" index_state = {}\n",
" index = [[0,0], [0,1], [0,2], [1,0], [1,1], [1,2], [2,0], [2,1], [2,2]]\n",
" x, y = 0, 0\n",
" \n",
" for i in range(len(state)):\n",
" index_state[state[i]] = index[i]\n",
" \n",
" mhd = 0\n",
" \n",
" for i in range(8):\n",
" for j in range(2):\n",
" mhd = abs(index_goal[i][j] - index_state[i][j]) + mhd\n",
" \n",
" return mhd\n",
"\n",
"def sqrt_manhanttan(state,goal):\n",
" index_goal = {0:[2,2], 1:[0,0], 2:[0,1], 3:[0,2], 4:[1,0], 5:[1,1], 6:[1,2], 7:[2,0], 8:[2,1]}\n",
" index_state = {}\n",
" index = [[0,0], [0,1], [0,2], [1,0], [1,1], [1,2], [2,0], [2,1], [2,2]]\n",
" x, y = 0, 0\n",
" \n",
" for i in range(len(state)):\n",
" index_state[state[i]] = index[i]\n",
" \n",
" mhd = 0\n",
" \n",
" for i in range(8):\n",
" for j in range(2):\n",
" mhd = (index_goal[i][j] - index_state[i][j])**2 + mhd\n",
" \n",
" return math.sqrt(mhd)\n",
"\n",
"def max_heuristic(state,goal):\n",
" score1 = manhanttan(state, goal)\n",
" score2 = linear(state, goal)\n",
" return max(score1, score2)"
"execution_count": null,
"metadata": {},
"outputs": [],
"# Solving the puzzle \n",
"puzzle = EightPuzzle()\n",
"puzzle.checkSolvability([2,4,3,1,5,6,7,8,0]) # checks whether the initialized configuration is solvable or not\n",
"puzzle.solve([2,4,3,1,5,6,7,8,0], [1,2,3,4,5,6,7,8,0],max_heuristic) # Max_heuristic\n",
"puzzle.solve([2,4,3,1,5,6,7,8,0], [1,2,3,4,5,6,7,8,0],linear) # Linear\n",
"puzzle.solve([2,4,3,1,5,6,7,8,0], [1,2,3,4,5,6,7,8,0],manhanttan) # Manhattan\n",
"puzzle.solve([2,4,3,1,5,6,7,8,0], [1,2,3,4,5,6,7,8,0],sqrt_manhanttan) # Sqrt_manhattan"
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## HILL CLIMBING\n",
"\n",
"Hill Climbing is a heuristic search used for optimization problems.\n",
"Given a large set of inputs and a good heuristic function, it tries to find a sufficiently good solution to the problem. \n",
"This solution may or may not be the global optimum.\n",
"The algorithm is a variant of generate and test algorithm. \n",
"<br>\n",
"As a whole, the algorithm works as follows:\n",
"- Evaluate the initial state.\n",
"- If it is equal to the goal state, return.\n",
"- Find a neighboring state (one which is heuristically similar to the current state)\n",
"- Evaluate this state. If it is closer to the goal state than before, replace the initial state with this state and repeat these steps.\n",
"<br>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"psource(hill_climbing)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will find an approximate solution to the traveling salespersons problem using this algorithm.\n",
"<br>\n",
"We need to define a class for this problem.\n",
"<br>\n",
"`Problem` will be used as a base class."
]
},
{
"cell_type": "code",
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"class TSP_problem(Problem):\n",
"\n",
" \"\"\" subclass of Problem to define various functions \"\"\"\n",
"\n",
" def two_opt(self, state):\n",
" \"\"\" Neighbour generating function for Traveling Salesman Problem \"\"\"\n",
" neighbour_state = state[:]\n",
" left = random.randint(0, len(neighbour_state) - 1)\n",
" right = random.randint(0, len(neighbour_state) - 1)\n",
" if left > right:\n",
" left, right = right, left\n",
" neighbour_state[left: right + 1] = reversed(neighbour_state[left: right + 1])\n",
" return neighbour_state\n",
"\n",
" def actions(self, state):\n",
" \"\"\" action that can be excuted in given state \"\"\"\n",
" return [self.two_opt]\n",
"\n",
" def result(self, state, action):\n",
" \"\"\" result after applying the given action on the given state \"\"\"\n",
" return action(state)\n",
"\n",
" def path_cost(self, c, state1, action, state2):\n",
" \"\"\" total distance for the Traveling Salesman to be covered if in state2 \"\"\"\n",
" cost = 0\n",
" for i in range(len(state2) - 1):\n",
" cost += distances[state2[i]][state2[i + 1]]\n",
" cost += distances[state2[0]][state2[-1]]\n",
" return cost\n",
"\n",
" def value(self, state):\n",
" \"\"\" value of path cost given negative for the given state \"\"\"\n",
" return -1 * self.path_cost(None, None, None, state)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will use cities from the Romania map as our cities for this problem.\n",
"<br>\n",
"A list of all cities and a dictionary storing distances between them will be populated."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
"source": [
"distances = {}\n",
"all_cities = []\n",
"\n",
"for city in romania_map.locations.keys():\n",
" distances[city] = {}\n",
" all_cities.append(city)\n",
" \n",
"all_cities.sort()\n",
"print(all_cities)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, we need to populate the individual lists inside the dictionary with the manhattan distance between the cities."
]
},
{
"cell_type": "code",
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"for name_1, coordinates_1 in romania_map.locations.items():\n",
" for name_2, coordinates_2 in romania_map.locations.items():\n",
" distances[name_1][name_2] = np.linalg.norm(\n",
" [coordinates_1[0] - coordinates_2[0], coordinates_1[1] - coordinates_2[1]])\n",
" distances[name_2][name_1] = np.linalg.norm(\n",
" [coordinates_1[0] - coordinates_2[0], coordinates_1[1] - coordinates_2[1]])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The way neighbours are chosen currently isn't suitable for the travelling salespersons problem.\n",
"We need a neighboring state that is similar in total path distance to the current state.\n",
"<br>\n",
"We need to change the function that finds neighbors."
]
},
{
"cell_type": "code",
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def hill_climbing(problem):\n",
" \n",
" \"\"\"From the initial node, keep choosing the neighbor with highest value,\n",
" stopping when no neighbor is better. [Figure 4.2]\"\"\"\n",
" \n",
" def find_neighbors(state, number_of_neighbors=100):\n",
" \"\"\" finds neighbors using two_opt method \"\"\"\n",
" \n",
" neighbors = []\n",
" \n",
" for i in range(number_of_neighbors):\n",
" new_state = problem.two_opt(state)\n",
" neighbors.append(Node(new_state))\n",
" state = new_state\n",
" \n",
" return neighbors\n",
"\n",
" # as this is a stochastic algorithm, we will set a cap on the number of iterations\n",
" iterations = 10000\n",
" \n",
" current = Node(problem.initial)\n",
" while iterations:\n",
" neighbors = find_neighbors(current.state)\n",
" if not neighbors:\n",
" break\n",
" neighbor = argmax_random_tie(neighbors,\n",
" key=lambda node: problem.value(node.state))\n",
" if problem.value(neighbor.state) <= problem.value(current.state):\n",
" current.state = neighbor.state\n",
" iterations -= 1\n",
" \n",
" return current.state"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"An instance of the TSP_problem class will be created."
]
},
{
"cell_type": "code",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"tsp = TSP_problem(all_cities)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can now generate an approximate solution to the problem by calling `hill_climbing`.\n",
"The results will vary a bit each time you run it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"hill_climbing(tsp)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The solution looks like this.\n",
"It is not difficult to see why this might be a good solution.\n",
"<br>\n",
""
]
},
{
"cell_type": "markdown",
"\n",
"Genetic algorithms (or GA) are inspired by natural evolution and are particularly useful in optimization and search problems with large state spaces.\n",
"\n",
"Given a problem, algorithms in the domain make use of a *population* of solutions (also called *states*), where each solution/state represents a feasible solution. At each iteration (often called *generation*), the population gets updated using methods inspired by biology and evolution, like *crossover*, *mutation* and *natural selection*."
]
},
{
"cell_type": "markdown",
"source": [
"### Overview\n",
"\n",
"A genetic algorithm works in the following way:\n",
"\n",
"1) Initialize random population.\n",
"\n",
"2) Calculate population fitness.\n",
"\n",
"3) Select individuals for mating.\n",
"\n",
"4) Mate selected individuals to produce new population.\n",
"\n",
" * Random chance to mutate individuals.\n",
"\n",
"5) Repeat from step 2) until an individual is fit enough or the maximum number of iterations was reached."
]
},
{
"cell_type": "markdown",
"### Glossary\n",
"\n",
"Before we continue, we will lay the basic terminology of the algorithm.\n",
"\n",
"* Individual/State: A list of elements (called *genes*) that represent possible solutions.\n",
"* Population: The list of all the individuals/states.\n",
"\n",
"* Gene pool: The alphabet of possible values for an individual's genes.\n",
"\n",
"* Generation/Iteration: The number of times the population will be updated.\n",
"\n",
"* Fitness: An individual's score, calculated by a function specific to the problem."
]
},
{
"cell_type": "markdown",
"### Crossover\n",
"\n",
"Two individuals/states can \"mate\" and produce one child. This offspring bears characteristics from both of its parents. There are many ways we can implement this crossover. Here we will take a look at the most common ones. Most other methods are variations of those below.\n",
"\n",
"* Point Crossover: The crossover occurs around one (or more) point. The parents get \"split\" at the chosen point or points and then get merged. In the example below we see two parents get split and merged at the 3rd digit, producing the following offspring after the crossover.\n",
"\n",
"\n",
"\n",
"* Uniform Crossover: This type of crossover chooses randomly the genes to get merged. Here the genes 1, 2 and 5 were chosen from the first parent, so the genes 3, 4 were added by the second parent.\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"### Mutation\n",
"\n",
"When an offspring is produced, there is a chance it will mutate, having one (or more, depending on the implementation) of its genes altered.\n",
"\n",
"For example, let's say the new individual to undergo mutation is \"abcde\". Randomly we pick to change its third gene to 'z'. The individual now becomes \"abzde\" and is added to the population."
]
},
{
"cell_type": "markdown",
"At each iteration, the fittest individuals are picked randomly to mate and produce offsprings. We measure an individual's fitness with a *fitness function*. That function depends on the given problem and it is used to score an individual. Usually the higher the better.\n",
"The selection process is this:\n",
"1) Individuals are scored by the fitness function.\n",
"\n",
"2) Individuals are picked randomly, according to their score (higher score means higher chance to get picked). Usually the formula to calculate the chance to pick an individual is the following (for population *P* and individual *i*):\n",
"\n",
"$$ chance(i) = \\dfrac{fitness(i)}{\\sum_{k \\, in \\, P}{fitness(k)}} $$"
]
},
{
"cell_type": "markdown",
"### Implementation\n",
"\n",
"Below we look over the implementation of the algorithm in the `search` module.\n",
"\n",
"First the implementation of the main core of the algorithm:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
Aman Deep Singh
a validé
"psource(genetic_algorithm)"
]
},
{
"cell_type": "markdown",
"source": [
"The algorithm takes the following input:\n",
"\n",
"* `population`: The initial population.\n",
"\n",
"* `fitness_fn`: The problem's fitness function.\n",
"\n",
"* `gene_pool`: The gene pool of the states/individuals. By default 0 and 1.\n",
"* `f_thres`: The fitness threshold. If an individual reaches that score, iteration stops. By default 'None', which means the algorithm will not halt until the generations are ran.\n",
"\n",
"* `ngen`: The number of iterations/generations.\n",
"\n",
"* `pmut`: The probability of mutation.\n",
"\n",
"The algorithm gives as output the state with the largest score."
]
},
{
"cell_type": "markdown",
"For each generation, the algorithm updates the population. First it calculates the fitnesses of the individuals, then it selects the most fit ones and finally crosses them over to produce offsprings. There is a chance that the offspring will be mutated, given by `pmut`. If at the end of the generation an individual meets the fitness threshold, the algorithm halts and returns that individual.\n",
"\n",
Aman Deep Singh
a validé
"The function of mating is accomplished by the method `recombine`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
Aman Deep Singh
a validé
"source": [
"psource(recombine)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The method picks at random a point and merges the parents (`x` and `y`) around it.\n",
"\n",
"The mutation is done in the method `mutate`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
Aman Deep Singh
a validé
"source": [
"psource(mutate)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We pick a gene in `x` to mutate and a gene from the gene pool to replace it with.\n",
"\n",
"To help initializing the population we have the helper function `init_population`\":"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
Aman Deep Singh
a validé
"source": [
"psource(init_population)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The function takes as input the number of individuals in the population, the gene pool and the length of each individual/state. It creates individuals with random genes and returns the population when done."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Explanation\n",
"\n",
"Before we solve problems using the genetic algorithm, we will explain how to intuitively understand the algorithm using a trivial example.\n",
Aman Deep Singh
a validé
"\n",
"#### Generating Phrases\n",
"\n",
"In this problem, we use a genetic algorithm to generate a particular target phrase from a population of random strings. This is a classic example that helps build intuition about how to use this algorithm in other problems as well. Before we break the problem down, let us try to brute force the solution. Let us say that we want to generate the phrase \"genetic algorithm\". The phrase is 17 characters long. We can use any character from the 26 lowercase characters and the space character. To generate a random phrase of length 17, each space can be filled in 27 ways. So the total number of possible phrases is\n",
"\n",
"$$ 27^{17} = 2153693963075557766310747 $$\n",
"\n",
"which is a massive number. If we wanted to generate the phrase \"Genetic Algorithm\", we would also have to include all the 26 uppercase characters into consideration thereby increasing the sample space from 27 characters to 53 characters and the total number of possible phrases then would be\n",
"\n",
"$$ 53^{17} = 205442259656281392806087233013 $$\n",
"\n",
"If we wanted to include punctuations and numerals into the sample space, we would have further complicated an already impossible problem. Hence, brute forcing is not an option. Now we'll apply the genetic algorithm and see how it significantly reduces the search space. We essentially want to *evolve* our population of random strings so that they better approximate the target phrase as the number of generations increase. Genetic algorithms work on the principle of Darwinian Natural Selection according to which, there are three key concepts that need to be in place for evolution to happen. They are:\n",
"\n",
"* **Heredity**: There must be a process in place by which children receive the properties of their parents. <br> \n",
Aman Deep Singh
a validé
"For this particular problem, two strings from the population will be chosen as parents and will be split at a random index and recombined as described in the `recombine` function to create a child. This child string will then be added to the new generation.\n",
"\n",
"\n",
"* **Variation**: There must be a variety of traits present in the population or a means with which to introduce variation. <br>If there is no variation in the sample space, we might never reach the global optimum. To ensure that there is enough variation, we can initialize a large population, but this gets computationally expensive as the population gets larger. Hence, we often use another method called mutation. In this method, we randomly change one or more characters of some strings in the population based on a predefined probability value called the mutation rate or mutation probability as described in the `mutate` function. The mutation rate is usually kept quite low. A mutation rate of zero fails to introduce variation in the population and a high mutation rate (say 50%) is as good as a coin flip and the population fails to benefit from the previous recombinations. An optimum balance has to be maintained between population size and mutation rate so as to reduce the computational cost as well as have sufficient variation in the population.\n",
"\n",
"\n",
"* **Selection**: There must be some mechanism by which some members of the population have the opportunity to be parents and pass down their genetic information and some do not. This is typically referred to as \"survival of the fittest\". <br>\n",
Aman Deep Singh
a validé
"There has to be some way of determining which phrases in our population have a better chance of eventually evolving into the target phrase. This is done by introducing a fitness function that calculates how close the generated phrase is to the target phrase. The function will simply return a scalar value corresponding to the number of matching characters between the generated phrase and the target phrase."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Before solving the problem, we first need to define our target phrase."
]
},
{
"cell_type": "code",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
Aman Deep Singh
a validé
"target = 'Genetic Algorithm'"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"We then need to define our gene pool, i.e the elements which an individual from the population might comprise of. Here, the gene pool contains all uppercase and lowercase letters of the English alphabet and the space character."
]
},
{
"cell_type": "code",
Aman Deep Singh
a validé
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# The ASCII values of uppercase characters ranges from 65 to 91\n",
"u_case = [chr(x) for x in range(65, 91)]\n",
"# The ASCII values of lowercase characters ranges from 97 to 123\n",
"l_case = [chr(x) for x in range(97, 123)]\n",
"\n",
"gene_pool = []\n",
"gene_pool.extend(u_case) # adds the uppercase list to the gene pool\n",
"gene_pool.extend(l_case) # adds the lowercase list to the gene pool\n",
"gene_pool.append(' ') # adds the space character to the gene pool"
]
},
{
"cell_type": "markdown",
Aman Deep Singh
a validé
"We now need to define the maximum size of each population. Larger populations have more variation but are computationally more expensive to run algorithms on."
]
},
{
"cell_type": "code",
Aman Deep Singh
a validé
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"max_population = 100"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As our population is not very large, we can afford to keep a relatively large mutation rate."
]
},
{
"cell_type": "code",
Aman Deep Singh
a validé
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"mutation_rate = 0.07 # 7%"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Great! Now, we need to define the most important metric for the genetic algorithm, i.e the fitness function. This will simply return the number of matching characters between the generated sample and the target phrase."
]
},
{
"cell_type": "code",
Aman Deep Singh
a validé
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def fitness_fn(sample):\n",
" # initialize fitness to 0\n",
" fitness = 0\n",
" for i in range(len(sample)):\n",
" # increment fitness by 1 for every matching character\n",
" if sample[i] == target[i]:\n",
" fitness += 1\n",
" return fitness"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Before we run our genetic algorithm, we need to initialize a random population. We will use the `init_population` function to do this. We need to pass in the maximum population size, the gene pool and the length of each individual, which in this case will be the same as the length of the target phrase."
]
},
{
"cell_type": "code",
Aman Deep Singh
a validé
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"population = init_population(max_population, gene_pool, len(target))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will now define how the individuals in the population should change as the number of generations increases. First, the `select` function will be run on the population to select *two* individuals with high fitness values. These will be the parents which will then be recombined using the `recombine` function to generate the child."
]
},
{
"cell_type": "code",
Aman Deep Singh
a validé
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"parents = select(2, population, fitness_fn) "
]
},
{
"cell_type": "code",
Aman Deep Singh
a validé
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# The recombine function takes two parents as arguments, so we need to unpack the previous variable\n",
"child = recombine(*parents)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, we need to apply a mutation according to the mutation rate. We call the `mutate` function on the child with the gene pool and mutation rate as the additional arguments."
]
},
{
"cell_type": "code",
Aman Deep Singh
a validé
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"child = mutate(child, gene_pool, mutation_rate)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The above lines can be condensed into\n",
Aman Deep Singh
a validé
"`child = mutate(recombine(*select(2, population, fitness_fn)), gene_pool, mutation_rate)`\n",
"\n",
"And, we need to do this `for` every individual in the current population to generate the new population."
]
},
{
"cell_type": "code",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
Aman Deep Singh
a validé
"population = [mutate(recombine(*select(2, population, fitness_fn)), gene_pool, mutation_rate) for i in range(len(population))]"
]
},
{
"cell_type": "markdown",
Aman Deep Singh
a validé
"The individual with the highest fitness can then be found using the `max` function."
]
},
{
"cell_type": "code",
Aman Deep Singh
a validé
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"current_best = max(population, key=fitness_fn)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's print this out"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
Aman Deep Singh
a validé
"source": [
"print(current_best)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We see that this is a list of characters. This can be converted to a string using the join function"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
Aman Deep Singh
a validé
"source": [
"current_best_string = ''.join(current_best)\n",
"print(current_best_string)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We now need to define the conditions to terminate the algorithm. This can happen in two ways\n",
"1. Termination after a predefined number of generations\n",
"2. Termination when the fitness of the best individual of the current generation reaches a predefined threshold value.\n",
Aman Deep Singh
a validé
"We define these variables below"
]
},
{
"cell_type": "code",
Aman Deep Singh
a validé
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"ngen = 1200 # maximum number of generations\n",
"# we set the threshold fitness equal to the length of the target phrase\n",
"# i.e the algorithm only terminates whne it has got all the characters correct \n",
"# or it has completed 'ngen' number of generations\n",
"f_thres = len(target)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"To generate `ngen` number of generations, we run a `for` loop `ngen` number of times. After each generation, we calculate the fitness of the best individual of the generation and compare it to the value of `f_thres` using the `fitness_threshold` function. After every generation, we print out the best individual of the generation and the corresponding fitness value. Lets now write a function to do this."
]
},
{
"cell_type": "code",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
Aman Deep Singh
a validé
"def genetic_algorithm_stepwise(population, fitness_fn, gene_pool=[0, 1], f_thres=None, ngen=1200, pmut=0.1):\n",
" for generation in range(ngen):\n",
" population = [mutate(recombine(*select(2, population, fitness_fn)), gene_pool, pmut) for i in range(len(population))]\n",
" # stores the individual genome with the highest fitness in the current population\n",
" current_best = ''.join(max(population, key=fitness_fn))\n",
" print(f'Current best: {current_best}\\t\\tGeneration: {str(generation)}\\t\\tFitness: {fitness_fn(current_best)}\\r', end='')\n",
" \n",
" # compare the fitness of the current best individual to f_thres\n",
" fittest_individual = fitness_threshold(fitness_fn, f_thres, population)\n",
" \n",
" # if fitness is greater than or equal to f_thres, we terminate the algorithm\n",
" if fittest_individual:\n",
" return fittest_individual, generation\n",
" return max(population, key=fitness_fn) , generation "
]
},
{
"cell_type": "markdown",
Aman Deep Singh
a validé
"The function defined above is essentially the same as the one defined in `search.py` with the added functionality of printing out the data of each generation."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
Aman Deep Singh
a validé
"source": [
"psource(genetic_algorithm)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We have defined all the required functions and variables. Let's now create a new population and test the function we wrote above."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
Aman Deep Singh
a validé
"source": [
"population = init_population(max_population, gene_pool, len(target))\n",
"solution, generations = genetic_algorithm_stepwise(population, fitness_fn, gene_pool, f_thres, ngen, mutation_rate)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The genetic algorithm was able to converge!\n",
"We implore you to rerun the above cell and play around with `target, max_population, f_thres, ngen` etc parameters to get a better intuition of how the algorithm works. To summarize, if we can define the problem states in simple array format and if we can create a fitness function to gauge how good or bad our approximate solutions are, there is a high chance that we can get a satisfactory solution using a genetic algorithm. \n",
"- There is also a better GUI version of this program `genetic_algorithm_example.py` in the GUI folder for you to play around with."
]
},
{
"cell_type": "markdown",
"source": [
"### Usage\n",
"Below we give two example usages for the genetic algorithm, for a graph coloring problem and the 8 queens problem.\n",
"First we will take on the simpler problem of coloring a small graph with two colors. Before we do anything, let's imagine how a solution might look. First, we have to represent our colors. Say, 'R' for red and 'G' for green. These make up our gene pool. What of the individual solutions though? For that, we will look at our problem. We stated we have a graph. A graph has nodes and edges, and we want to color the nodes. Naturally, we want to store each node's color. If we have four nodes, we can store their colors in a list of genes, one for each node. A possible solution will then look like this: ['R', 'R', 'G', 'R']. In the general case, we will represent each solution with a list of chars ('R' and 'G'), with length the number of nodes.\n",
"Next we need to come up with a fitness function that appropriately scores individuals. Again, we will look at the problem definition at hand. We want to color a graph. For a solution to be optimal, no edge should connect two nodes of the same color. How can we use this information to score a solution? A naive (and ineffective) approach would be to count the different colors in the string. So ['R', 'R', 'R', 'R'] has a score of 1 and ['R', 'R', 'G', 'G'] has a score of 2. Why that fitness function is not ideal though? Why, we forgot the information about the edges! The edges are pivotal to the problem and the above function only deals with node colors. We didn't use all the information at hand and ended up with an ineffective answer. How, then, can we use that information to our advantage?\n",
"We said that the optimal solution will have all the edges connecting nodes of different color. So, to score a solution we can count how many edges are valid (aka connecting nodes of different color). That is a great fitness function!\n",
"Let's jump into solving this problem using the `genetic_algorithm` function."
]
},
{
"cell_type": "markdown",
"source": [
"First we need to represent the graph. Since we mostly need information about edges, we will just store the edges. We will denote edges with capital letters and nodes with integers:"
]
},
{
"cell_type": "code",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"edges = {\n",
" 'A': [0, 1],\n",
" 'B': [0, 3],\n",
" 'C': [1, 2],\n",
" 'D': [2, 3]\n",
"}"
]
},
{
"cell_type": "markdown",
"Edge 'A' connects nodes 0 and 1, edge 'B' connects nodes 0 and 3 etc.\n",
"\n",
"We already said our gene pool is 'R' and 'G', so we can jump right into initializing our population. Since we have only four nodes, `state_length` should be 4. For the number of individuals, we will try 8. We can increase this number if we need higher accuracy, but be careful! Larger populations need more computating power and take longer. You need to strike that sweet balance between accuracy and cost (the ultimate dilemma of the programmer!)."