예제 #1
0
def calc_pso():
    # num表示搜索范围,calc_func里的search_range长度必须与它保持一致
    num = 19
    # pso = PSO(func=calc_func, dim=num, pop=400, max_iter=400, lb=[0,825,30,0.01], ub=[0.24,930,680,1.17], w=0.8, c1=0.5, c2=0.5)
    # pso = PSO(func=calc_func, dim=num, pop=400, max_iter=400, lb=[30,300, 30,0.01,0.01, 0.01], ub=[863,900,680,2.78,0.65, 1.17], w=0.8,c1=0.5, c2=0.5)
    # pso = PSO(func=calc_func, dim=num, pop=20, max_iter=400, lb=[0, 30, 30, 0.01, 0.01, 0.01],
    #           ub=[30, 850, 160, 1.69, 0.23, 0.55], w=0.8, c1=0.2, c2=0.8)
    pso = PSO(func=calc_func,
              dim=num,
              pop=300,
              max_iter=1000,
              lb=[
                  825, 30, 0, 30, 0, 0, 0.16, 0.37, 0.002, 0.003, 0.01, 0, 30,
                  0, 30, 30, 0.01, 0.01, 0.01
              ],
              ub=[
                  930, 540, 15, 140, 120, 0.5, 0.35, 0.51, 0.008, 0.012, 0.11,
                  0.18, 930, 30, 850, 160, 1.69, 0.23, 0.55
              ],
              w=0.8,
              c1=0.2,
              c2=0.8)

    # pso = PSO(func=calc_func, dim=num, pop=500, max_iter=1000, lb=np.zeros(num), ub=np.ones(num),w=0.8, c1=0.2, c2=0.8)
    pso.run()
    print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
예제 #2
0
def calc_pso(num):
    f = open("./3_elements_result.info", 'w+')
    combins = [c for c in combinations(['Fe', 'Cu', 'Al', 'Mg', 'Co', 'Ni', 'Cr', 'Ti'], num)]
    for item in combins:
        global current_combins
        current_combins = item
        print('current combins: ', item, file=f)
        pso = PSO(func=calc_func, dim=num, pop=400, max_iter=400, lb=np.zeros(num), ub=np.ones(num)*100)
        pso.run()
        print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y, file=f)
    f.close()
예제 #3
0
def reg_time(args):
    #假设TEST_TIME为100
    #总运行次数小于T1(比如200)时,运行次数就是运行次数
    #总运行次数大于T1(比如200)时,计算运行次数乘以TEST_TIME/实际运行次数与T2的调和平均数
    #这里T1代表了实际最大运算次数,T2代表了计算结果的最大重算次数
    kind, f, p_min = args
    print(".", end="")
    res_ary = [1e+500]
    if kind == "de":
        de = DE(func=f,
                n_dim=DIM,
                lb=LB,
                ub=UB,
                max_iter=ITER // 2,
                size_pop=POP)
        time_de = 0
        while res_ary[-1] > p_min + MIN_PRECISION:
            if len(res_ary) > STOP_ITER_TIME and res_ary[
                    -STOP_ITER_TIME] - res_ary[-1] < CALC_PRECISION:
                return (False, time_de - STOP_ITER_TIME)
            _, temp_de = de.run()
            res_ary.append(temp_de[0])
            time_de += 1
        return (True, time_de)
    if kind == "ga":
        ga = GA(func=f,
                n_dim=DIM,
                lb=LB,
                ub=UB,
                max_iter=ITER,
                size_pop=POP,
                precision=1e-200)
        time_ga = 0
        while res_ary[-1] > p_min + MIN_PRECISION:
            if len(res_ary) > STOP_ITER_TIME and res_ary[
                    -STOP_ITER_TIME] - res_ary[-1] < CALC_PRECISION:
                return (False, time_ga - STOP_ITER_TIME)
            _, temp_ga = ga.run()
            res_ary.append(temp_ga[0])
            time_ga += 1
        return (True, time_ga)
    if kind == "pso":
        pso = PSO(func=f, dim=DIM, pop=POP, max_iter=ITER, lb=LB, ub=UB)
        time_pso = 0
        while res_ary[-1] > p_min + MIN_PRECISION:
            if len(res_ary) > STOP_ITER_TIME and res_ary[
                    -STOP_ITER_TIME] - res_ary[-1] < CALC_PRECISION:
                return (False, time_pso - STOP_ITER_TIME)
            pso.run()
            res_ary.append(pso.gbest_y)
            time_pso += 1
        return (True, time_pso)
