Advertisement
Guest User

Untitled

a guest
Dec 11th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.03 KB | None | 0 0
  1. #PSO
  2. import pyswarms as ps
  3. from pyswarms.single.global_best import GlobalBestPSO
  4. import matplotlib.pyplot as plt
  5. from pyswarms.utils.plotters import plot_cost_history
  6. from pyswarms.utils.plotters.formatters import Mesher, Designer
  7. import numpy as np
  8. import math
  9.  
  10.  
  11. def func(x):
  12.     y=(x[:,0]-6)**2+(x[:,1]-7)**2
  13.     g1=-3*x[:,0]-2*x[:,1]+6
  14.     g2 = -x[:,0] + x[:,1] -3
  15.     g3 = x[:,0]+ x[:,1] -7
  16.     g4 = 2/3*x[:,0]- x[:,1] - 4/3
  17.     c=9999
  18.     f=1*y[:]+c*np.maximum(g1[:],0)**2+c*np.maximum(g2[:],0)**2+c*np.maximum(g3[:],0)**2+c*(g4[:])**2
  19.     return f
  20.  
  21. options = {'c1': 0.5, 'c2': 0.3, 'w': 0.9}
  22.  
  23. x_max = 10 * np.ones(2)
  24. x_min = -1 * x_max
  25. bounds = (x_min, x_max)
  26.  
  27. optimizer = GlobalBestPSO(n_particles=100, dimensions=2, options=options,bounds=bounds)
  28.  
  29. cost, pos = optimizer.optimize(func, iters=200)
  30. print(cost,pos)
  31.  
  32. plot_cost_history(optimizer.cost_history)
  33. plt.show()
  34.  
  35. #GENETIC
  36. import math
  37. import numpy as np
  38. from genetic_algorithm.main import genetic_optimisation
  39. import matplotlib.pyplot as plt
  40. from mpl_toolkits.mplot3d import Axes3D
  41. import numpy as np
  42.  
  43. def func(x):
  44.  
  45.     y=(x[0]-6)**2+(x[1]-7)**2
  46.     g1=-3*x[0]-2*x[1]+6
  47.     g2 = -x[0] + x[1] -3
  48.     g3 = x[0] + x[1] -7
  49.     g4 = 2/3*x[0] - x[1] - 4/3
  50.     c=-1*9999
  51.     f=-1*y+c*max(g1,0)**2+c*max(g2,0)**2+c*max(g3,0)**2+c*(g4,0)**2
  52.     return f
  53.  
  54. def fitness(x):
  55.     x = list(x.values())
  56.     return func(x)
  57.  
  58. x1v = np.arange(-6, 6, 0.01)
  59. x2v = np.arange(-6, 6, 0.01)
  60. x1, x2 = np.meshgrid(x1v, x2v)
  61. f = np.zeros((len(x1),len(x2)))
  62.  
  63. for i in range(0,len(x1),1):
  64.     for j in range(0,len(x1),1):
  65.         f[i,j]=func((x1[i,j], x2[i,j]))
  66.  
  67. fig = plt.figure()
  68. ax = fig.gca(projection='3d')
  69. p1 = ax.plot_surface(x1, x2, f)
  70. plt.show()
  71.  
  72. param_space = {"x1": [-5, 5],"x2": [-5, 5]}
  73.  
  74. xopt=genetic_optimisation(input_model=fitness, param_space=param_space, pop_size=100, num_parents=2,
  75.                      max_num_generations=500, mutation_prob=0.5, stoping_rounds=50, integer_params=[])
  76.  
  77. print(xopt.get('best fitness'))
  78. print(xopt.get('best params'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement