1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| import random from abc import abstractmethod from typing import List
import numpy as np
class PSO:
def __init__(self, epochs, pop_size, var_num, bound: List[List]): self.epochs = epochs self.pop_size = pop_size self.var_num = var_num self.bound = bound
self.pop_x = np.zeros((self.pop_size, self.var_num)) self.pop_v = np.zeros((self.pop_size, self.var_num))
self.p_best = np.zeros((self.pop_size, self.var_num)) self.g_best = np.zeros((1, var_num))
tmp = float("-inf") for i in range(self.pop_size): for j in range(self.var_num): self.pop_x[i][j] = random.uniform(self.bound[0][j], self.bound[1][j]) self.pop_v[i][j] = random.uniform(0, 1) self.p_best[i] = self.pop_x[i] fit = self.evaluate(self.p_best[i]) if fit > tmp: self.g_best = self.p_best[i] temp = fit
@abstractmethod def evaluate(self, vals): return vals
def _update_func(self, w, c1, c2, xi, vi, pi, pg): return w * vi + \ c1 * random.uniform(0, 1) * (pi - xi) + \ c2 * random.uniform(0, 1) * (pg - xi)
def update(self): c1 = 2 c2 = 2 w = 0.4 for i in range(self.pop_size): self.pop_v[i] = self._update_func(w, c1, c2, self.pop_x[i], self.pop_v[i], self.p_best[i], self.g_best) self.pop_x[i] = self.pop_x[i] + self.pop_v[i] for j in range(self.var_num): if self.pop_x[i][j] < self.bound[0][j]: self.pop_x[i][j] = self.bound[0][j] if self.pop_x[i][j] > self.bound[1][j]: self.pop_x[i][j] = self.bound[1][j] if self.evaluate(self.pop_x[i]) > self.evaluate(self.p_best[i]): self.p_best[i] = self.pop_x[i] if self.evaluate(self.pop_x[i]) > self.evaluate(self.g_best): self.g_best = self.pop_x[i]
def run(self): hist = [] self.ng_best = np.zeros((1, self.var_num))[0] for gen in range(self.epochs): self.update() print('############ Generation {} ############'.format(str(gen + 1))) if self.evaluate(self.g_best) > self.evaluate(self.ng_best): self.ng_best = self.g_best.copy() print('最好的位置:{}'.format(self.ng_best)) print('最大的函数值:{}'.format(self.evaluate(self.ng_best))) hist.append(self.ng_best) return hist
|