Main Content

이 번역 페이지는 최신 내용을 담고 있지 않습니다. 최신 내용을 영문으로 보려면 여기를 클릭하십시오.

유전 알고리즘 옵션의 영향

이 예제에서는 몇 가지 옵션이 유전 알고리즘 함수 ga에 미치는 영향을 보여줍니다. optimoptions 함수를 사용하여 옵션을 만들고 변경할 수 있습니다.

ga에 대한 문제 설정

ga는 유전 알고리즘을 사용하여 함수의 최솟값을 탐색합니다. 이 예제에서는 ga를 사용하여 두 변수의 실수 값 함수인 적합도 함수 shufcn을 최소화합니다.

plotobjective(이 예제를 실행할 때 포함되어 있음)를 호출하여 범위 = [-2 2;-2 2]에서 shufcn을 플로팅합니다.

plotobjective(@shufcn,[-2 2; -2 2]);

Figure contains an axes object. The axes object contains 2 objects of type surface, contour.

ga 솔버를 사용하려면 최소 두 개의 입력 인수를 제공합니다. 하나는 적합도 함수이고 다른 하나는 문제 내 변수의 개수입니다. ga가 반환하는 처음 2개의 출력 인수는 찾아낸 최적점 x와 이 최적점에서의 함수 값 Fval입니다. 3번째 출력 인수 exitFlagga가 중지된 이유를 나타냅니다. ga는 솔버의 성능 정보가 들어 있는 4번째 인수 Output도 반환할 수 있습니다.

FitnessFunction = @shufcn;
numberOfVariables = 2;

ga 솔버를 실행합니다.

rng default % For reproducibility
[x,Fval,exitFlag,Output] = ga(FitnessFunction,numberOfVariables);
ga stopped because the average change in the fitness value is less than options.FunctionTolerance.
fprintf('The number of generations is: %d\n', Output.generations);
The number of generations is: 124
fprintf('The number of function evaluations is: %d\n', Output.funccount);
The number of function evaluations is: 5881
fprintf('The best function value found is: %g\n', Fval);
The best function value found is: -186.199

ga는 확률적 알고리즘이기 때문에 rng default 명령 없이 이 예제를 실행하면 결과가 달라질 수 있습니다.

유전 알고리즘의 작동 방식

유전 알고리즘은 하나의 모집단을 가지고 이 모집단에 일련의 연산자를 적용하는 방식입니다. 모집단은 설계 공간 내 점들의 집합입니다. 초기 모집단은 기본적으로 무작위로 생성됩니다. 알고리즘은 현재 세대에 있는 개체들의 적합도를 사용하여 모집단의 다음 세대를 계산합니다. 자세한 내용은 How the Genetic Algorithm Works 항목을 참조하십시오.

시각화 추가하기

솔버가 실행 중일 때 솔버 성능을 시각화하려면 optimoptions를 사용하여 'PlotFcn' 옵션을 설정합니다. 이 경우에는 셀형 배열로 지정된 2개의 플롯 함수를 선택합니다. 각 세대에서 모집단의 최고 점수와 평균 점수를 플로팅하는 gaplotbestf를 설정합니다. 또한 충족된 중지 기준 비율을 플로팅하는 gaplotstopping도 설정합니다.

opts = optimoptions(@ga,'PlotFcn',{@gaplotbestf,@gaplotstopping});

opts 인수를 포함하여 ga 솔버를 실행합니다.

[x,Fval,exitFlag,Output] = ...
    ga(FitnessFunction,numberOfVariables,[],[],[],[],[],[],[],opts);
ga stopped because the average change in the fitness value is less than options.FunctionTolerance.

Figure Genetic Algorithm contains 2 axes objects. Axes object 1 with title Best: -186.71 Mean: -123.753, xlabel Generation, ylabel Fitness value contains 2 objects of type scatter. These objects represent Best fitness, Mean fitness. Axes object 2 with title Stopping Criteria, xlabel Progress contains an object of type bar.

모집단 옵션 지정하기

모집단 옵션은 솔버 성능에 커다란 영향을 미칠 수 있습니다. 각 반복의 속도는 모집단 크기에 따라 달라집니다. 모집단이 클수록 반복 속도는 느려집니다. 반대로 모집단이 크면 ga가 더 꼼꼼하게 탐색하므로 더 나은 해를 구할 수 있습니다. 마찬가지로, 초기 범위가 넓을수록 더 꼼꼼한 탐색이 가능하지만 더 넓은 범위를 비슷한 수준으로 꼼꼼하게 탐색하려면 더 큰 모집단이 필요할 수 있습니다.

