現在この質問をフォロー中です
- フォローしているコンテンツ フィードに更新が表示されます。
- コミュニケーション基本設定に応じて電子メールを受け取ることができます。
How to invoke and use GA tool in Matlab R2022b?
23 ビュー (過去 30 日間)
古いコメントを表示
I typed optimtool in Matlab R2022b to invoke the GA Tool but its' not there. Can anybody guide me how to invoke and use GA tool in Matlab R 2022b because I usually tune the setting for the best results but since its not here, so what to do and how to do?
Regards,
4 件のコメント
Star Strider
2022 年 12 月 14 日
The previous version is gone.
If you click on it, it directs you to a Live Editor optimisation task, and opens the task.
If you want to use ga it will likely be necessary to code it specifically. That’s what I usually do anyway.
Sadiq Akbar
2022 年 12 月 14 日
Thanks a lot for your kind response dear Star Strider. But I am not so much expert to code it by my own. Can you demonstrate it by getting my desired solution. My functions are as below:
clear all
clc
global u
global Noise
u=[-35, 35, -5, 5, -25, 25, 45, -45];% My desired vector
nvars=length(u);% No. of varibles
lb=-90*ones(1,nvars);%Lower bound
ub=90*ones(1,nvars);%Upper bound
Population=250;
iterations=500;
Noise=20;
nn=0;
for n=1:10
nn=nn+1;
% Invoke GA to get executed and returns us best solution x, fitness value fval and execution time i.e.,
[x,fval,time] = ga(???????);
one(nn)=fval;
temp(nn,:)=x;
time1(nn)=time;
[~, ix] = sort(u);
[~, ix1(ix)] = sort(temp(nn,:));
two(nn,:) = temp(nn,ix1);
end
%%%%%%%%%%%%%%%%%%%%%
% GA code here
%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%
% My function called by GA for fitness
%%%%%%%%%%%%%%%%%%%%%
function e=myfun(b)
global u
global Noise
M=6; %Constant1
N=6; %Constant2
K=length(u);%Constant3
d = 0.5; %Constant4
vec = @(MAT) MAT(:);
vecH = @(MAT) MAT(:).';
steerVecT = @(ang) exp(1j*2*pi*d*(0:M-1).'*sin(vecH(ang)));
steerVecR = @(ang) exp(1j*2*pi*d*(0:N-1).'*sin(vecH(ang)));
%%%%%%%%%%%%%%%%%%%%
% Swapping vector b
%%%%%%%%%%%%%%%%%%%%
[~, ix] = sort(u);
[~, ix1(ix)] = sort(b);
b = b(ix1);
A = ones(K, 1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Calculation of yo and ye
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
yo = yMatTR(deg2rad(u), steerVecT, steerVecR);
yo=awgn(yo,Noise);
ye = yMatTR(deg2rad(b), steerVecT, steerVecR);
%%%%%%%%%%%%%%%%%%
% MSE
%%%%%%%%%%%%%%%%%%
e=norm(yo-ye).^2/(M*N);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% User defined function called within myfun
%%%%%%%%%%%%%%%%%%%%%%%%5%%%
function y = yMatTR(targetAngle, steerVecT, steerVecR)
steerA = steerVecT(targetAngle);
steerB = steerVecR(targetAngle);
y=sum( steerA.*permute(steerB,[3,2,1]) ,2);
y=y(:);
%%%%%%%%%%%%% End of my code %%%%%%%%%%%%%%%%%%%%%
I want to run it and the GA returns me the three values i.e., the best solution, fitness and time. But the best solution should be equal to or nealry equal to my desired vector u.
Star Strider
2022 年 12 月 14 日
First, there is no reason to put the ga call in a loop unless you are varying specific parameters between calls to it.
Second, I have no idea what the fitness function is or the problem you are optimising.
Third, it is never advisable to use global variables. See the documentation on Passing Extra Parameters to understand how to do that correctly.
Sadiq Akbar
2022 年 12 月 14 日
Reason to put ga in loop: Because I want to get 10 independent run values for the same parameters.
The fitness function is a user defined function defined for the problem. My problem is to find the desired solution x whose value matches the value of my desired vector u or nearly matches it.
Use of global variables: If I don't use global variables, then how will it be visible to my fitness function?
採用された回答
Star Strider
2022 年 12 月 14 日
If you are doing parameter estimation, this approach will likely work —
x = 1:0.1:10;
y = 2.5*exp(-(x-5).^2/2)+randn(size(x))*0.25;
objfcn = @(b,x) b(1).*exp(-(x-b(2)).^2*b(3));
fitnessfcn = @(b) norm(y-objfcn(b,x));
Parms = 3;
opts = optimoptions('ga', 'MaxGenerations',1000);
[B,fval,exitflag,output] = ga(fitnessfcn, Parms,[],[],[],[],[],[],[],opts);
Optimization terminated: average change in the fitness value less than options.FunctionTolerance.
Parameters = B
Parameters = 1×3
2.5311 4.8704 0.5030
BestFitness = fval
BestFitness = 2.2760
Generations = output.generations
Generations = 129
figure
plot(x, y, '.', 'DisplayName','Data')
hold on
plot(x, objfcn(B,x), '-r', 'DisplayName','Function Fit')
hold off
grid
legend('Location','best')
This uses ga to estimate the parameters of the function fitting the data.
With respect to eliminating global variables, see the ‘Passing Extra Parameters’ documentation I already linked to.
.
17 件のコメント
Sadiq Akbar
2022 年 12 月 15 日
編集済み: Sadiq Akbar
2022 年 12 月 15 日
Thank you very much dear Star Strider for your kind response. Yes you may be write. You can say its a type of parameter estimation. But what is this reproduced below?
x = 1:0.1:10;
y = 2.5*exp(-(x-5).^2/2)+randn(size(x))*0.25;
objfcn = @(b,x) b(1).*exp(-(x-b(2)).^2*b(3));
fitnessfcn = @(b) norm(y-objfcn(b,x));
As far as I understand your code, you have a desired vector [2.5 5 0.25] like mine u but yours has 3 values and my u has got 4 values. Your function is y=2.5*exp(-(x-5).^2/2) and then you are adding noise to it. But mine has two or three functions as can be seen from "myfun.m". b is the random vector coming one by one from the random population generated by ga The same is the case with mine. But I don't understand the 3rd and 4th lines in your code. Can you explain them please?
Now coming to my problem. I want that when ga runs and stops after completion, it should return me an estimated vector "two" which must be equal to my desired vector u or if not equal, then nearly equal to u. So how will we do that then? Can you do that for me by removing global variables because I am not too much expert in Matlab by using my above function "myfun.m"?
Star Strider
2022 年 12 月 15 日
My pleasure.
The code I posted is simply an example of how to estimate parameters using ga. It can easily be generalised to other problems, with other data and other fitness functions. The lines you quoted from it create a data set and then the necessary objective function and fitness function to present to ga for optimisation.
I have no idea what you want to do or what your fitness function is. My objective here is to provide an example of parameter estimation using ga, since I assume that is what you want to do, nothing else.
You need to create your fitness function to do what you want it to do. I have no idea what that is.
Again, with respect to global variables, refer to the documentation section I linked to in my earlier Comment.
Star Strider
2022 年 12 月 17 日
My pleasure.
The ‘myfun’ function does not appear to exist anywhere in the posted code. At least I don’t see it.
Also, what exactly is ‘Line 9’? Considering that ‘myfun’ is missing, I have no idea what ‘Line 9’ refers to. Is it part of ‘myfun’ or something else?
Star Strider
2022 年 12 月 18 日
Yu will have to provide whatever ‘b’ is suppolsed to be, and be certain it is in your calling function workspace.
The ‘myfun’ function is still not described where I can see it, so I cannot help you with it.
Sadiq Akbar
2022 年 12 月 18 日
Thank you very much dear Star Strider for your kind responses and sorry for being late. Line 11 is:
[B,fval,exitflag,output] = ga(@myfun(b,u,Noise), Parms,[],[],[],[],[],[],[],opts);
Star Strider
2022 年 12 月 18 日
My pleasure!
I am not certain what parameter you are optimising. In that event, it needs to be the input to the fitness function:
[B,fval,exitflag,output] = ga(@(b)myfun(b,u,Noise), Parms,[],[],[],[],[],[],[],opts)
This selects ‘b’ as the argument to be optimised that ga passes to ‘myfun’.
With that change, this runs without error —
clear all
clc
u=[-35 35 50];
dim=length(u);
lb=-90*ones(1,dim);
ub=90*ones(1,dim);
Noise=35;
Parms = 3;
opts = optimoptions('ga', 'MaxGenerations',1000);
[B,fval,exitflag,output] = ga(@(b)myfun(b,u,Noise), Parms,[],[],[],[],[],[],[],opts)
Optimization terminated: average change in the fitness value less than options.FunctionTolerance.
B = 1×3
-35.0195 50.0848 35.0961
fval = 8.4405e-04
exitflag = 1
output = struct with fields:
problemtype: 'unconstrained'
rngstate: [1×1 struct]
generations: 200
funccount: 10050
message: 'Optimization terminated: average change in the fitness value less than options.FunctionTolerance.'
maxconstraint: []
hybridflag: []
function e=myfun(b,u,Noise)
M=6; %Constant1
N=6; %Constant2
K=length(u);%Constant3
d = 0.5; %Constant4
vec = @(MAT) MAT(:);
vecH = @(MAT) MAT(:).';
steerVecT = @(ang) exp(1j*2*pi*d*(0:M-1).'*sin(vecH(ang)));
steerVecR = @(ang) exp(1j*2*pi*d*(0:N-1).'*sin(vecH(ang)));
%%%%%%%%%%%%%%%%%%%%
% Swapping vector b
%%%%%%%%%%%%%%%%%%%%
[~, ix] = sort(u);
[~, ix1(ix)] = sort(b);
b = b(ix1);
A = ones(K, 1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Calculation of yo and ye
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
yo = yMatTR(deg2rad(u), steerVecT, steerVecR);
yo=awgn(yo,Noise);
ye = yMatTR(deg2rad(b), steerVecT, steerVecR);
%%%%%%%%%%%%%%%%%%
% MSE
%%%%%%%%%%%%%%%%%%
e=norm(yo-ye).^2/(M*N);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% User defined function called within myfun
%%%%%%%%%%%%%%%%%%%%%%%%5%%%
function y = yMatTR(targetAngle, steerVecT, steerVecR)
steerA = steerVecT(targetAngle);
steerB = steerVecR(targetAngle);
y=sum( steerA.*permute(steerB,[3,2,1]) ,2);
y=y(:);
end
If you want ‘lb’ aand ‘ub’ to be parameter constraints (although it does not appear to make much difference here, since the results are well within those ranges), put them in the appropriate places in the argument list.
I still do not understand what you are doing, since the estimated parameters in a curve-fitting optimisation make the objective function values approximate the supplied data when the original fitting function is evaluated with those parameters, similar to the code I originally posted as an example. Here, the results appear to be the actual function fit, rather than the parameters (whatever they are) that provide that fit.
If it does what you want, it is not necessary that I understand it or how it actually works.
.
Sadiq Akbar
2022 年 12 月 19 日
Thank you very much dear Star Strider for your help. Yes now it works. But each time I run it, the message "Optimization terminated: average change in the fitness value less than options.FunctionTolerance." is displayed. How can I suppress this message? Also, I want to pass two things more to 'ga' as input argumenmts and those are my bounds and population size i.e., I want to pass the following as input arguments to 'ga':
lb=-90*ones(1,dim);
ub=90*ones(1,dim);
pop=50;
Further, I want that 'ga' should return me the execution time. Besides this, what is the purpose of " exitflag and output ?" I don't understand this.
Star Strider
2022 年 12 月 19 日
My pleasure.
See the options section of the ga documentation for suppressing the output messages and providing the population size as an input. All that is possible using an optimoptions options structure.
With regard to the parameter bounds, see lb and ub in the documentation. They are input arguments to ga and so are part of the argument list.
The ga function itself will not return the execution time. With respect to the time, I have this as part of a standard ga call I use:
t0 = clock;
fprintf('\nStart Time: %4d-%02d-%02d %02d:%02d:%07.4f\n', t0)
[theta,fval,exitflag,output,population,scores] = ga(ftns, Parms, [],[],[],[],lb,ub,[],[],opts);
t1 = clock;
fprintf('\nStop Time: %4d-%02d-%02d %02d:%02d:%07.4f\n', t1)
GA_Time = etime(t1,t0)
DT_GA_Time = datetime([0 0 0 0 0 GA_Time], 'Format','HH:mm:ss.SSS');
fprintf('\nElapsed Time: %23.15E\t\t%s\n\n', GA_Time, DT_GA_Time)
Using tic and toc instead of the clock and etime calls are another option. Using datetime as I use it here makes it easier to parse the elapsed time in seconds and fractional seconds into hours, minutes, and seconds, since some of my ga optimisations run for several hours.
The ‘exitflag’ and ‘output’ and other outputs are for my benefit, since they contain information about the optimisation (such as the number of generations) that I believe are important. If you do not need the information they provide, then eliminate them from the output list. Returning their information is not required. The only output information that is required is the first output, since it contains the parameters that have been optimised. The second output is the optimal fitness value, usually considered to be important.
.
Star Strider
2022 年 12 月 19 日
My pleasure!
You have not told ga anything about the constraints:
[B,fval] = ga(@(b)myfun(b,u,Noise), dim,[],[],[],[],[],[],[],options)
Do this instead:
[B,fval] = ga(@(b)myfun(b,u,Noise), dim,[],[],[],[],lb,ub,[],[],options)
That should work.
.
Star Strider
2022 年 12 月 19 日
The loop addressing appeasrs to be the problem.
Try this —
% clear all
% clc
u=[-35 35 50];
dim=length(u);
lb=-90*ones(1,dim);
ub=90*ones(1,dim);
% Noise=35;
% PopulationSize_Data=200;
PopulationSize_Data = 20;
MaxGenerations_Data=1000;
FunctionTolerance_Data=1e-6;
ConstraintTolerance_Data=1e-6;
options = optimoptions('ga','PopulationSize', PopulationSize_Data);
options = optimoptions('ga','MaxGenerations', MaxGenerations_Data);
options = optimoptions('ga','FunctionTolerance', FunctionTolerance_Data);
options = optimoptions('ga','ConstraintTolerance', ConstraintTolerance_Data);
options = optimoptions('ga','CreationFcn', @gacreationuniform);
options = optimoptions('ga','CrossoverFcn', { @crossoverheuristic [] });
options = optimoptions('ga','MutationFcn', @mutationadaptfeasible);
options = optimoptions('ga','Display', 'off');
Noise=10:12;
% for mm=1:numel(Noise)
% [B,fval] = ga(@(b)myfun(b,u,Noise(mm)), dim,[],[],[],[],lb,ub,[],options)
% one(mm)=fval;
% two(mm,:)=B;
% end
NrCallsToGA = 5; % Number Of Times To Run The Inner Loop
for mm=1:numel(Noise)
for nn = 1:NrCallsToGA
[B,fval] = ga(@(b)myfun(b,u,Noise(mm)), dim,[],[],[],[],lb,ub,[],options);
onev(nn,:) = fval;
twov(nn,:) = B;
end
[~,idx] = min(onev); % Choose Lowest 'fval' For Each Run
one(mm,:)=onev(idx); % Save That 'fval' Value
two(mm,:)=twov(idx,:); % Save That 'B' Value
end
one
one = 3×1
0.0620
0.0513
0.0436
two
two = 3×3
49.8298 34.9975 -34.8970
-34.8288 50.1081 34.9002
-34.8867 50.1524 35.0214
function e=myfun(b,u,Noise)
M=6; %Constant1
N=6; %Constant2
K=length(u);%Constant3
d = 0.5; %Constant4
vec = @(MAT) MAT(:);
vecH = @(MAT) MAT(:).';
steerVecT = @(ang) exp(1j*2*pi*d*(0:M-1).'*sin(vecH(ang)));
steerVecR = @(ang) exp(1j*2*pi*d*(0:N-1).'*sin(vecH(ang)));
%%%%%%%%%%%%%%%%%%%%
% Swapping vector b
%%%%%%%%%%%%%%%%%%%%
[~, ix] = sort(u);
[~, ix1(ix)] = sort(b);
b = b(ix1);
A = ones(K, 1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Calculation of yo and ye
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
yo = yMatTR(deg2rad(u), steerVecT, steerVecR);
yo=awgn(yo,Noise);
ye = yMatTR(deg2rad(b), steerVecT, steerVecR);
%%%%%%%%%%%%%%%%%%
% MSE
%%%%%%%%%%%%%%%%%%
e=norm(yo-ye).^2/(M*N);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% User defined function called within myfun
%%%%%%%%%%%%%%%%%%%%%%%%5%%%
function y = yMatTR(targetAngle, steerVecT, steerVecR)
steerA = steerVecT(targetAngle);
steerB = steerVecR(targetAngle);
y=sum( steerA.*permute(steerB,[3,2,1]) ,2);
y=y(:);
end
This corrected version runs without error.
I do not understand what you were doing originally. If the nested loops were supposed to do something specific, that was not obvious, so I initially replaced them with a single loop and one loop counter, that being ‘mm’.
I assume that you want to run ga several times with a specific value of ‘Noise’. If so, something like this may be more appropriate:
Noise=10:12;
NrCallsToGA = 5; % Number Of Times To Run The Inner Loop
for mm=1:numel(Noise)
for nn = 1:NrCallsToGA
[B,fval] = ga(@(b)myfun(b,u,Noise(mm)), dim,[],[],[],[],lb,ub,[],options);
onev(nn,:) = fval;
twov(nn,:) = B;
end
[~,idx] = min(onev); % Choose Lowest 'fval' For Each Run
one(mm,:)=onev(idx); % Save That 'fval' Value
two(mm,:)=twov(idx,:); % Save That 'B' Value
end
I ran this to test it, and it works as I intend it to work. (I checked the interim results to be sure, however I did not include that additional code here.) Change ‘NrCallsToGA’ value to be whatever works best (and that you have time for).
I reduced the population size so it would run in the 55 seconds allowed here.
.
Sadiq Akbar
2022 年 12 月 19 日
Thanks a lot for your so much help and continuous kind support dear Star Strider. Actually I want to vary the value of Noise and for each value of Noise, I run 'ga' several times, say for example 50 times but I get its best value of B as well as of fval for that particular value of Noise i.e., Suppose Noise=10, now I want to run 'ga' several times i.e., 50 times and it gives me the best value of B and fval for this Noise value. Then if I change Noise value to 11 and run again the 'ga' 50 times and it gives me its best values of B and fval for that Noise value. Likewise if I change Noise value to 12 and again run 'ga' and it gives me its best values of B and fval. But i don't know how to do as I am not so much expert in Matlab.
Star Strider
2022 年 12 月 19 日
My pleasure.
Set the ‘Noise’ vector to be whatever you want.
To run the ga loop 50 times for each value of ‘Noise’, change ‘NrCallsToGA’ to 50.
The code I wrote will return the values of ‘one’ and ‘two’ for the lowest ‘fval’ value for each ‘Noise’ value for all ‘NrCallsToGA’ values that use it. No other changes to my code are necessary.
Sadiq Akbar
2022 年 12 月 19 日
Thanks a lot dear Star Strider for your continuous help and support. Indeed you have done very well. May you live long.
Star Strider
2022 年 12 月 19 日
As always, my pleasure!
Thank you! I very much appreciate your compliment. I wish you only the best in your life and career!
その他の回答 (0 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!エラーが発生しました
ページに変更が加えられたため、アクションを完了できません。ページを再度読み込み、更新された状態を確認してください。
Web サイトの選択
Web サイトを選択すると、翻訳されたコンテンツにアクセスし、地域のイベントやサービスを確認できます。現在の位置情報に基づき、次のサイトの選択を推奨します:
また、以下のリストから Web サイトを選択することもできます。
最適なサイトパフォーマンスの取得方法
中国のサイト (中国語または英語) を選択することで、最適なサイトパフォーマンスが得られます。その他の国の MathWorks のサイトは、お客様の地域からのアクセスが最適化されていません。
南北アメリカ
- América Latina (Español)
- Canada (English)
- United States (English)
ヨーロッパ
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
アジア太平洋地域
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)