示例#1
0
def trainab(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])
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    dd = 1e23
    # start iteration

    for i in range(iter_num):
        ga = GA(func=fitness, n_dim=2, size_pop=10, max_iter=50, \
         lb=[0.0, 0.0], ub=[dd, dd], precision=1e-7)
        #ga = GA(func=fitness, n_dim=2, size_pop=10, max_iter=4, \
        #	lb=[0.0, 0.0], ub=[dd, dd], precision=1e-7)

        ga.to(device=device)  #GPU
        best_x, best_y = ga.run()  # best_x={alpha,beta},best_y=Q-R
        alpha, beta = best_x
        print('iteration ', i, ': best alpha and beta: ', alpha, beta)
        print('best_y:', best_y)
        if best_y == 0:
            print('best {alpha,beta}:', best_x, 'best_y', best_y)
            end_cnt = fitness(best_x)
            print("detect if zeros: ", end_cnt)
            if end_cnt == 0:
                break
        else:
            R = ReSet(alpha, beta)
            SP, _ = getPfromR(R, dataset_name)
    return best_x
示例#2
0
 def fit_ga(self, y0, E, I, R, n):
     self.parameter = [E, I, R, y0]
     self.y0 = y0
     if n == 4:
         ga = GA(func=self.loss_function_ga,
                 n_dim=4,
                 size_pop=50,
                 max_iter=300,
                 lb=[0, 0, 0, 0],
                 ub=[1, 1, 1, 1])
     elif n == 2:
         ga = GA(func=self.loss_function_ga_2,
                 n_dim=2,
                 size_pop=50,
                 max_iter=300,
                 lb=[0, 0],
                 ub=[1, 1])  # 遗传算法求解
     best_x, best_y = ga.run()
     if n == 4:
         alpha, beta1, beta2, gamma2 = best_x[0], best_x[1], best_x[
             2], best_x[3]
         return alpha, beta1, beta2, gamma2
     elif n == 2:
         alpha, gamma2 = best_x[0], best_x[1]
         return alpha, gamma2
示例#3
0
 def fit2(self):
     # ga_beta = GA(func=self.loss_function2_beta, n_dim=2, size_pop=50, max_iter=1000, lb=[0, 0], ub=[1, 1], precision=1e-7)
     # ga_gamma = GA(func=self.loss_function2_gamma, n_dim=2, size_pop=50, max_iter=1000, lb=[0, 0], ub=[1, 1], precision=1e-7)
     # best_x_beta, best_y = ga_beta.run()
     # best_x_gamma, best_y = ga_gamma.run()
     ga = GA(func=self.loss_function2, n_dim=2, size_pop=50, max_iter=3000, lb=[0, 0], ub=[1, 1], precision=1e-7)
     best_x, best_y = ga.run()
     # self.__beta = best_x_beta[0]
     # self.__gamma = best_x_gamma[1]
     self.__beta = best_x[0]
     self.__gamma = best_x[1]
     print('best_x:', best_x)
示例#4
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)
示例#5
0
def GAmethod(max_iter=50, size_pop=500):
    lb = lb
    ub = ub
    ga = GA(func=calculEffFunc,
            n_dim=5,
            size_pop=size_pop,
            max_iter=max_iter,
            lb=lb,
            ub=ub,
            precision=1e-7,
            prob_mut=prob_mut)  #只求解最小值

    best_x, best_y = ga.run()
    Y_history = ga.all_history_Y
    return best_x, best_y, Y_history, ga.generation_best_Y
示例#6
0
def findWay(tryNum):  # 找从起点移动tryNum步距终点最近的路径
    lBoundary = []  # 存自变量下界
    uBoundary = []  # 存自变量上界
    precisions = []  # 存自变量精度

    for i in range(tryNum):  # 0,1,2,3代表四个方向,从0到3,精度为1
        lBoundary.append(0)
        uBoundary.append(3)
        precisions.append(1)

    ga = GA(func=demo_func,
            n_dim=tryNum,
            size_pop=150,
            max_iter=1000,
            lb=lBoundary,
            ub=uBoundary,
            precision=precisions)
    return ga.run()
