Exemplo n.º 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)
Exemplo n.º 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()
Exemplo n.º 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)
Exemplo n.º 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())))
Exemplo n.º 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
Exemplo n.º 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)
Exemplo n.º 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)
Exemplo n.º 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)
Exemplo n.º 9
0
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)
'''
模拟退火算法
'''
sa = SA(func=func3,
        x0=[1, 1, 1],
        T_max=1,
        T_min=1e-9,
Exemplo n.º 10
0
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()

    #10
    pso.run(5)
    print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
    plt.plot(pso.gbest_y_hist)
    plt.savefig('10.png')
    record_dict = pso.record_value
    f = open('10.txt', 'w')
    # iou=find_path_func(X)
    # print(iou)

    set_run_mode(find_path_func, 'multiprocessing')
    # set_run_mode(find_path_func, 'multithreading')

    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")

    # 1
    print("pao4")
    pso.run(2)
    print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
    plt.plot(pso.gbest_y_hist)
    plt.savefig('2.png')
    record_dict = pso.record_value
    f = open('2.txt', 'w')
    f.write(str(record_dict) + '\n' + 'best_x is ' + str(pso.gbest_x) + 'best_y is' + str(pso.gbest_y))
    f.close()

    5
    print("pao4")
    pso.run(4)
    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
Exemplo n.º 12
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)
Exemplo n.º 13
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)
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
Exemplo n.º 15
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
Exemplo n.º 16
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)