모집단 크기 지정하기

ga는 균일 난수 생성기를 사용하여 디폴트 초기 모집단을 생성합니다. ga가 사용하는 디폴트 모집단 크기는 결정 변수의 개수가 5 미만이면 50이고, 그 이상이면 200입니다. 이 디폴트 크기는 일부 문제에서는 잘 맞지 않을 수 있습니다. 예를 들어, 더 작은 문제라면 모집단 크기가 더 작아도 충분할 수 있습니다. 현재 문제에는 변수가 2개뿐이므로 모집단 크기를 10으로 지정합니다. 기존 옵션 opts에서 옵션 PopulationSize의 값을 10으로 설정합니다.

opts.PopulationSize = 10;

초기 모집단 범위 지정하기

초기 모집단을 생성하는 기본 방법은 균일 난수 생성기를 사용합니다. 정수 제약 조건이 없는 문제의 경우 ga는 모든 점이 -10에서 10 사이의 범위에 있는 초기 모집단을 생성합니다. 예를 들어, 다음 명령을 사용하여 크기가 3인 모집단을 디폴트 범위에서 생성할 수 있습니다.

Population = [-10,-10] + 20*rand(3,2);

InitialPopulationRange 옵션을 변경하여 초기 범위를 설정할 수 있습니다. 범위는 2개 행을 가진 행렬이어야 합니다. 범위에 열이 하나만 있는 경우, 즉 2×1이면 모든 변수의 범위는 이 주어진 범위가 됩니다. 예를 들어, 범위를 [-1; 1]로 설정하면 이 두 변수의 초기 범위는 -1에서 1입니다. 각 변수마다 다른 초기 범위를 지정하려면 2개의 행을 가진 행렬로 범위를 지정하고 numberOfVariables 열을 지정해야 합니다. 예를 들어 범위를 [-1 0; 1 2]로 설정하면 첫 번째 변수의 범위는 -1에서 1이고, 두 번째 변수의 범위는 0에서 2입니다(각 열이 하나의 변수에 대응).

기존 옵션 opts에서 옵션 InitialPopulationRange의 값을 수정합니다.

opts.InitialPopulationRange = [-1 0; 1 2];

ga 솔버를 실행합니다.

[x,Fval,exitFlag,Output] = ga(FitnessFunction,numberOfVariables,[],[],[], ...
    [],[],[],[],opts);
ga stopped because the average change in the fitness value is less than options.FunctionTolerance.

Figure Genetic Algorithm contains 2 axes objects. Axes object 1 with title Best: -179.987 Mean: -78.6061, xlabel Generation, ylabel Fitness value contains 2 objects of type scatter. These objects represent Best fitness, Mean fitness. Axes object 2 with title Stopping Criteria, xlabel Progress contains an object of type bar.

fprintf('The number of generations is: %d\n', Output.generations);
The number of generations is: 67
fprintf('The number of function evaluations is: %d\n', Output.funccount);
The number of function evaluations is: 614
fprintf('The best function value found is: %g\n', Fval);
The best function value found is: -179.987

결과 재현하기

기본적으로 ga는 MATLAB® 난수 생성기를 사용하여 생성되는 무작위 초기 모집단으로 시작합니다. 솔버는 ga 연산자를 사용하여 다음 세대를 만드는데 이때도 동일한 난수 생성기를 사용합니다. 난수가 생성될 때마다 난수 생성기의 상태가 바뀝니다. 따라서 아무런 옵션을 변경하지 않았더라도 솔버를 다시 실행하면 다른 결과가 나올 수 있습니다.

이 현상을 확인하기 위해 솔버를 두 번 실행합니다.

ga 솔버를 실행합니다.

[x,Fval,exitFlag,Output] = ga(FitnessFunction,numberOfVariables);
ga stopped because the average change in the fitness value is less than options.FunctionTolerance.
fprintf('The best function value found is: %g\n', Fval);
The best function value found is: -186.484

ga를 다시 실행합니다.

[x,Fval,exitFlag,Output] = ga(FitnessFunction,numberOfVariables);
ga stopped because the average change in the fitness value is less than options.FunctionTolerance.
fprintf('The best function value found is: %g\n', Fval);
The best function value found is: -185.867

난수 생성기의 상태가 매 실행마다 바뀌기 때문에 ga는 이 두 번의 실행에서 서로 다른 결과를 제공합니다.