예제 #4
0
def params_tuning():
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    pso = PSO(func=params_tuning_function,
              dim=4,
              pop=100,
              max_iter=50,
              lb=[5, 1, 3, 5],
              ub=[30, 5, 15, 30],
              w=0.8,
              c1=0.5,
              c2=0.5)
    pso.run()
    print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
예제 #5
0
def trainabPSO(model_name,dataset_name,iter_num):
	# init T,R,SP
	T = getSGGRes(model_name,dataset_name,"train",tasktype)
	R = getGT(model_name,dataset_name,"train",tasktype)
	SP,N = getPfromR(R,dataset_name)
	print("T info: ",len(T),len(T[0]),T[0][0])
	print("R info: ",len(R),len(R[0]),R[0][0])
	print("N: ",N)
	#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

	# start iteration

	for i in range(iter_num):

		#pso = PSO(func=fitness, dim=2, pop=100, max_iter=50, \
		#	lb=[0.0, 0.0], ub=[1e6, 1e6],w=0.8, c1=0.5, c2=0.5)
		
		#pso = PSO(func=fitness1, dim=3, pop=100, max_iter=100, \
		#	lb=[0.0, 0.0,0.0], ub=[1e6,1e6, 1e6],w=0.8, c1=2, c2=2)
		pso = PSO(func=fitnessNDCG, dim=2, pop=50, max_iter=50, \
			lb=[0.0, 0.0], ub=[1e6, 1e6],w=0.8, c1=0.5, c2=0.5)
		

		#pso = PSO(func=fitness, dim=2, pop=10, max_iter=5, \
		#	lb=[0.0, 0.0], ub=[1e6, 1e6],w=0.8, c1=2, c2=2)
		
		#pso.to(device=device)	#GPU
		start_time = time.time()
		pso.run()# best_x={alpha,beta},best_y=Q-R
		
		print("run time: ",time.time() - start_time)
		best_x = pso.gbest_x
		alpha, beta = pso.gbest_x
		best_y = pso.gbest_y
		print('iteration ',i,': best alpha and beta: ', best_x)
		print('best_y:', best_y)
		if best_y==0:
			print('best {alpha,beta}:',best_x,'best_y',best_y)
			end_cnt = fitnessNDCG(best_x)
			print("detect if zeros: ",end_cnt)
			if end_cnt==0:
				break
		else:
			#R = ReSet(alpha,beta)
			R = addsmallNDCG(alpha,beta,R)
			SP,_ = getPfromR(R,dataset_name)
			cnt_now=fitnessNDCG(best_x)
			print(i," iter :", cnt_now)
	return best_x
예제 #6
0
def calc_pso():
    # 'num' means search range,the length of parameter 'search_range' in calc_func should keep same with it
    num = 6
    pso = PSO(func=calc_func,
              dim=num,
              pop=300,
              max_iter=1000,
              lb=[10, 30, 30, 0.01, 0.01, 0.01],
              ub=[30, 850, 160, 1.69, 0.23, 0.55],
              w=0.8,
              c1=0.2,
              c2=0.8)
    # pso = PSO(func=calc_func, dim=num, pop=20, max_iter=1000, lb=np.zeros(num), ub=np.ones(num))
    pso.run()
    print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
예제 #7
0
def calc_pso():
    # num表示搜索范围,calc_func里的search_range长度必须与它保持一致
    num = 6
    # pso = PSO(func=calc_func, dim=num, pop=400, max_iter=400, lb=[0,825,30,0.01], ub=[0.24,930,680,1.17], w=0.8, c1=0.5, c2=0.5)
    # pso = PSO(func=calc_func, dim=num, pop=400, max_iter=2000, lb=[30,300, 30,0.01,0.01, 0.01], ub=[863,900,680,2.78,0.65, 1.17], w=0.8,c1=0.5, c2=0.5)
    # pso = PSO(func=calc_func, dim=num, pop=20, max_iter=400, lb=[0, 30, 30, 0.01, 0.01, 0.01],
    #           ub=[30, 895.812, 200, 0.02, 0.21, 0.91], w=0.8, c1=0.2, c2=0.8)
    pso = PSO(func=calc_func,
              dim=num,
              pop=300,
              max_iter=1000,
              lb=[10, 30, 30, 0.01, 0.01, 0.01],
              ub=[30, 850, 160, 1.69, 0.23, 0.55],
              w=0.8,
              c1=0.2,
              c2=0.8)
    # pso = PSO(func=calc_func, dim=num, pop=20, max_iter=400, lb=np.zeros(num), ub=np.ones(num))
    pso.run()
    print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