示例#7
0
def GA_CAV_included_best_UE(control_portion):
    constraint_ueq = [
        lambda x: sum(x) - 5 * control_portion,
    ]
    # ga = SA(func=CAV_UE, x0=[0]*15, n_dim=15, size_pop=50, max_iter=200, lb=[0]*15, ub=[5]*15, precision=1e-7, constraint_eq=constraint_eq)
    # ga = PSO(func=CAV_UE, n_dim=15, size_pop=50, max_iter=200, lb=[0]*15, ub=[5]*15, precision=1e-7, constraint_eq=constraint_eq)
    set_run_mode(CAV_UE, 'multiprocessing')
    ga = GA(func=CAV_UE,
            n_dim=2,
            size_pop=50,
            max_iter=800,
            lb=[0] * 2,
            ub=[5 * control_portion] * 2,
            precision=1e-5,
            constraint_ueq=constraint_ueq)
    best_x, best_y = ga.run()
    print('best_x:', best_x, '\n', 'best_y:', best_y)
    return best_y
示例#8
0
def config_ga():
    lb = [1] * (station_count + truck_count - 1)
    ub = [21] * (station_count + truck_count - 1)
    iteration = int(cfg.read_config("iteration_time"))
    ga = GA(func=fitness_fun,
            size_pop=100,
            n_dim=station_count + truck_count - 1,
            max_iter=iteration,
            prob_mut=0.01,
            lb=lb,
            ub=ub,
            precision=[1] * (station_count + truck_count - 1))
    ga.Chrom = generate_new_pop()
    if cfg.read_config("crossover_type") is not None:
        ga.register(operator_name='crossover', operator=customized_crossover). \
            register(operator_name='mutation', operator=customized_mutation)
    # TODO: 排序的策略配置(暂时不考虑)
    return ga
示例#9
0
文件: ga.py 项目: rqhu1995/bikeshare
def config_ga():
    constraint_eq = [
        lambda x: int(cfg.read_config('bike_total_count')) - sum(x)
    ]
    lb = [0] * station_count
    ub = hub.hub
    iteration = int(cfg.read_config("iteration_time"))
    ga = GA(func=fitness_fun,
            size_pop=300,
            n_dim=station_count,
            max_iter=iteration,
            prob_mut=0.01,
            lb=lb,
            ub=ub,
            constraint_eq=constraint_eq,
            precision=[1] * 20)
    if cfg.read_config("crossover_type") is not None:
        ga.register(operator_name='crossover',
                    operator=crossover.crossover_1point)
    # TODO: 变异和排序的策略配置(暂时不考虑)
    return ga
示例#10
0
    def test_x2gray(self):
        cases = [
            [2, [-1, -1], [1, 1], 1e-7],
            [5, [-10, -1, -3, -4.5, 1.5], [1, 3, 5, 7.8, 9.8], 1e-7],
            [3, [0, -5, -10], [15, 10, 5], 1],
        ]
        for n_dim, lb, ub, precision in cases:
            ga = GA(func=lambda x: x,
                    n_dim=n_dim,
                    size_pop=200,
                    max_iter=800,
                    lb=lb,
                    ub=ub,
                    precision=precision)

            value = ga.chrom2x(ga.Chrom)
            chrom2 = x2gray(x=value,
                            n_dim=n_dim,
                            lb=lb,
                            ub=ub,
                            precision=precision)
            self.assertTrue(np.allclose(ga.Chrom, chrom2), msg='x2gray error')
示例#11
0
def GAmethod(max_iter=50):
    start_time = datetime.now()
    ga = GA(func=finallFunction,
            n_dim=5,
            size_pop=size_pop,
            max_iter=max_iter,
            lb=lb,
            ub=ub,
            prob_mut=prob_mut)  #只求解最小值
    end_time = datetime.now()
    print('Itreation numbers is {}, weight is '.format(max_iter) +
          str(weight) +
          ' using time is {}'.format((end_time - start_time).total_seconds()))
    best_x, best_y = ga.run()
    Y_history = ga.all_history_Y
    tm = time.localtime(time.time())
    tm_str = '{}-{}-{} {}:{}:{} '.format(tm[0], tm[1], tm[2], tm[3], tm[4],
                                         tm[5])

    with open(r'GArecordHistory_Y.txt', 'a') as f:
        for yh in ga.all_history_Y:
            f.write(str(yh)[1:-1] + '\n\n')
    with open(r'GAbestPredictCircuit.txt', 'a') as f:
        f.write(tm_str +
                'GA algorithm iteration number is {} best Predict Circuit is '.
                format(max_iter) + str(bestPredictCircuit)[1:-1] +
                ' using time is {}'.format((end_time -
                                            start_time).total_seconds()) +
                '\n')
    with open(r'GAbestStructure.txt', 'a') as f:
        f.write(
            tm_str +
            'GA algorithm iteration number is {}, weight is {} best Structure is '
            .format(max_iter, weight) + str(best_x)[1:-1] + ' ' +
            'Best result is ' +
            str(bestPredictCircuit[0] - bestPredictCircuit[1] +
                bestPredictCircuit[2] - bestPredictCircuit[3]) + '\n')

    return best_x, best_y, Y_history, ga
