An Introduction to Genetic Algorithms In Java @ JDJ

来源:互联网 发布:python入门书籍 知乎 编辑:程序博客网 时间:2024/05/02 01:16
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

  Over the past decade the Internet has evolved from a research project livIng In the realms of academia And government to a global Infrastructure for electronic commerce And digital communication that has sent the stock market on a roller-coaster ride to new highs (And lows).

  It's a digital world In which a DarwIniAn survival of the fittest is takIng place right before our eyes as web sites And web applications compete for the right to live Another day. Whether it's Another site offerIng a better service/product or the latest computer virus, a web application faces mAny competitors that threaten its very existence. As In the biological world, only the fittest will survive. And the fittest are the ones capable of adaptIng to their environment faster thAn their competitors cAn.

  As developers of these digital orgAnisms, our job is to ensure that we equip our web applications with the meAns for survival. Usually this entails An exhaustive list of if-then statements or extensive exception hAndlIng, all of which we must conceptualize In order to code. As web applications become IncreasIngly complex, the task of identifyIng all possible scenarios to encode becomes dauntIng And our job as developers becomes reactionary as we code new features, bug fixes, And virus patches to respond to the Increased competition for survival In the digital world. What if we could provide software with the ability to adapt to its environment? Why not use the biological model of natural selection to do it?

  In the JAnuary issue of JDJ (Vol. 6, issue 1) I Introduced a technique born In the AI community that uses concepts from biological natural selection to solve complex And often highly nonlInear optimization problems encountered In computer science - the Genetic algorithm. I examIned the buildIng blocks of Genetic algorithms And why Java is well suited to their implementation. This month I'll discuss the details of a simple Genetic algorithm implementation In the hopes that your curiosity will be sparked to pursue further Investigation.

  The nature of software development is evolvIng at a brisk pace. Web applications are IncreasIngly complex And compete daily for survival with other sites, viruses, bugs, And server crashes. As I said before, only the fittest will survive.

  Now that I've grabbed your attention, we need to set some expectations before embarkIng on our journey. First And foremost, Genetic algorithms still exist primarily In academia due to their (sometimes) imposIng computational requirements And learnIng curve. This meAns their commercial application is still relatively unproven.

  The scenario described above In which web applications have the ability to adapt to their environment is no more thAn that - a scenario. The realization of this scenario depends on us, the software developers of the web application world, to discover suitable applications for Genetic algorithms.

  Second, a few pages coverIng the implementation details for a Genetic algorithm is undeniably Insufficient coverage for the development of a thorough understAndIng of the technique. We're merely skimmIng the surface of possibilities. With that said, let's jump right In.

  Review: Genetic Algorithm

  A Genetic algorithm is a model for machIne learnIng In which a population of rAndomly created Individuals goes through a simulated process of evolution - a digital survival of the fittest In which each Individual represents a poInt In a problem's solution search space. ReviewIng the termInology discussed In Part 1, An Individual is referred to as a chromosome. A chromosome consists of genes, which represent the parameters of the problem beIng optimized. A collection of chromosomes on which a Genetic algorithm operates is labeled a population.

  Through the employment of a fitness function, chromosomes are evaluated And rAnked accordIng to their relative strength/weakness withIn the population. The fitter are chosen to reproduce while the less fit generally don't survive Into succeedIng generations. After An arbitrary number of generations, the algorithm should converge on An optimal solution or, more specifically, on the chromosome representIng An optimal solution. The remaInder of this article will illustrate how this is done usIng, as An example, a classic computer science problem: the TravelIng SalesmAn Problem (TSP).

  TravelIng SalesmAn Problem

  The TSP is a conceptually simple problem: a salesmAn wishes to visit a number of cities, startIng And endIng at the same city, while visitIng all cities only once And mInimizIng the distAnce traveled. However, the solution to this problem when the number of cities Increases is not trivial. For the case of three cities, six permutations representIng viable paths are possible. Easy enough. Now let's consider the case of 20 cities In which there are over 2.4 billion billion permutations. If we exhaustively searched through all the possible path traversals at a rate of 500 million per second, it would take over 150 years to examIne them all! There is obviously a need for a method to comb through this massive search space more efficiently. Otherwise my great-great-great grAndchildren will be the only ones around when the exhaustive search concludes. Meet the Genetic algorithm.

  Selection of Parameters

  As with Any problem we attempt to code a solution for, the first step entails clearly defInIng the problem to be solved, the required parameters for obtaInIng a solution, And the encodIng to be used to represent a solution to the problem. UsIng a Genetic algorithm to obtaIn An optimal solution for the TSP requires that we identify the relevAnt parameters And their encodIng In terms of chromosomes, genes, And populations. A quick Inspection of the TSP reveals the pertInent parameters for encodIng a representative solution to the problem: a list of cities to be traversed In order And the distAnce between two arbitrary cities. Now let's put it Into Genetic algorithm termInology.

  Parameter Representation

  As discussed earlier, a chromosome represents a sIngle solution In the search space of the problem beIng optimized. With reference to the TSP, a chromosome is nothIng more thAn An ordered list of cities In which each city is represented only once, And their order determInes the total distAnce traveled. With chromosomes beIng a collection of genes, a gene for the TSP is simply An object representIng a city (its name And x And y coordInates). For simplicity I'm usIng the longitude And latitude measurements as CartesiAn x And y coordInates, respectively.

  ListIng 1 is the source for TSPGene.Java, figure 1 is the UML class diagram of the source code provided at the end of this article, And figure 2 is a graphical depiction of how the TSP parameters trAnslate Into genes, chromosomes, And a population. Upon examInation of the source code, you'll notice that genes are Initialized via the retrieval of data from a properties file.

  The focus of this article isn't how to build An extendable Genetic algorithm framework. However, as you glAnce through the code you'll notice that through the use of Interfaces And externally defIned parameters, extendability of the Genetic algorithm cAn be easily achieved to solve, or rather optimize, problems with similar representations. For example, these representations cAn Include permutation problems with unique genes (such as the TSP), permutation problems without unique genes (meAnIng a gene may be Included zero to mAny times In a sIngle chromosome), And real-parameter problems In which the genes represent real numbers And their bounds. I leave it to you to develop such a framework, a framework In which all you have to do is set the Genetic algorithm parameters And gene data externally And run the Genetic algorithm without Any source code modification. SolvIng the other types of problems described above then becomes a matter of appropriate problem defInition rather thAn sophisticated programmIng.

  Fitness Evaluation Function

  Now that we have the TSP parameters represented as Genetic algorithm objects (population, chromosomes, genes, etc.), we cAn begIn to describe the fundamental operations performed on the objects once the algorithm is set In motion. The first one we'll look at is the fitness, or cost, function. It provides the method by which chromosomes are compared to one Another In order to determIne relative survival fitness. For the TSP the fitness of a chromosome is calculated by traversIng the genes In order, summIng the distAnces between adjacent cities. The chromosome with the lowest fitness score is the fittest as it represents the shortest path between the cities. I cAn't emphasize enough the importAnce of the cost function as it determInes which chromosomes are the fittest withIn a population. Without An appropriate defInition of the fitness evaluation, you might as well rummage around the solution search space at rAndom. ListIng 2 provides the source code In TSPChromosome.Java In which the fitness is calculated.

  Initial Population

  With the parameters And cost function defIned, it's time to set the Genetic algorithm In motion. RecallIng the Genetic algorithm workflow defIned last month, Individuals are selected from a population (combIned In a process called crossover) to create a set of children, And the children are rAndomly mutated to create a new set of chromosomes to be reInserted Into the population. Once enough children chromosomes have been created to replace a population, a generation is said to have passed. With each generation, all the chromosomes are evaluated accordIng to the cost function. Only the fittest survive Into the next generation where the selection, crossover, And mutate process begIns Anew. After a number of generations have elapsed, the best chromosome is selected from the population And represents the optimal solution to the problem beIng solved. Figure 3 depicts a flowchart of the algorithm.

  Upon examInation of the properties file, you'll notice two properties concernIng the population size. One is the Initial population size And the other is the "regular" population size. The way I've encoded the Genetic algorithm for the TSP is that An Initial population of 500 rAndom chromosomes is created And sorted, And the 100 fittest chromosomes are the ones selected for the Genetic algorithm startIng poInt.

  The advAntage of this approach is that by creatIng a large Initial population, you cAn cover a greater amount of the solution search space Initially And then pare down the population to the fittest to focus the search usIng relatively strong chromosomes. Otherwise, the computational power required to perform a Genetic algorithm on a population of 500 chromosomes is far greater thAn that required for 100 chromosomes.

  Selection

  ContInuIng with the Genetic algorithm workflow, it's now time to select parents for reproduction. The goal of selection is to choose parents that are capable of creatIng fitter children while maIntaInIng Genetic diversity. What this meAns is that we wAnt the Genetic algorithm to pick not only the fittest to reproduce, but also occasionally the less fit chromosomes to maIntaIn variation In the population. If a few relatively strong chromosomes are contInually selected for reproduction, it's likely that the algorithm will converge on these "super" chromosomes sInce it's their Genetic material that's most likely to pass on to the next generation. And it may be the case that the chromosomes represent a local mInimum In the cost function rather thAn the global mInimum we're searchIng for.

  The technique I've used In the selectParents() method of TSPPopulation.Java (see ListIng 3) is referred to as tournament selection. A small group of chromosomes is rAndomly selected, In this case six, And the two fittest are selected to reproduce. KeepIng the tournament size small results In a smaller selection pressure, thus IncreasIng Genetic diversity.

  Crossover

  Once parents have been selected, the crossover operator combInes the two parents rAndomly to create two children chromosomes. A crossover probability (In our example 90%) is used to determIne whether crossover will occur for two given parents. If crossover doesn't occur, the children will be exact replicas of the parents. Crossover is An essential operator for a Genetic algorithm as it is the mechAnism by which the algorithm "moves" through the solution search space toward convergence.

  ContInuIng with the TSP example, a typical crossover operation Includes selectIng a chunk of a chromosome And iteratIng through the other parent chromosome to extract the genes that weren't selected from the first parent In order to combIne them In a new child. As discussed earlier, the TSP is basically a permutation problem In which gene uniqueness must be maIntaIned. For other problems, such as permutation without the uniqueness constraInt or real-valued problems, crossover takes on a completely different appearAnce. But for now, we'll use the TSP crossover described above. ListIng 4 displays the crossover() method from TSPChromosome.Java, which illustrates In code the concepts described above.

  Mutation

  Mutation is similar to crossover, except that only a sIngle chromosome is Involved. As with crossover, there's a probability associated with mutations, albeit a low one (5% In our example). The mutate() method (see ListIng 5) defInes a very simple mutation method: two genes are selected at rAndom from the chromosome And swapped. A number of mutation techniques are available dependIng on the problem encodIng (permutation, real-valued, etc.), And I recommend further Investigation to understAnd them. ReturnIng to the comparision with crossover, mutation also ensures that a Genetic algorithm "moves" through the solution search space, although not always In the direction of IncreasIng fitness. Remember that these operators are blInd, that they're determIned by probability And chAnce. The cost function ensures that the population as a whole moves toward An optimal solution.

  Insertion

  Parents have been selected And children chromosomes created via crossover And An occasional mutation. What next? It's time to Insert the children Into the population And begIn the selection, crossover, And mutation process Anew. to preserve the strongest chromosomes withIn the population, a concept called elitism that protects the n (n = 10 In our TSP example) most elite chromosomes is Introduced And replaces the rest of the population with the newly created children.

  Convergence

  The goal of employIng a Genetic algorithm for the TSP is to converge on An optimal path (i.e., chromosome) through the cities In which the distAnce traveled is mInimized. The convergence criterion is thus the mInimum distAnce, but sInce we don't know it a priori, we cAn't use it to test that the algorithm has converged. Convergence is a key area of research In Genetic algorithms, And the approach commonly used today is to provide large populations And a high number of generations to give the algorithm the best chAnce of convergence. One of the reasons Genetic algorithms still exist primarily In academia is that, based on all the parameters that cAn be set for a Genetic algorithm And the different encodIngs it cAn assume, there isn't consensus on convergence criteria, meAnIng that it's largely a process of trial And error for the domaIn represented.

  Conclusion

  I've briefly examIned the key components of a Genetic algorithm And provided examples usIng the TravelIng SalesmAn Problem. Much of this affirms that use of a Genetic algorithm is by no meAns An exact science And is largely predicated on trial And error In determInIng An appropriate encodIng of the problem beIng optimized as well as the selection of the parameters controllIng the Genetic algorithm.

  My hope is that I have presented An

  InterestIng programmIng technique And

  sparked your Interest In wAntIng to know more about Genetic algorithms And the power they hold for optimizIng complex problems we encounter every day as software developers.

  In my opInion we're approachIng a poInt In software development where our jobs are becomIng more And more reactionary to the competitive lAndscape that the Internet provides. to shift back Into the proactive role, we need to develop software that relieves us of the burden of codIng for every possible scenario. We won't get there overnight, but we have to start somewhere, And the Genetic algorithm is a logical startIng poInt as it provides a framework for the evolution of digital applications to solve problems as they arise. I encourage you to dabble with the code provided with this article And thInk seriously about the future of software development. As Bob DylAn so eloquently stated back In 1964, "the times, they are a-chAngIn'."

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>