예제 #8
0
def calc_pso():
    # 'num' means search range,the length of parameter 'search_range' in calc_func should keep same with it
    num = 19
    # As the first two columns of 21-dimesional features in the based dataset value 0, so here perform pso search on the remained 19 features
    pso = PSO(func=calc_func,
              dim=num,
              pop=300,
              max_iter=1000,
              lb=[
                  825, 30, 0, 30, 0, 0, 0.16, 0.37, 0.002, 0.003, 0.01, 0, 30,
                  0, 30, 30, 0.01, 0.01, 0.01
              ],
              ub=[
                  930, 540, 15, 140, 120, 0.5, 0.35, 0.51, 0.008, 0.012, 0.11,
                  0.18, 930, 30, 850, 160, 1.69, 0.23, 0.55
              ],
              w=0.8,
              c1=0.2,
              c2=0.8)
    # pso = PSO(func=calc_func, dim=num, pop=500, max_iter=1000, lb=np.zeros(num), ub=np.ones(num),w=0.8, c1=0.2, c2=0.8)
    pso.run()
    print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
예제 #9
0
# plt.show()
'''
粒子群算法
'''


def func3(x):
    x1, x2, x3 = x
    return x1**2 + (x2 - 0.05)**2 + x3**2


pso = PSO(func=func3,
          dim=3,
          pop=40,
          max_iter=150,
          lb=[0, -1, 0.5],
          ub=[1, 1, 1],
          w=0.8,
          c1=0.5,
          c2=0.5)