示例#12
0
    def __init__(self,
                 env,
                 pop_size=100,
                 genotype_size=61,
                 lb=-1,
                 ub=1,
                 max_iter=100,
                 init=None):

        self.env = env
        global E
        E = env

        #The evolutionary search object
        self.ga = GA(func=EvaluateGenome,
                     n_dim=genotype_size,
                     size_pop=pop_size,
                     max_iter=max_iter,
                     lb=lb,
                     ub=ub,
                     precision=1e-7)
        if init is not None:
            self.ga.Chrom = init
示例#13
0
class EvolutionarySearch:
    def __init__(self,
                 env,
                 pop_size=100,
                 genotype_size=61,
                 lb=-1,
                 ub=1,
                 max_iter=100,
                 init=None):

        self.env = env
        global E
        E = env

        #The evolutionary search object
        self.ga = GA(func=EvaluateGenome,
                     n_dim=genotype_size,
                     size_pop=pop_size,
                     max_iter=max_iter,
                     lb=lb,
                     ub=ub,
                     precision=1e-7)
        if init is not None:
            self.ga.Chrom = init

    def calc_genotype(self, pheno_dict):
        genotype_length = 0
        for key in pheno_dict:
            genotype_length += len(pheno_dict[key])
        return genotype_length

    def run(self, increments=10):

        total_its = self.ga.max_iter // increments
        for i in range(total_its):
            best_x, best_y = self.ga.run(max_iter=increments)
            gen = (i + 1) * increments
            print(f'Generation: {gen}')
            print('best_x:', best_x, '\n', 'best_y:', best_y)
            # %% Plot the result

        Y_history = pd.DataFrame(self.ga.all_history_Y)
        fig, ax = plt.subplots(2, 1)
        ax[0].plot(Y_history.index, Y_history.values, '.', color='red')
        Y_history.min(axis=1).cummin().plot(kind='line')
        plt.show()
        fig.savefig('./evo_run.pdf')
        Y_history.to_pickle("Run_history.pkl")

        return best_x
示例#14
0
def trainabGA(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])
	device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
	
	# start iteration
	low = [0.0,0.0]
	high = [1e6,1e6]
	
	for i in range(iter_num):
		#ga = GA(func=fitness, n_dim=2, size_pop=4, max_iter=10, \
		#	lb=[0.0, 0.0], ub=[1.0, 1.0], precision=1e-7)
		#ga = GA(func=fitness, n_dim=2, size_pop=6, max_iter=50, \
		#	lb=low, ub=high, precision=1e-7)
		
		#ga = GA(func=fitness, n_dim=2, size_pop=50, max_iter=50, \
		#	lb=low, ub=high, precision=1e-7)
		ga = GA(func=fitnessNDCG, n_dim=2, size_pop=100, max_iter=100, \
			lb=low, ub=high, precision=1e-7)

	
		ga.register(operator_name='selection', operator=selection_tournament, tourn_size=3).\
			register(operator_name='ranking', operator=ranking.ranking). \
    			register(operator_name='crossover', operator=crossover.crossover_2point). \
    			register(operator_name='mutation', operator=mutation.mutation)
		ga.to(device=device)	#GPU
		start_time = time.time()
		best_x, best_y = ga.run()# best_x={alpha,beta},best_y=Q-R
		print("run time: ",time.time() - start_time)
		
		alpha, beta = best_x
		print('iteration ',i,': best alpha and beta: ', alpha,beta)
		print('best_y:', best_y)
		print("sum_ndcg: ",-best_y-0.5*(alpha**2+beta**2))
		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=fitness(best_x)
			print(i," iter :", cnt_now)

	return best_x