이전 결과를 재현하고 싶다면 ga를 실행하기 전에 난수 스트림의 상태를 저장할 수 있습니다.

thestate = rng;

ga를 실행합니다.

[x,Fval,exitFlag,Output] = ga(FitnessFunction,numberOfVariables);
ga stopped because the average change in the fitness value is less than options.FunctionTolerance.
fprintf('The best function value found is: %g\n', Fval);
The best function value found is: -186.467

스트림을 재설정하고 ga를 다시 실행합니다. 이전 실행과 결과가 동일합니다.

rng(thestate);
[x,Fval,exitFlag,Output] = ga(FitnessFunction,numberOfVariables);
ga stopped because the average change in the fitness value is less than options.FunctionTolerance.
fprintf('The best function value found is: %g\n', Fval);
The best function value found is: -186.467

결과를 재현하도록 지정하지 않고 ga를 실행하는 경우에는 output 구조체를 가지고 있다면 난수 생성기를 재설정할 수 있습니다.

strm = RandStream.getGlobalStream;
strm.State = Output.rngstate.State;

ga를 다시 실행합니다. 이번에도 결과가 동일합니다.

[x,Fval,exitFlag,Output] = ga(FitnessFunction,numberOfVariables);
ga stopped because the average change in the fitness value is less than options.FunctionTolerance.
fprintf('The best function value found is: %g\n', Fval);
The best function value found is: -186.467

중지 기준 수정하기

ga는 4가지 기준을 사용하여 솔버를 중지하는 시점을 결정합니다. ga는 최대 세대 수에 도달하면 중지됩니다. 기본적으로 이 숫자는 변수 개수에 100을 곱한 것입니다. 또한 ga는 초 단위로 지정된 시간(정체 시간 제한) 또는 특정 세대 수(최대 정체 세대 수) 동안 최적 적합도 값이 변화하지 않는 경우를 감지합니다. 또 다른 기준은 최대 시간 제한(단위: 초)입니다. 중지 조건을 수정하여 최대 세대 수를 300으로, 최대 정체 세대 수를 100으로 늘립니다.

opts = optimoptions(opts,'MaxGenerations',300,'MaxStallGenerations', 100);

ga 솔버를 다시 실행합니다.

[x,Fval,exitFlag,Output] = ga(FitnessFunction,numberOfVariables,[],[],[], ...
    [],[],[],[],opts);
ga stopped because the average change in the fitness value is less than options.FunctionTolerance.

Figure Genetic Algorithm contains 2 axes objects. Axes object 1 with title Best: -186.729 Mean: -186.202, xlabel Generation, ylabel Fitness value contains 2 objects of type scatter. These objects represent Best fitness, Mean fitness. Axes object 2 with title Stopping Criteria, xlabel Progress contains an object of type bar.

fprintf('The number of generations is: %d\n', Output.generations);
The number of generations is: 299
fprintf('The number of function evaluations is: %d\n', Output.funccount);
The number of function evaluations is: 2702
fprintf('The best function value found is: %g\n', Fval);
The best function value found is: -186.729

ga 연산자 지정하기

ga는 모집단 내의 무작위 점 집합으로 시작하고 연산자를 사용하여 모집단의 다음 세대를 만듭니다. 각 연산자는 스케일링, 선택, 교차, 변이입니다. 툴박스는 각 연산자에 대해 지정할 수 있는 여러 함수를 제공합니다. FitnessScalingFcn에는 fitscalingprop를 지정하고 SelectionFcn에는 selectiontournament를 지정합니다.

opts = optimoptions(@ga,'SelectionFcn',@selectiontournament, ...
                        'FitnessScalingFcn',@fitscalingprop);

ga를 다시 실행합니다.

[x,Fval,exitFlag,Output] = ga(FitnessFunction,numberOfVariables,[],[],[], ...
    [],[],[],[],opts);
ga stopped because the average change in the fitness value is less than options.FunctionTolerance.
fprintf('The number of generations is: %d\n', Output.generations);
The number of generations is: 52
fprintf('The number of function evaluations is: %d\n', Output.funccount);
The number of function evaluations is: 2497
fprintf('The best function value found is: %g\n', Fval);
The best function value found is: -186.417

최적 함수 값은 지정된 연산자에 따라 개선될 수도 있고 나빠질 수도 있습니다. 문제에 가장 적합한 연산자의 조합이 무엇인지 결정하려면 여러 연산자들로 실험해 보는 것이 최선의 방법입니다.

참고 항목

관련 항목