pso.run()
print('\n带约束的粒子群算法\n')
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
# plt.plot(pso.gbest_y_hist)
# plt.show()
pso = PSO(func=func3, dim=3)
pso.run()
print('\n不带约束的粒子群算法\n')
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
'''
模拟退火算法
예제 #10
0
def demo_func(x):
    x1, x2, x3 = x
    return x1**2 + (x2 - 0.05)**2 + x3**2


from sko.PSO import PSO
pso = PSO(func=demo_func, dim=3)
fitness = pso.fit()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
pso.plot_history()

# from test_func import sphere as obj_func
예제 #11
0
import numpy as np
import matplotlib.pyplot as plt
from sko.PSO import PSO
from matplotlib.animation import FuncAnimation


def demo_func(x):
    x1, x2 = x
    return x1**2 + (x2 - 0.05)**2


pso = PSO(func=demo_func, dim=2, pop=20, max_iter=150, lb=[-1, -1], ub=[1, 1])
pso.record_mode = True
pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)

# %%
record_value = pso.record_value
X_list, V_list = record_value['X'], record_value['V']

fig, ax = plt.subplots(1, 1)
ax.set_title('title', loc='center')
line = ax.plot([], [], 'b.')

X_grid, Y_grid = np.meshgrid(np.linspace(-1.0, 1.0, 20),
                             np.linspace(-1.0, 1.0, 20))
Z_grid = demo_func((X_grid, Y_grid))
ax.contour(X_grid, Y_grid, Z_grid, 20)

ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
예제 #12
0
    # iou
    act_path = 'rbg_1.jpg'

    iou, pa = eval(mask_out_path, act_path)

    return -iou  # 最优化取最小值!!取负数!!


if __name__ == '__main__':
    # iou=find_path_func(20,0.3,0.2,0.2)
    # print(iou)

    set_run_mode(find_path_func, 'multiprocessing')
    print("pao1")
    pso = PSO(func=find_path_func, n_dim=4, pop=15, max_iter=30, lb=[0.1, 0.1, 0.1, 0.1], ub=[0.28, 0.8, 0.8, 0.8],
              w=0.8, c1=0.5, c2=0.5)
    print("pao2")
    pso.record_mode = True
    print("pao3")

    #5
    print("pao4")
    pso.run(5)
    print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
    plt.plot(pso.gbest_y_hist)
    plt.savefig('5.png')
    record_dict = pso.record_value
    f = open('5.txt', 'w')
    f.write(str(record_dict) + '\n' + 'best_x is ' + str(pso.gbest_x) + 'best_y is' + str(pso.gbest_y))
    f.close()
예제 #13
0
from sko.PSO import PSO


def demo_func(x):
    x1, x2 = x
    return -20 * np.exp(-0.2 * np.sqrt(0.5 * (x1**2 + x2**2))) - np.exp(
        0.5 * (np.cos(2 * np.pi * x1) + np.cos(2 * np.pi * x2))) + 20 + np.e


constraint_ueq = (lambda x: (x[0] - 1)**2 + (x[1] - 0)**2 - 0.5**2, )

max_iter = 50
pso = PSO(func=demo_func,
          n_dim=2,
          pop=40,
          max_iter=max_iter,
          lb=[-2, -2],
          ub=[2, 2],
          constraint_ueq=constraint_ueq)
pso.record_mode = True
pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)

# %% Now Plot the animation
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

record_value = pso.record_value
X_list, V_list = record_value['X'], record_value['V']

fig, ax = plt.subplots(1, 1)
예제 #14
0
import time


def demo_func(x):

    DT, Cr, Ni, C, TT, THT = x

    return -50.58 * pow(DT * (Cr + Ni),
                        1 / 3) - 2.24536 * C * (TT + DT - THT) - 158.7


time_start = time.time()

pso = PSO(func=demo_func,
          dim=6,
          pop=20,
          max_iter=400,
          lb=[30, 0, 0, 0, 0, 10],
          ub=[850, 0.55, 1.69, 0.23, 160, 30])

pso.record_mode = True

pso.run()

print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)

time_end = time.time()

# %% Now Plot the animation

# import matplotlib.pyplot as plt
#
예제 #15
0
            return ((a * l_0 * u * R * (l + O)) / (a * u * O - l_1 * a * (l + O) + l_0 * (a * (l + O) + a * u + r * (l + O)))) - \
                   (C / (a * u * O - l_1 * a * (l + O) + l_0 * (a * (l + O) + a * u + r * (l + O)))) * \
                   ((l_0 * (a * u + (l + O) * (r + a)) * (N + 1) / 2) + (a * (u * O - l_1 * (l + O)) * (N - 1) / 2) + \
                    ((a * l_0 * l_1 * (l + O) * (a * u + (l + O) * (r + a))) / (a * O * u - l_1 * (l + O))) - \
                    a * l_0 * l_1 + (a * r) * l * l_0)
        else:
            return 0

    def test(l_0, l_1):
        return -social1(l_0, l_1)

    pso = PSO(func=test,
              dim=2,
              pop=100,
              max_iter=2000,
              lb=[0, 0],
              ub=[1, 1],
              w=0.9,
              c1=2,
              c2=2)
    pso.run()
    x2.append(pso.gbest_x[0])
    y2.append(pso.gbest_x[1])

y2 = np.where(np.array(x2) == 0, np.array(x2), np.array(y2))
# print(x2)
# print(y2)

s1 = []
s2 = []
for i in range(len(M)):
예제 #16
0
def demo_func(x):
    x1, x2, x3 = x
    return x1**2 + (x2 - 0.05)**2 + x3**2


from sko.PSO import PSO

pso = PSO(func=demo_func, dim=3)
fitness = pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
pso.plot_history()

# from test_func import sphere as obj_func

# %% PSO with constrain:
print('*' * 50, '\n PSO with constrain:')

pso = PSO(func=demo_func, dim=3, lb=[0, -1, 0.5], ub=[1, 1, 1])
pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
예제 #17
0
def demo_func(x):
    x1, x2, x3 = x
    return x1**2 + (x2 - 0.05)**2 + x3**2


from sko.PSO import PSO

pso = PSO(func=demo_func,
          dim=3,
          pop=40,
          max_iter=150,
          lb=[0, -1, 0.5],
          ub=[1, 1, 1],
          w=0.8,
          c1=0.5,
          c2=0.5)
pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)

import matplotlib.pyplot as plt

plt.plot(pso.gbest_y_hist)
plt.show()

# %% PSO without constraint:
pso = PSO(func=demo_func, dim=3)
fitness = pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
예제 #18
0
        d = np.linalg.norm(x - np.array(sensor.get_pos()))
        if (d <= R):
            num += 1
            u = A/ ((d + B) ** 2)  # 该节点的充电效率
            uRate = uWorst / u  # 最差充电效率与当前充电效率之比
            if uRate > maxU:
                maxU = uRate
    # 计算适应值
    if num == 0:
        fitness = np.float('inf')
    else:
         fitness = c1 * num + c2 * maxU
    return fitness



if __name__ == '__main__':
    # 生成传感器
    sensors = Sensor.generateSensor(30, 10)
    # 萤火虫算法
    bound = np.tile([[0], [10]], 2)
    fa = FireflyAlgorithm(20, 2, bound, 20, [1.0, 0.9, 0.3])
    fa.solve(sensors, 10)



    pso = PSO(func=calculateFitness, dim=2, sensors=sensors,pop=20, max_iter=20, lb=[0,0], ub=[10,10], w=0.8, c1=0.5, c2=0.5)
    pso.run(sensors)
    print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
    # plt.plot(pso.gbest_y_hist)
예제 #19
0
def calc_pso():
    # num表示搜索范围,calc_func里的search_range长度必须与它保持一致
    num = 4
    pso = PSO(func=calc_func, dim=num, pop=400, max_iter=400, lb=np.zeros(num), ub=np.ones(num)*100)
    pso.run()
    print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
예제 #20
0

def objective(x):    return 0.0007 * x ** 2 + 0.3 * x + 4 + \
0.0004 * (100 - x) ** 2 + 0.32 * (100 - x) + 3


# -flim <= S * [[pg1], [pg2], [-100]] <= flim, 0 <= pg2 <= 50
constraint_ueq = [lambda x: -S[i, 0] * x - S[i, 1] * (100 - x) - S[i, 2] * (-100) - flim[i] for i in range(3)] + \
                 [lambda x: S[i, 0] * x + S[i, 1] * (100 - x) + S[i, 2] * (-100) - flim[i] for i in range(3)] + \
                 [lambda x: 100 - x - 50, lambda x: x - 100]

pso = PSO(func=objective,
          n_dim=1,
          pop=40,
          max_iter=500,
          lb=[30],
          ub=[150],
          w=0.9,
          c1=2,
          c2=2,
          constraint_ueq=constraint_ueq)
pso.run()
print('PG1 =', pso.gbest_x, 'PG2 =', 100 - pso.gbest_x, 'F =', pso.gbest_y)
plt.plot(pso.gbest_y_hist)
plt.show()
# %% [markdown]
# # 课堂练习
# <div align=center><img src='../../pics/pic18.png' /></div>
#
# ## 目标函数
# $$
# min:
예제 #21
0
def P_min(f):
    other_mins = []
    de = DE(func=f, n_dim=DIM, lb=LB, ub=UB, max_iter=ITER // 2, size_pop=POP)
    ga = GA(func=f,
            n_dim=DIM,
            lb=LB,
            ub=UB,
            max_iter=ITER,
            size_pop=POP,
            precision=1e-200)
    pso = PSO(func=f, dim=DIM, pop=POP, max_iter=ITER, lb=LB, ub=UB)
    _, e_de = de.run()
    e_de = e_de[0]
    _, e_ga = ga.run()
    e_ga = e_ga[0]
    pso.run()
    e_pso = pso.gbest_y
    time_de, time_ga, time_pso = 0, 0, 0
    cnt = 0
    while True:
        de_x, temp_de = de.run()
        temp_de = temp_de[0]
        time_de = time_de + 1 if e_de - temp_de < CALC_PRECISION else 0
        e_de = temp_de
        ga_x, temp_ga = ga.run()
        temp_ga = temp_ga[0]
        time_ga = time_ga + 1 if e_ga - temp_ga < CALC_PRECISION else 0
        e_ga = temp_ga
        pso.run()
        time_pso = time_pso + 1 if e_pso - pso.gbest_y < CALC_PRECISION else 0
        e_pso = pso.gbest_y
        res = sorted([[e_de, time_de, de_x], [e_ga, time_ga, ga_x],
                      [e_pso, time_pso, pso.gbest_x]],
                     key=lambda x: x[0])
        if res[1][0] - res[0][0] < CALC_PRECISION and res[0][
                1] > STOP_ITER_TIME:
            return (res[0][0], res[0][2])
        if res[0][1] > STOP_ITER_TIME and res[1][1] > STOP_ITER_TIME and res[
                2][1] > STOP_ITER_TIME:
            other_mins.append((res[0][0], res[0][2]))
            if len(other_mins) == 10:
                return min(other_mins, key=lambda x: x[0])
            res = []
            de = DE(func=f,
                    n_dim=DIM,
                    lb=LB,
                    ub=UB,
                    max_iter=ITER // 2,
                    size_pop=POP)
            ga = GA(func=f,
                    n_dim=DIM,
                    lb=LB,
                    ub=UB,
                    max_iter=ITER,
                    size_pop=POP,
                    precision=1e-200)
            pso = PSO(func=f, dim=DIM, pop=POP, max_iter=ITER, lb=LB, ub=UB)
            de_x, e_de = de.run()
            e_de = e_de[0]
            ga_x, e_ga = ga.run()
            e_ga = e_ga[0]
            pso.run()
            e_pso = pso.gbest_y
            time_de, time_ga, time_pso = 0, 0, 0
def en(code):
    pop,it,w,c1,c2=code
    pso  = PSO(func=obj, dim=2,pop=int(pop), max_iter=int(it), lb=[-5,-5], ub=[5,5], w=w, c1=c1, c2=c2)
    pso.run()
    return pso.gbest_y