示例#15
0
    def _calT():
        def obj_func(p):
            x1, x2 = p
            return np.abs(r[kx, ky, 1] - x1 - x2 + r[kx - 1, ky, 0])

        if r[kx, ky + 1, 1] == NaN:
            constraint_ueq = [lambda x: np.abs(r[kx, ky, 1] - x[0]) - 0.1]
            ga = GA(func=obj_func,
                    n_dim=2,
                    size_pop=popsize,
                    max_iter=maxiter,
                    lb=[0, -r[kx - 1, ky + 1, 2]],
                    ub=[r[kx, ky + 1, 2] + prec, r[kx - 1, ky + 1, 2] + prec],
                    precision=[prec, prec],
                    constraint_ueq=constraint_ueq)
        else:
            constraint_ueq = [
                lambda x: np.abs(r[kx, ky, 0] - x[0]) - 0.1,
                lambda x: np.abs(r[kx - 1, ky, 1] - x[1]) - 0.1,
            ]
            constraint_eq = [
                lambda x: r[kx, ky + 1, 2]**2 - r[kx, ky + 1, 1]**2 - x[0]**2
            ]
            ga = GA(func=obj_func,
                    n_dim=2,
                    size_pop=popsize,
                    max_iter=maxiter,
                    lb=[0, -r[kx - 1, ky + 1, 2]],
                    ub=[r[kx, ky + 1, 2] + prec, r[kx - 1, ky + 1, 2] + prec],
                    precision=[prec, prec],
                    constraint_eq=constraint_eq,
                    constraint_ueq=constraint_ueq)
        best_x, _ = ga.run()
        r[kx, ky + 1, 0] = best_x[0]
        r[kx - 1, ky + 1, 1] = best_x[1]
        return
示例#16
0
 def ga_opt(self, max_=False):
     if not max_:
         ga = GA(func=self.func, n_dim=len(self.lb), size_pop=50, max_iter=int(self.repeaT), lb=self.lb, ub=self.ub,
                 constraint_eq=self.eq_ls, constraint_ueq=self.ueq_ls, precision=1e-5)
         self.best_x, self.best_y = ga.run()
     elif max_:
         ga = GA(func=-self.func, n_dim=len(self.lb), size_pop=50, max_iter=int(self.repeaT), lb=self.lb, ub=self.ub,
                 constraint_eq=self.eq_ls, constraint_ueq=self.ueq_ls, precision=1e-5)
         self.best_x, self.best_y = ga.run()
         self.best_y = -self.best_y
示例#17
0
def x2gray(x, n_dim, lb, ub, precision):
    ga = GA(func=lambda k: None, n_dim=n_dim, size_pop=2, max_iter=1, lb=lb, ub=ub, precision=precision)

    ub = ga.ub_extend if ga.int_mode else ga.ub  # for int mode
    x = (x - ga.lb) / (ub - ga.lb)  # map to (0,1)
    x = np.round(x * (np.exp2(ga.Lind) - 1)).astype(int)  # map to int

    res = np.zeros((x.shape[0], ga.Lind.sum()))
    for row_idx, row in enumerate(x):
        tmp1 = ''
        for col_idx, col in enumerate(row):
            tmp2 = bin(col ^ (col >> 1))[2:]  # real value to gray code
            tmp2 = '0' * (ga.Lind[col_idx] - len(tmp2)) + tmp2  # zero fill
            tmp1 += tmp2
        res[row_idx, :] = (np.array(list(tmp1)) == '1') * 1

    return res
示例#18
0
        aspirants_index = np.random.choice(range(algorithm.size_pop),
                                           size=tourn_size)
        sel_index.append(max(aspirants_index, key=lambda i: FitV[i]))
    algorithm.Chrom = algorithm.Chrom[sel_index, :]  # next generation
    return algorithm.Chrom


# %% step2: import package and build ga, as usual.
import numpy as np
from sko.GA import GA, GA_TSP

demo_func = lambda x: x[0]**2 + (x[1] - 0.05)**2 + (x[2] - 0.5)**2
ga = GA(func=demo_func,
        n_dim=3,
        size_pop=100,
        max_iter=500,
        lb=[-1, -10, -5],
        ub=[2, 10, 2],
        precision=[1e-7, 1e-7, 1])

# %% step3: register your own operator
ga.register(operator_name='selection',
            operator=selection_tournament,
            tourn_size=3)
# %% Or import the operators scikit-opt already defined.
from sko.operators import ranking, selection, crossover, mutation

ga.register(operator_name='ranking', operator=ranking.ranking). \
    register(operator_name='crossover', operator=crossover.crossover_2point). \
    register(operator_name='mutation', operator=mutation.mutation)
# %% Run ga
示例#19
0
#这个代码用来示意遗传算法
import numpy as np
def schaffer(p):
#这是自定义的函数(即优化的目标函数)
    '''
    This function has plenty of local minimum, with strong shocks
    global minimum at (0,0) with value 0
    '''
    x1, x2 = p
    x = np.square(x1) + np.square(x2) #f(x1,x2) =0.5 + (sin^2(x1^2 + x2^2)-0.5)/ ((1+0.001*x)^2)
    return 0.5 + (np.square(np.sin(x)) - 0.5) / np.square(1 + 0.001 * x)
from sko.GA import GA
ga = GA(func=schaffer, n_dim=2, size_pop=50, max_iter=800, lb=[-1, -1], ub=[1, 1], precision=1e-7)
best_x, best_y = ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y) #这里对函数的最优值进行了求解

#绘图

import pandas as pd
import matplotlib.pyplot as plt

Y_history = pd.DataFrame(ga.all_history_Y)
print(Y_history)
fig, ax = plt.subplots(2, 1)
plt.rcParams['font.sans-serif']=['SimHei'] #指定默认字体 SimHei为黑体
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
print(Y_history.index)
ax[0].plot(Y_history.index, Y_history.values, '.', color='red')
ax[0].set_title('目标函数值优化路线')
ax[1].plot(Y_history.index,Y_history.min(axis=1).cummin())
# Y_history.min(axis=1).cummin().plot(kind='line')
示例#20
0
import numpy as np


def schaffer(p):
    '''
    This function has plenty of local minimum, with strong shocks
    global minimum at (0,0) with value 0
    '''
    x1, x2 = p
    x = np.square(x1) + np.square(x2)
    return 0.5 + (np.square(np.sin(x)) - 0.5) / np.square(1 + 0.001 * x)


# %%
from sko.GA import GA

ga = GA(func=schaffer, n_dim=2, size_pop=50, max_iter=800, prob_mut=0.001, lb=[-1, -1], ub=[1, 1], precision=1e-7)
best_x, best_y = ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)
# %% Plot the result
import pandas as pd
import matplotlib.pyplot as plt

Y_history = pd.DataFrame(ga.all_history_Y)
fig, ax = plt.subplots(2, 1)
ax[0].plot(Y_history.index, Y_history.values, '.', color='red')
Y_history.min(axis=1).cummin().plot(kind='line')
plt.show()
示例#21
0
# %% Global definition
SEED = 1024
n_dim = 10
func = lambda x: schaffer_nd(x, n=n_dim)
n_pop = 50
n_iter = 50
lb = [-10] * n_dim
ub = [10] * n_dim
# lb = [0] * n_dim
# ub = [10] * n_dim
# %% sko GA optimizer
np.random.seed(SEED)
skoga = GA(func=lambda x: -func(x)[0] if func == ode_loss_func else -func(x),
           n_dim=n_dim,
           size_pop=n_pop,
           max_iter=n_iter,
           prob_mut=0.05,
           lb=lb,
           ub=ub,
           precision=1e-5)

sko_best_x, sko_best_y = skoga.run()
Y_history = pd.DataFrame(skoga.all_history_Y)

# %% Self defined GA optimizer
np.random.seed(SEED)
ga_opt = GAOPT(
    func=func,
    n_dim=n_dim,
    n_iter=n_iter,
    n_pop=n_pop,
    pcr=0.9,
for task_type in ('io_costly', 'cpu_costly'):
    costly_function = generate_costly_function(task_type=task_type)

    def obj_func(p):
        costly_function()
        x1, x2 = p
        x = np.square(x1) + np.square(x2)
        return 0.5 + (np.square(np.sin(x)) - 0.5) / np.square(1 + 0.001 * x)

    for mode in ('common', 'multithreading', 'multiprocessing'):
        set_run_mode(obj_func, mode)
        ga = GA(func=obj_func,
                n_dim=2,
                size_pop=10,
                max_iter=5,
                lb=[-1, -1],
                ub=[1, 1],
                precision=1e-7)
        start_time = datetime.datetime.now()
        best_x, best_y = ga.run()
        print(
            'on {task_type} task,use {mode} mode, costs {time_costs}s'.format(
                task_type=task_type,
                mode=mode,
                time_costs=(datetime.datetime.now() -
                            start_time).total_seconds()))

    # to use the vectorization mode, the function itself should support the mode.
    mode = 'vectorization'
示例#23
0
'''GA求函数最值'''

import numpy as np
from sko.GA import GA

'''求f(x) = x ^ 2在[0, 31]上的最大值'''
t = 0.0001
def demo_func(p):
    x1, = p
    return 1.0 / (np.square(x1) + t)

ga = GA(func=demo_func, n_dim=1, size_pop=50, max_iter=800, lb=[0], ub=[31], precision=1e-7)
best_x, best_y = ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)
        x = np.square(x1) + np.square(x2)
        return 0.5 + (np.square(np.sin(x)) - 0.5) / np.square(1 + 0.001 * x)

    def obj_func4_2(self, p):
        time.sleep(0.1)  # say that this function is very complicated and cost 0.1 seconds to run
        x1, x2 = p
        x = np.square(x1) + np.square(x2)
        return 0.5 + (np.square(np.sin(x)) - 0.5) / np.square(1 + 0.001 * x)


your_class = YourClass()

set_run_mode(your_class.obj_func2, 'vectorization')
set_run_mode(your_class.obj_func3, 'parallel')

ga1 = GA(func=your_class.obj_func1, n_dim=2, size_pop=10, max_iter=5, lb=[-1, -1], ub=[1, 1], precision=1e-7)
ga2 = GA(func=your_class.obj_func2, n_dim=2, size_pop=10, max_iter=5, lb=[-1, -1], ub=[1, 1], precision=1e-7)
ga3 = GA(func=your_class.obj_func3, n_dim=2, size_pop=10, max_iter=5, lb=[-1, -1], ub=[1, 1], precision=1e-7)

start_time = datetime.datetime.now()
best_x, best_y = ga1.run()
print('common mode, time costs: ', (datetime.datetime.now() - start_time).total_seconds())

start_time = datetime.datetime.now()
best_x, best_y = ga2.run()
print('vector mode, time costs: ', (datetime.datetime.now() - start_time).total_seconds())

start_time = datetime.datetime.now()
best_x, best_y = ga3.run()
print('parallel mode, time costs: ', (datetime.datetime.now() - start_time).total_seconds())
示例#25
0
    #     print('查全率:', recall_score)
    #     print('p:', p)
    # '-----'
    # if prec_score > best:  # 选择查准率最大的
    #     best = prec_score
    #     pd.DataFrame(p).to_csv('../data/parm_prec.csv')
    #     print('查准率:', prec_score)
    #     print('p:', p)
    return test_loss[1]


# '--------------'
# lb为定义域的下限,ub为定义域的上限
ga = GA(func=schaffer2,
        n_dim=input_num * 27 + 27 * 1,
        size_pop=2,
        max_iter=1,
        precision=1e-7)
