Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #PSO
- import pyswarms as ps
- from pyswarms.single.global_best import GlobalBestPSO
- import matplotlib.pyplot as plt
- from pyswarms.utils.plotters import plot_cost_history
- from pyswarms.utils.plotters.formatters import Mesher, Designer
- import numpy as np
- import math
- def func(x):
- y=(x[:,0]-6)**2+(x[:,1]-7)**2
- g1=-3*x[:,0]-2*x[:,1]+6
- g2 = -x[:,0] + x[:,1] -3
- g3 = x[:,0]+ x[:,1] -7
- g4 = 2/3*x[:,0]- x[:,1] - 4/3
- c=9999
- f=1*y[:]+c*np.maximum(g1[:],0)**2+c*np.maximum(g2[:],0)**2+c*np.maximum(g3[:],0)**2+c*(g4[:])**2
- return f
- options = {'c1': 0.5, 'c2': 0.3, 'w': 0.9}
- x_max = 10 * np.ones(2)
- x_min = -1 * x_max
- bounds = (x_min, x_max)
- optimizer = GlobalBestPSO(n_particles=100, dimensions=2, options=options,bounds=bounds)
- cost, pos = optimizer.optimize(func, iters=200)
- print(cost,pos)
- plot_cost_history(optimizer.cost_history)
- plt.show()
- #GENETIC
- import math
- import numpy as np
- from genetic_algorithm.main import genetic_optimisation
- import matplotlib.pyplot as plt
- from mpl_toolkits.mplot3d import Axes3D
- import numpy as np
- def func(x):
- y=(x[0]-6)**2+(x[1]-7)**2
- g1=-3*x[0]-2*x[1]+6
- g2 = -x[0] + x[1] -3
- g3 = x[0] + x[1] -7
- g4 = 2/3*x[0] - x[1] - 4/3
- c=-1*9999
- f=-1*y+c*max(g1,0)**2+c*max(g2,0)**2+c*max(g3,0)**2+c*(g4,0)**2
- return f
- def fitness(x):
- x = list(x.values())
- return func(x)
- x1v = np.arange(-6, 6, 0.01)
- x2v = np.arange(-6, 6, 0.01)
- x1, x2 = np.meshgrid(x1v, x2v)
- f = np.zeros((len(x1),len(x2)))
- for i in range(0,len(x1),1):
- for j in range(0,len(x1),1):
- f[i,j]=func((x1[i,j], x2[i,j]))
- fig = plt.figure()
- ax = fig.gca(projection='3d')
- p1 = ax.plot_surface(x1, x2, f)
- plt.show()
- param_space = {"x1": [-5, 5],"x2": [-5, 5]}
- xopt=genetic_optimisation(input_model=fitness, param_space=param_space, pop_size=100, num_parents=2,
- max_num_generations=500, mutation_prob=0.5, stoping_rounds=50, integer_params=[])
- print(xopt.get('best fitness'))
- print(xopt.get('best params'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement