| | clear; |
| | clc; |
| | p = 0 : 0.01: 2; % sample input |
| | t = sin(pi ∗ p); % sample output |
| | n = 3; % the number of neurons in the hidden layer |
| | net = newff(p,t, n, {'tansig','purelin'}, 'trainlm'); swarmCount = 20; % particle count. |
| | swarmLength = 10; % particle length |
| | vMax = 20; % maximum speed of particle movement |
| | pMax = 2; % maximum position of particle motion |
| | swarm = rand (swarmCount, swarmLength); % initial particle swarm, that is, the position of the particle |
| | = rand (swarmCount, swarmLength); % particle speed. |
| | swarmfitness = zeros (swarmCount, 1, 'double'); % particle fitness value. |
| | pBest = rand (swarmCount, swarmLength); % individual optimal value. |
| | pBestfitness = zeros (swarmCount, 1, 'double'); % individual optimal fitness valuepBestfitness(:,) = 100; |
| | gBest = rand (1, swarmLength); % global optimum. |
| | gBestfitness = 100; % global optimal fitness value |
| | c1 = 2; |
| | c2 = 2; |
| | wmax = 0.95; |
| | wmin = 0.25; |
| | maxEpoch = 2000; % maximum training times |
| | errGoal = 0.01; % expected error minimum |
| | epoch = 1; |
| | while (epoch < maxEpoch && gBestfitness > errGoal) |
| | for i = 1: swarmCount |
| | % calculating the fitness value of the particle |
| | net.iw{1, 1} = swarm(i, 1 : 3)'; |
| | net.b{1} = swarm(i, 4 : 6)'; |
| | net.lw{2,1} = swarm(i, 7 : 9); |
| | net.b{2} = swarm(i, 10 : 10); |
| | tout = sim(net, p); % output of prediction. |
| | sse = sum((tout - t).^ (2)/length(t); |
| | swarmfitness(i, 1) = sse; |
| | % updating the individual optimal value |
| | if (pBestfitness(i, 1) > sse) |
| | pBestfitness(i, 1) = sse; |
| | pBest(i,) = swarm(i,); |
| | % updating the global optimum |
| | if(gBestfitness > sse) |
| | gBestfitness = sse; |
| | gBest(1,) = swarm(i,); |
| | end |
| | end |
| | end |
| | % updating particle velocity and position |
| | W(epoch) = wmax-((wmax-wmin)/maxEpoch)∗epoch; |
| | for i = 1: swarmCount |
| | (i,) = W(1)∗v(i,) + c1 ∗ rand(1, 1) ∗ (pBest(i,) - swarm(i,)) + c2 ∗ rand(1, 1) ∗ (gBest(1,) - swarm(i,)); % velocity update |
| | tmp = (i,) > vMax; |
| | (i, tmp) = vMax; % particles that exceed the bounds are converted to bounds |
| | swarm(i,) = swarm(i,) + (i,); % particle position update |
| | tmp = find(swarm(i,) > pMax); % particles that exceed the bounds are converted to bounds |
| | swarm(i, tmp) = pMax; |
| | end |
| | epoch = epoch + 1; |
| | end |
| | net.iw{1, 1} = gBest(1, 1 : 3)'; |
| | net.b{1} = gBest(1, 4 : 6)'; |
| | net.lw{2, 1} = gBest(1, 7 : 9); |
| | net.b{2} = gBest(1, 10 : 10); |
| | tout = sim(net, p); |
| | figure(1) |
| | plot(p, t, 'k-'); |
| | hold on; |
| | plot(p, tout, 'b-'); |