best_x, best_y = ga.run()
# '---'
# best_x = pd.read_csv('../data/parm_acc.csv')
# best_x = best_x.iloc[:, 1].values
# '--------------'
p = pd.DataFrame(best_x)
a = p.iloc[:input_num * 27]
b = p.iloc[input_num * 27:]
a = np.array(a).reshape((input_num, 27))
b = np.array(b).reshape((27, 1))
# 预测
en = [
    10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 150, 140, 160, 180, 200, 220,
示例#26
0
'''
遗传算法
    这里的func有一堆局部最小值,全局最小值在(0, 0),是0
'''


def func2(p):  # 涟漪状
    x1, x2 = p
    x = np.square(x1) + np.square(x2)
    return 0.5 + (np.sin(x) - 0.5) / np.square(1 + 0.001 * x)


ga = GA(func=func2,
        n_dim=2,
        size_pop=50,
        max_iter=200,
        lb=[-1, -1],
        ub=[1, 1],
        precision=1e-7)
best_x, best_y = ga.run()
print('\n遗传\n')
print('best_x:', best_x, '\nbest_y:', best_y)

# Y_history = pd.DataFrame(ga.all_history_Y)
# fig, ax = plt.subplots(2, 1)
# ax[0].plot(Y_history.index, Y_history.values, '.', color='red')
# Y_history.min(axis=1).cummin().plot(kind='line')
# plt.show()
'''
遗传算法用于旅行商问题
'''
示例#27
0
    sa = SA(func=obj,
            dim=2,
            pop=pop,
            x0=[s1, s2],
            T_max=10**t_max,
            T_min=10**t_min,
            L=l,
            max_stay_counter=stay)
    best_x, best_y = sa.run()
    return best_y


ga = GA(func=en,
        n_dim=7,
        size_pop=50,
        max_iter=10,
        lb=[1, -3, -3, -7, -12, 1, 1],
        ub=[100, 3, 3, 0, -7, 500, 500],
        precision=1e-7)

best_x, best_y = ga.run()
#%%
result = np.array(ga.all_history_Y)
np.repeat(np.arange(10), 50)
plt.scatter(np.repeat(np.arange(10), 50),
            result.reshape(-1, 1),
            label='raw_data')
plt.plot(result.min(axis=1),
         '--',
         c='r',
         lw=5,
示例#28
0
def loss_func1(start_add, test_num):
    start_add = int(start_add)
    test_num = int(test_num)
    if start_add + test_num >= length - 2:
        return Max
    country.set_start_sub(start_add)  # 设置起始数据
    italy_err = country.sir_main_nopic(forecast_add=test_num,
                                       test_num=test_num)  # 25656122.19997323
    print('italy_err:', italy_err)
    return italy_err


if __name__ == '__main__':
    ga = GA(func=loss_func1,
            n_dim=2,
            size_pop=50,
            max_iter=3,
            lb=[0, 0],
            ub=[length, length])  # 遗传算法求解
    best_x, best_y = ga.run()
    start_add = best_x[0]
    test_num = best_x[1]
    start_add = int(start_add)
    test_num = int(test_num)
    print('start_add:', start_add)
    print('test_num:', int(test_num))
    country.set_start_sub(start_add)
    err = country.sir_main(forecast_add=test_num + 10, test_num=test_num)
    print(err)
示例#29
0
from sko.GA import GA

demo_func = lambda x: x[0] ** 2 + (x[1] - 0.05) ** 2 + x[2] ** 2
ga = GA(func=demo_func, n_dim=3, max_iter=500, lb=[-1, -10, -5], ub=[2, 10, 2])
best_x, best_y = ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)

import pandas as pd
import matplotlib.pyplot as plt

Y_history = ga.all_history_Y
Y_history = pd.DataFrame(Y_history)
fig, ax = plt.subplots(3, 1)
ax[0].plot(Y_history.index, Y_history.values, '.', color='red')
plt_mean = Y_history.mean(axis=1)
plt_max = Y_history.min(axis=1)
ax[1].plot(plt_mean.index, plt_mean, label='mean')
ax[1].plot(plt_max.index, plt_max, label='min')
ax[1].set_title('mean and all Y of every generation')
ax[1].legend()
ax[2].plot(plt_max.index, plt_max.cummin())
ax[2].set_title('best fitness of every generation')
plt.show()

示例#30
0

#%%
def objectfunction(p):
    x1, x2, x3 = p
    res = [0 for i in range(len(t))]
    for i in range(len(t)):
        res[i] = CoolingTower(t[i], h[i], waterin[i], flow[i], hz[i],
                              waterout[i], x1, x2, x3)
    return sum(res)


#%%
time_start = time.time()
ga = GA(func=objectfunction,
        n_dim=3,
        size_pop=100,
        max_iter=1000,
        lb=[-10, -10, -10],
        ub=[10, 10, 10],
        precision=1e-7)
best_x, best_y = ga.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)
time_end = time.time()
print('time cost of GA', time_end - time_start, 's', '-' * 70)

Y_history = pd.DataFrame(ga.all_history_Y)
fig, ax = plt.subplots(2, 1)
ax[0].plot(Y_history.index, Y_history.values, '.', color='red')
Y_history.min(axis=1).cummin().plot(kind='line')
plt.show()