示例#1
0
def ga(df, start, end, _positionList, ranges=[(20,100),(0.01, 1),(0.01, 1),(0.01, 1),(1, 5)], eps=0.01):
    indv_template = BinaryIndividual(ranges=ranges, eps=eps)
    population = Population(indv_template=indv_template, size=100)
    population.init()  # Initialize population with individuals.
    # Use built-in operators here.
    selection = RouletteWheelSelection()
    crossover = UniformCrossover(pc=0.8, pe=0.5)
    mutation = FlipBitMutation(pm=0.3)
    engine = GAEngine(population=population, selection=selection,
                      crossover=crossover, mutation=mutation,
                      analysis=[FitnessStore])

    @engine.fitness_register
    def fitness(indv):
        n, upper, lower, adds, cutoff = indv.solution
        df['KAMA'] = talib.KAMA(df.close, int(n))
        df['VAR'] = talib.VAR(df.close-df.KAMA.shift(1) - df.close.shift(1)+df.KAMA.shift(2),10)
        profitsList, buypriceList, sellpriceList, fits,positionList = profitsCal(df, start, end, _positionList, upper=upper, lower=lower, adds = adds, cutoff=cutoff)
        return float(fits)

    @engine.analysis_register
    class ConsoleOutput(OnTheFlyAnalysis):
        master_only = True
        interval = 1
        def register_step(self, g, population, engine):
            best_indv = population.best_indv(engine.fitness)
            msg = 'Generation: {}, best fitness: {:.3f}'.format(g, engine.fmax)
            print(best_indv.solution)
            engine.logger.info(msg)
    engine.run(ng=30)

    return population.best_indv(engine.fitness).solution, _positionList
示例#2
0
def tain_svm():
    indv_template = BinaryIndividual(ranges=[(-8, 8), (-8, 8), (-8, 8)],
                                     eps=[0.001, 0.001, 0.001])
    population = Population(indv_template=indv_template, size=1000)
    population.init()  # Initialize population with individuals.

    # In[ ]:

    selection = RouletteWheelSelection()
    crossover = UniformCrossover(pc=0.8, pe=0.5)
    # mutation = FlipBitMutation(pm=0.1)
    mutation = FlipBitBigMutation(pm=0.1, pbm=0.55, alpha=0.6)

    engine = GAEngine(population=population,
                      selection=selection,
                      crossover=crossover,
                      mutation=mutation,
                      analysis=[ConsoleOutput, FitnessStore])
    #############################################################
    indv = engine.population.best_indv(engine.fitness).variants
    c, e, g = indv.variants[1], indv.variants[2], indv.variants[-1]
    clf = svm.svR(C=c, epsilon=e, gamma=g, kernel='rbf')

    data_x, data_y = preprocess_pca()
    clf.fit(data_x, data_y)
    predictval = clf.predict(data_x)
    reaval = data_y
    print(predictval)

    # In[ ]:

    engine.run(ng=100)
示例#3
0
    def test_run(self):
        '''
        Make sure GA engine can run correctly.
        '''
        indv_template = GAIndividual(ranges=[(0, 10)],
                                     encoding='binary',
                                     eps=0.001)
        population = GAPopulation(indv_template=indv_template, size=50).init()

        # Create genetic operators.
        selection = RouletteWheelSelection()
        crossover = UniformCrossover(pc=0.8, pe=0.5)
        mutation = FlipBitMutation(pm=0.1)

        # Create genetic algorithm engine.
        engine = GAEngine(population=population,
                          selection=selection,
                          crossover=crossover,
                          mutation=mutation)

        @engine.fitness_register
        def fitness(indv):
            x, = indv.variants
            return x + 10 * sin(5 * x) + 7 * cos(4 * x)

        engine.run(50)
示例#4
0
class pyGaft(Optimizer):
    def __init__(self, objfunc, var_bounds, individual_size, max_iter,
                 max_or_min, **kwargs):
        super().__init__(objfunc)
        self.max_iter = max_iter

        # 定义个体 / 种群
        self.individual = BinaryIndividual(ranges=var_bounds, eps=0.001)
        self.population = Population(indv_template=self.individual,
                                     size=individual_size).init()

        # Create genetic operators.
        # selection = RouletteWheelSelection()
        selection = TournamentSelection()
        crossover = UniformCrossover(pc=0.8, pe=0.5)
        mutation = FlipBitBigMutation(pm=0.1, pbm=0.55, alpha=0.6)

        self.engine = GAEngine(population=self.population,
                               selection=selection,
                               crossover=crossover,
                               mutation=mutation,
                               analysis=[FitnessStore])

        @self.engine.fitness_register
        def fitness(indv):
            """
            适应度函数: 注意这里默认为优化得到最小值
            :param indv:
            :return:
            """
            x = indv.solution

            if max_or_min == 'max':
                return objfunc(x, **kwargs)
            else:
                return -objfunc(x, **kwargs)

        @self.engine.analysis_register
        class ConsoleOutputAnalysis(OnTheFlyAnalysis):
            interval = 1
            master_only = True

            def register_step(self, g, population, engine):
                best_indv = population.best_indv(engine.fitness)
                msg = 'Generation: {}, best fitness: {:.3f}'.format(
                    g, engine.fitness(best_indv))
                # self.logger.info(msg)

            def finalize(self, population, engine):
                best_indv = population.best_indv(engine.fitness)
                x = best_indv.solution
                y = engine.fitness(best_indv)
                msg = 'Optimal solution: ({}, {})'.format(x, y)
                # self.logger.info(msg)

    def run(self):
        self.engine.run(ng=self.max_iter)
    def generate(self):
        
        best_policy = None
        best_reward = -float('Inf')
        candidates = []
        eps = 1 # equal to actions space resolution, eps is step size
        pop_size = 4
        cross_prob = 1
        exchange_prob = 1
        mutation_pob = 1
        generation = 4
        tmp_reward = []
        tmp_policy = []
        random.seed(54)
        turb = 5
        
        try:
            # Agents should make use of 20 episodes in each training run, if making sequential decisions

            # Define population
            indv_template = DecimalIndividual(ranges=[(0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1),(0, 1), (0, 1)], eps=eps)
            population = Population(indv_template=indv_template, size = pop_size)
            population.init()  # Initialize population with individuals.

            # Create genetic operators
            # Use built-in operators here.
            selection = RouletteWheelSelection()
            crossover = UniformCrossover(pc=cross_prob, pe=exchange_prob) # PE = Gene exchange probability
            mutation = FlipBitMutation(pm=mutation_pob) # 0.1 todo The probability of mutation

            # Create genetic algorithm engine to run optimization
            engine = GAEngine(population=population, selection=selection,
                            crossover=crossover, mutation=mutation,)

            # Define and register fitness function
            @engine.fitness_register
            def fitness(indv):
                p = [0 for _ in range(10)]
                p = indv.solution
                policy = {'1': [p[0], p[1]], '2': [p[2], p[3]], '3': [p[4], p[5]], '4': [p[6], p[7]], '5': [p[8], p[9]]}xw
                reward = self.environment.evaluatePolicy(policy) # Action in Year 1 only
                print('Sequential Result : ', reward)
                tmp_reward.append(reward)
                tmp_policy.append(policy)
                tmp_single = []
                return reward + uniform(-turb, turb)
            
            # run
            engine.run(ng = generation)
            best_reward = max(tmp_reward)
            best_policy = tmp_policy[-pop_size]
        
        except (KeyboardInterrupt, SystemExit):
            print(exc_info())
        
        return best_policy, best_reward
示例#6
0
def doga(units, ploads, hload, size=50, ng=5, pc=0.8, pe=0.5, pm=0.1):
    # 计算不同典型日下,最小运行成本均值
    def calcost(indv):
        # 输入改造方案
        for chpunit, rtype in zip(chpunits, indv):
            chpunit.rtype = rtype
        meancost = 0
        # ploads为字典,key:典型日出现的概率,value:[典型日负荷曲线,风电出力极限曲线1,...,风电出力极限曲线n]
        for p in ploads.keys():
            x = ProSimu()
            x.pload = ploads[p][0]
            x.hload = hload
            wn = 0
            for wpunit in wpunits:
                wn += 1
                wpunit.maxwp = ploads[p][wn]
            x.units = units
            meancost += x.getoptvalue()*p
        return meancost

    ranges = list()
    wpunits = list()
    chpunits = list()
    for unit in units:
        if unit.ptype == 0:  # Wind Power Unit
            wpunits += [unit]
        elif unit.ptype == 2:  # CHP Unit-1
            ranges += [(0, 4)]
            chpunits += [unit]
        elif unit.ptype == 3:  # CHP Unit-2
            ranges += [(0, 3)]
            chpunits += [unit]
    template = BinaryIndividual(ranges, eps=1)
    population = Population(indv_template=template, size=size).init()
    selection = TournamentSelection()
    crossover = UniformCrossover(pc=pc, pe=pe)
    mutation = FlipBitMutation(pm=pm)
    engine = GAEngine(population=population, selection=selection, crossover=crossover, mutation=mutation,
                      analysis=[ConsoleOutput, FitnessStore])

    @engine.fitness_register
    @engine.minimize
    def fitness(indv):
        # print(type(float(calcost(indv.solution))))
        return float(calcost(indv.solution))

    engine.run(ng=ng)

    bestindv = population.best_indv(engine.fitness).solution
    for unitt, rtype in zip(chpunits, bestindv):
        unitt.rtype = rtype
    result = calcost(bestindv)
    print('Best individual:', bestindv)
    print('Optimal result:', result)
示例#7
0
    def tune_weights(self):
        old_fitness = self.individual.fitness

        weights_scaling = self.individual.get_subtree_scaling()
        weights_translation = self.individual.get_subtree_translation()
        # Create array with range for each scaling and translation parameter
        range = [
            self.scale_range,
        ] * len(weights_scaling) + [
            self.translation_range,
        ] * len(weights_translation)
        indv_template = DecimalIndividual(ranges=range, eps=0.1)
        population = Population(indv_template=indv_template,
                                size=self.pop_size)
        population.init()

        engine = GAEngine(
            population=population,
            selection=TournamentSelection(),
            crossover=GaussianCrossover(pc=1.0),
            mutation=NoMutation(),
            fitness=self.fitness_function_GAFT,
            analysis=[
                new_early_stopping_analysis(scale_range=self.scale_range)
            ])

        engine.logger = NoLoggingLogger()

        # Run the GA with the specified number of iterations
        try:
            engine.run(ng=self.max_iterations)
        except ValueError:
            pass

        # Get the best individual.
        best_indv = engine.population.best_indv(engine.fitness)

        # Log the tuning process
        print(
            f"Tuner {np.round(old_fitness, 3)} {np.round(-engine.ori_fmax, 3)}"
        )

        # Only use the new individual if it was really improved
        if old_fitness > -engine.ori_fmax:
            weights_scaling, weights_translation = self.split_list(
                best_indv.solution)

            self.individual.set_subtree_scaling(weights_scaling)
            self.individual.set_subtree_translation(weights_translation)
            self.individual.fitness = -engine.ori_fmax

        return deepcopy(self.individual)
示例#8
0
selection = ExponentialRankingSelection()
crossover = UniformCrossover(pc=0.5, pe=0.5)
mutation = FlipBitMutation(pm=0.5)

engine = GAEngine(population=population,
                  selection=selection,
                  crossover=crossover,
                  mutation=mutation)


@engine.fitness_register
@engine.minimize
def fitness(indv):
    ObjectF = 1
    Constraint = 0
    for i in indv.solution:
        ObjectF *= i
        Constraint += 1 / i**2
    return ObjectF + M1(indv.solution) * (Constraint - (
        (-b + ma.sqrt(b**2 + 8 * a * epsilon))**2) / (2 * a))


def Generate_noise(sigma):
    mu_vector = np.zeros([1, n])
    covariance = np.diag(sigma)
    return np.random.multivariate_normal(mu_vector, covariance)


if '__main__' == __name__:
    engine.run(ng=150)
示例#9
0
                  mutation=mutation,
                  analysis=[ConsoleOutput, FitnessStore])

# 加载数据
dataset, labels = load_data('testSet.txt')


@engine.fitness_register
def fitness(indv):
    w, b = indv.variants[:-1], indv.variants[-1]
    min_dis = min([y * (np.dot(w, x) + b) for x, y in zip(dataset, labels)])
    return float(min_dis)


if '__main__' == __name__:
    engine.run(300)

    variants = engine.population.best_indv(engine.fitness).variants
    w = variants[:-1]
    b = variants[-1]

    # 分类数据点
    classified_pts = {'+1': [], '-1': []}
    for point, label in zip(dataset, labels):
        if label == 1.0:
            classified_pts['+1'].append(point)
        else:
            classified_pts['-1'].append(point)

    fig = plt.figure()
    ax = fig.add_subplot(111)
示例#10
0
                  crossover=crossover, mutation=mutation,
                  analysis=[FitnessStore])

# Define fitness function.
@engine.fitness_register
def fitness(indv):
    x, = indv.solution
    return x + 10*sin(5*x) + 7*cos(4*x)

# Define on-the-fly analysis.
@engine.analysis_register
class ConsoleOutputAnalysis(OnTheFlyAnalysis):
    interval = 1
    master_only = True

    def register_step(self, g, population, engine):
        best_indv = population.best_indv(engine.fitness)
        msg = 'Generation: {}, best fitness: {:.3f}'.format(g, engine.ori_fmax)
        self.logger.info(msg)

    def finalize(self, population, engine):
        best_indv = population.best_indv(engine.fitness)
        x = best_indv.solution
        y = engine.ori_fmax
        msg = 'Optimal solution: ({}, {})'.format(x, y)
        self.logger.info(msg)

if '__main__' == __name__:
    # Run the GA engine.
    engine.run(ng=100)
                  selection=selection,
                  crossover=crossover,
                  mutation=mutation,
                  analysis=[ConsoleOutput, FitnessStore])


# Define fitness function.
@engine.fitness_register
def fitness(indv):
    x1, x2 = indv.solution
    formula = 21.5 + x1 * sin(4 * pi * x1) + x2 * sin(20 * pi * x2)
    return formula


# Best Fitness values are export to best_fit.py
engine.run(ng=generation)

import matplotlib.pyplot as plt
from best_avg_fit import best_avg_fit

steps, variants, fits, avgfits = list(zip(*best_avg_fit))
best_step, best_v, best_f, avg_f = steps[-1], variants[-1], fits[-1], avgfits[
    -1]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(steps, fits, label="Best_so_far")
ax.plot(steps, avgfits, label="Average Fitness")
ax.set_xlabel('Generation')
ax.set_ylabel('Fitness')
ax.legend(loc='lower right')
        tmp_policy.append(policy)
        print('Policy : ', policy)
        print(policy_450,'**************************good solution***************')
        #print(policy_bad,'**************************bad solution***************')


        return reward + uniform(-turb, turb)

    @engine.analysis_register
    class ConsoleOutput(OnTheFlyAnalysis):
        master_only = True
        interval = 1
        def register_step(self, g, population, engine):
            
            best_indv = population.best_indv(engine.fitness)
            msg = 'Generation: {}, best fitness: {:.3f}'.format(g + 1, engine.fmax)
            #best_reward = max(tmp_reward[g + pop_size * (generation - 1): g + pop_size * generation])
            #print(pop_size * (g - 0), pop_size * (g + 1),'&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
            REWARDS.append(max(reward_generation[pop_size * (g - 0): pop_size * (g + 1)]))
            #best_policy = POLICY[tmp_reward.index(best_reward)]
            #POLICY.append(best_policy)
            engine.logger.info(msg)
    
    engine.run(ng = generation, good_p = good_p, bad_p = bad_p)
    print(policy_450)
    x = list(range(len(tmp_reward)))
    plt.plot(x, tmp_reward)
    plt.title(f'Sequential Rewards')
    #plt.savefig(f'./res_geneticAlgorithm/Sequential_Rewards_eps:{eps}_popsize:{pop_size}_generation:{generation}_mutation_pob:{mutation_pob}_exchange_prob:{exchange_prob}_cross_prob:{cross_prob}.jpg')
    plt.show()
示例#13
0
            model_labels_ = model_labels.reshape(11, 25, 36, order='A')
        elif CASE.upper() == 'SEL':
            model_labels_ = model_labels.reshape(11, 13, 12, order='A')

        perf_vector = utils.get_projection_errors(true_labels=true_labels,
                                                  pred_labels=model_labels_)
        # print("perf = " + str(float(np.mean(perf_vector))))
        return float(np.mean(perf_vector))

    @engine.analysis_register
    class ConsoleOutput(OnTheFlyAnalysis):
        master_only = True
        interval = 1

        def register_step(self, g, population, engine):
            best_indv = population.best_indv(engine.fitness)
            msg = 'Generation: {}, best fitness: {:.3f}, weights: {}'.format(
                g, engine.fmax, best_indv.decode())
            engine.logger.info(msg)

    if config.VERBOSE:
        print('\n\n[+] Executing a genetic algorithm with parameters :')
        print(f'\t\tPop. size : {POPULATION_SIZE}')
        print(f'\t\tNumber of generations : {NB_GENERATIONS}')
        print(f'\t\tSelection : Roulette Wheel')
        print(f'\t\tCrossover probability : {CROSSOVER_PROBABILITY}')
        print(f'\t\tGenome exchange probability : {GE_PROBABILITY}')
        print(f'\t\tMutation probability : {MUTATION_PROBABILITY}')

    engine.run(ng=NB_GENERATIONS)
示例#14
0
indv_template = BinaryIndividual(ranges=[XB, YB], eps=EPS)
population = Population(indv_template=indv_template,
                        size=POPULATION_SIZE).init()

# Create genetic operators.
selection = SELECTION
crossover = UniformCrossover(pc=PC, pe=PE)
mutation = FlipBitBigMutation(pm=PM, pbm=PBM, alpha=ALPHA)

# Create genetic algorithm engine.
# Here we pass all built-in analysis to engine constructor.
engine = GAEngine(population=population,
                  selection=selection,
                  crossover=crossover,
                  mutation=mutation,
                  analysis=[ConsoleOutput, FitnessStore])


# Define fitness function.
@engine.fitness_register
@engine.minimize
def fitness(indv):
    x, y = indv.solution
    return (1.5 - x + x * y) * (1.5 - x + x * y) + (2.25 - x + x * y * y) * (
        2.25 - x + x * y * y) + (2.625 - x + x * y * y * y) * (2.625 - x +
                                                               x * y * y * y)


engine.run(ng=NG)
示例#15
0
def generate():
    
    import random
    good_seed = int(sys.argv[1])
    print('currrrrrrrrrrrrrrrrrrrrrrrrrrrrr', good_seed)
    envSeqDec = ChallengeProveEnvironment() # Initialise a New Challenge Environment to post entire policy
    #env = ChallengeEnvironment(experimentCount = 20000)
    eps = 0.1 # equal to actions space resolution # range/eps
    pop_size = 4
    cross_prob = 0.6
    exchange_prob = 0.7
    mutation_pob = 0.8
    generation = 4
    REWARDS = []
    NEW = []
    POLICY = []
    tmp_reward = []
    tmp_policy = []
    policy_450 = []
    reward_generation = []
    time = []
    random.seed(good_seed)
    # best_action = ([0], [0.8, 1])
    
    turb = 0
    test_action = ([[i/10 for i in range(0, 11)],[i/10 for i in range(0,11)]])
    # test_action = ([0, 0.1, 0.2, 0.3, 0.4, 0.5], [0.6, 0.7, 0.8, 0.9, 1])
    
    # 2. Define population
    indv_template = OrderIndividual(ranges=[(0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1)], eps=eps, actions = test_action) # low_bit and high_bit
    population = Population(indv_template=indv_template, size = pop_size)
    population.init()  # Initialize population with individuals.

    # 3. Create genetic operators

    # Use built-in operators here.
    #selection = RouletteWheelSelection()
    selection = TournamentSelection()

    crossover = UniformCrossover(pc=cross_prob, pe=exchange_prob) # PE = Gene exchange probability
    mutation = FlipBitMutation(pm=mutation_pob) # 0.1 todo The probability of mutation

    # 4. Create genetic algorithm engine to run optimization

    engine = GAEngine(population=population, selection=selection,
                    crossover=crossover, mutation=mutation,)
                    # analysis=[FitnessStore])
        
        
    # 5. Define and register fitness function   
    @engine.fitness_register
    #@engine.dynamic_linear_scaling(target='max', ksi0=2, r=0.9)

    def fitness(indv):
        p = [0 for _ in range(10)]
        p = indv.solution
        # encode
        policy = {'1': [p[0], p[1]], '2': [p[2], p[3]], '3': [p[4], p[5]], '4': [p[6], p[7]], '5': [p[8], p[9]]}
        reward = envSeqDec.evaluatePolicy(policy) # Action in Year 1 only
        #print('Sequential Result : ', reward)
        
    
        tmp_reward.append(reward)
        reward_generation.append(reward)
        tmp_policy.append(policy)
        #print('Policy : ', policy)
        #print(policy_450,'**************************good solution***************')
        #print(policy_bad,'**************************bad solution***************')


        return reward + uniform(-turb, turb)

    @engine.analysis_register
    class ConsoleOutput(OnTheFlyAnalysis):
        master_only = True
        interval = 1
        def register_step(self, g, population, engine):
            
            best_indv = population.best_indv(engine.fitness)
            msg = 'Generation: {}, best fitness: {:.3f}'.format(g + 1, engine.fmax)
            #best_reward = max(tmp_reward[g + pop_size * (generation - 1): g + pop_size * generation])
            #print(pop_size * (g - 0), pop_size * (g + 1),'&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
            REWARDS.append(max(reward_generation[pop_size * (g - 0): pop_size * (g + 1)]))
            #best_policy = POLICY[tmp_reward.index(best_reward)]
            #POLICY.append(best_policy)
            engine.logger.info(msg)
        
    engine.run(ng = generation)
    # print(policy_450)
    x = list(range(len(REWARDS)))
    plt.plot(x, REWARDS)
    plt.title(f'Sequential Rewards {good_seed}')
    plt.savefig(f'./GA_trick/GA_seed_{good_seed}.jpg')
    # #plt.savefig(f'./res_geneticAlgorithm/Sequential_Rewards_eps:{eps}_popsize:{pop_size}_generation:{generation}_mutation_pob:{mutation_pob}_exchange_prob:{exchange_prob}_cross_prob:{cross_prob}.jpg')
    plt.show()
示例#16
0
                fitness += (-10 * (time - 1))
            else:
                fitness -= 10000
    for key in ovsCheck1:
        if ovsCheck1[key] > 5:
            fitness -= 10000
    for key in ovsCheck2:
        if ovsCheck2[key] > 5:
            fitness -= 10000
    print(fitness)
    return fitness

if '__main__' == __name__:
    sData = schedulesData[2]
    pData = aircraftsData[2]
    mEngine.run(ng=10)
    # variable_ranges = []
    # for i in range(0, 97):
    #     variable_ranges.append((0, 30))
    #     variable_ranges.append((0, 16))
    # length = len(variable_ranges)
    # res = []
    # for i in range(0, length):
    #     res.append(1)
    #     sData = schedulesData[2]
    #     pData = aircraftsData[2]
    #     flightRow = sData[i]
    #     planeName = str(flightRow[6]).strip().lower()
    #     i = 0
    #     for row in pData:
    #         if str(row[0]).strip().lower() == planeName:
示例#17
0
文件: svm_ga.py 项目: MoherX/MLBox
engine = GAEngine(population=population, selection=selection,
                  crossover=crossover, mutation=mutation,
                  analysis=[ConsoleOutput, FitnessStore])

# 加载数据
dataset, labels = load_data('testSet.txt')

@engine.fitness_register
def fitness(indv):
    w, b = indv.variants[: -1], indv.variants[-1]
    min_dis = min([y*(np.dot(w, x) + b) for x, y in zip(dataset, labels)])
    return float(min_dis)

if '__main__' == __name__:
    engine.run(300)

    variants = engine.population.best_indv(engine.fitness).variants
    w = variants[: -1]
    b = variants[-1]

    # 分类数据点
    classified_pts = {'+1': [], '-1': []}
    for point, label in zip(dataset, labels):
        if label == 1.0:
            classified_pts['+1'].append(point)
        else:
            classified_pts['-1'].append(point)

    fig = plt.figure()
    ax = fig.add_subplot(111)
示例#18
0
    layer_1 = convert(g_1)
    layer_2 = convert(g_2)
    layer_3 = convert(g_3)
    layer_4 = convert(g_4)
    layer_5 = convert(g_5)
    hyper_list = [1, layer_1, layer_2, layer_3, layer_4, layer_5]

    #TODO: Convert to [1,2,4,8], negative feedback: model size, flops
    FLOPS = (40.6 + layer_1 * 114.94 / 64.0 + layer_2 * 75.76 / 32.0 +
             layer_3 * 151.26 / 32.0 + layer_4 * 75.6 / 32 +
             layer_5 * 150.99 / 32) / 49.4
    k = 1.5
    print(hyper_list)
    accuracy = run(hyper_list)
    fit = accuracy - 0.5 * FLOPS

    print("Accuracy= ", accuracy, "FLOPS= ", FLOPS, "Fitness= ", fit)
    return fit


def convert(g):
    layer = 2**g
    return layer


if '__main__' == __name__:

    # print(indv_template)
    engine.run(ng=20)
示例#19
0
    ax.plot(geracoes, n_nines)
    plt.show()


if __name__ == "__main__":

    individuo = BinaryIndividual(ranges=[(-100, 100), (-100, 100)],
                                 eps=0.000001)
    populacao = Population(indv_template=individuo, size=100)
    populacao.init()

    selecao = TournamentSelection()
    crossover = UniformCrossover(pc=0.65, pe=0.65)
    mutacao = FlipBitMutation(pm=0.008)

    engine = GAEngine(population=populacao,
                      selection=selecao,
                      crossover=crossover,
                      mutation=mutacao,
                      analysis=[FitnessStore, ConsoleOutput])

    @engine.fitness_register
    def aptidao(ind):
        x, y = ind.solution
        return 0.5 - ((sin(sqrt(x**2 + y**2))**2 - 0.5) / (1 + 0.001 *
                                                           (x**2 + y**2))**2)

    engine.run(ng=40)

    plot_best_fit()
# 定义编码
individual_template = BinaryIndividual(ranges=[(0, 10)], eps=0.001)

# 定义种群
_population = Population(indv_template=individual_template, size=20)

# 种群初始化
_population.init()

# 遗传操作
selection = RouletteWheelSelection()  # 个体选择:轮盘赌
crossover = UniformCrossover(pc=0.8, pe=0.5)  # 交叉算子:均匀交叉
mutation = FlipBitMutation(pm=0.1)  # 变异算子:翻转突变

# 遗传算法引擎
_engine = GAEngine(population=_population, selection=selection,
                   crossover=crossover, mutation=mutation, analysis=[ConsoleOutput])


# 适应度:目标
@_engine.fitness_register
# @_engine.minimize
def fitness(individual):
    x, = individual.solution
    return 0.01 * x + 10 * math.sin(5 * x) + 7 * math.cos(4 * x)


if __name__ == '__main__':
    _engine.run(ng=10)
示例#21
0
        best_indv = population.best_indv(gen_algo.fitness)
        msg = 'Generacija: {}, best fitness: {:.3f}'.format(generacija, gen_algo.fmax)
        gen_algo.logger.info(msg)

for generacija in range(individual_template):
                trenutna_generacija = generacija

                if mpi.is_master:
                    best_indv = population.best_indv(fitness)
                else:
                    best_indv = None
                best_indv = mpi.bcast(best_indv)
                local_indvs = []
                local_size = mpi.split_size(population.size // 2)

                
                for _ in range(local_size):
                   
                   roditelji = self.selection.select(population, fitness=fitness)
                   djeca = crossover.cross(*roditelji)
                   dijete= [mtation.mutation(dijete) for dijete in djeca]
                   local_indvs.extend(djeca)

                indvs = mpi.merge_seq(local_indvs)
                indvs[0] = best_indv
                population.individuals = indvs


if '__main__' == __name__:
    gen_algo.run(ng=100):
示例#22
0
    def generate(self):

        import random
        eps = 0.2  # equal to actions space resolution # range/eps
        pop_size = 2
        cross_prob = 0.6
        exchange_prob = 0.7
        mutation_pob = 0.8
        generation = 6
        REWARDS = []
        tmp_reward = []
        tmp_policy = []
        bad_p = []
        good_p = []
        turb = 0

        try:
            # Agents should make use of 20 episodes in each training run, if making sequential decisions
            first_action = []
            for a1 in [i / 10 for i in range(0, 11, 2)]:
                for a2 in [i / 10 for i in range(0, 11, 2)]:
                    first_action.append([a1, a2])

            # [0,0] is absolutely bad action
            first_action = first_action[1:]

            action_reward = []
            for i in range(len(first_action)):
                ar = self.environment.evaluateAction(first_action[i])
                self.environment.reset()
                action_reward.append(ar[1])

            # get the best policy for first year
            best_action = first_action[action_reward.index(max(action_reward))]
            test_action = ([[i / 10 for i in range(0, 11, 2)],
                            [i / 10 for i in range(0, 11, 2)]])

            # 2. Define population
            indv_template = OrderIndividual(
                ranges=[(0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1),
                        (0, 1), (0, 1), (0, 1)],
                eps=eps,
                actions=test_action,
                best_1=best_action)  # low_bit and high_bit
            population = Population(indv_template=indv_template, size=pop_size)
            population.init()  # Initialize population with individuals.

            # 3. Create genetic operators

            # Use built-in operators here.
            selection = LinearRankingSelection()

            crossover = UniformCrossover(
                pc=cross_prob,
                pe=exchange_prob)  # PE = Gene exchange probability
            mutation = FlipBitMutation(
                pm=mutation_pob)  # 0.1 todo The probability of mutation

            # 4. Create genetic algorithm engine to run optimization
            engine = GAEngine(population=population,
                              selection=selection,
                              crossover=crossover,
                              mutation=mutation)

            # 5. Define and register fitness function
            @engine.fitness_register
            def fitness(indv):
                p = [0 for _ in range(10)]
                p = indv.solution
                # encode
                policy = {
                    '1': [p[0], p[1]],
                    '2': [p[2], p[3]],
                    '3': [p[4], p[5]],
                    '4': [p[6], p[7]],
                    '5': [p[8], p[9]]
                }
                reward = self.environment.evaluatePolicy(policy)
                tmp_reward.append(reward)
                tmp_policy.append(policy)
                return reward + uniform(-turb, turb)

            @engine.analysis_register
            class ConsoleOutput(OnTheFlyAnalysis):
                master_only = True
                interval = 1

                def register_step(self, g, population, engine):
                    best_indv = population.best_indv(engine.fitness)
                    msg = 'Generation: {}, best fitness: {:.3f}'.format(
                        g + 1, engine.fmax)
                    REWARDS.append(
                        max(tmp_reward[pop_size * (g - 0):pop_size * (g + 1)]))
                    engine.logger.info(msg)

            engine.run(ng=generation)
            best_reward = max(tmp_reward)
            best_policy = tmp_policy[-pop_size]

        except (KeyboardInterrupt, SystemExit):
            print(exc_info())

        return best_policy, best_reward
        def register_step(self, g, population, engine):
            best_indv = population.best_indv(engine.fitness)
            f = engine.fitness(best_indv)
            msg = 'Generation: {}, best fitness: {}'.format(g, f)
            self.logger.info(msg)

        def finalize(self, population, engine):
            best_indv = population.best_indv(engine.fitness)
            x = best_indv.variants
            y = engine.fitness(best_indv)
            msg = 'Optimal solution: ({}, {})'.format(x, y)
            self.logger.info(msg)

    startt=time.time()
    engine.run(ng=numEpoch)
    endt=time.time()
    print('Runing cost time:',(endt-startt)//60,'min',(endt-startt),'s')

    best_indv = population.best_indv(engine.fitness)
    x_decode = best_indv.chromsome
    best_state=decode_sequence(x_decode)
    best_power=power_by_mtt_fastgraph(best_state,graph)
    print('best state:',best_state)
    print('best power:',best_power)

    write_output(best_state, outputpath, filename)



示例#24
0
if '__main__' == __name__:
    # Open the Hysys Model
    hyApp = win32.Dispatch("HYSYS.Application")
    hyApp.Visible = True
    hySimulationCase = hyApp.ActiveDocument

    fig = plt.figure(figsize=(16, 9))
    ax = fig.add_subplot(111, projection='3d')

    ax.set_xlabel('THF_PURITY_SPEC')
    ax.set_ylabel('TOLUENE_PURITY_SPEC')
    ax.set_zlabel('Profit')
    #ax.set_title('')

    #plt.ion()
    #plt.show()

    # Run Genetic Algorithm
    ga_best = engine.run(ng=str_ng)

    #ax.scatter(ga_best[0][0], ga_best[0][1], ga_best[1], c='r', marker='^', s=160, edgecolor='0.3',alpha=0.2)
    ax.scatter(ga_best[0][0],
               ga_best[0][1],
               ga_best[1],
               c='r',
               marker='^',
               s=160)

    plt.savefig('C:/ZY/03Output/Profit.png')

    print(ga_best)
示例#25
0
    @engine2.minimize
    def fitness2(indv):
        x, = indv.solution
        return func2(x)

    @engine1.fitness_register
    @engine1.minimize
    def fitness1(indv):
        x, = indv.solution
        return -func1(x)

    fitnessFunc1 = fitness1
    fitnessFunc2 = fitness2

    # Run the engine 1
    engine1.run(ng=50)
    # Run the engine 2
    engine2.run(ng=50)

    # After engine running, we can do something more...
    # Get the best individual
    best_indv = engine1.population.best_indv(engine1.fitness)
    # Get the solution
    print("========================")
    print("Function for Alex:")
    print("========================")
    print("t = ", best_indv.solution)
    # And the fitness value
    print("F(t) = ", fitnessFunc1(best_indv))

    best_indv = engine2.population.best_indv(engine2.fitness)
示例#26
0
def eval_nn_performance(node_per_layer, num_layer):
    node_per_layer = int(np.round(node_per_layer))
    num_layer = int(np.round(num_layer))
    f = open("./depth_cmd.txt", "a")
    f.write('python run_GA.py %d %d\n' % (node_per_layer, num_layer))
    start_time = datetime.now()
    value = main_fun(num_try=1,
                     width=node_per_layer,
                     depth=num_layer,
                     iter_num=50000,
                     learning_rate=5.0e-4)
    end_time = datetime.now()
    m, s = divmod((end_time - start_time).total_seconds(), 60)
    print(
        'node_per_layer = %d, | num_layer = %d | value = %f | time = %dm%ds' %
        (node_per_layer, num_layer, -float(value), m, s))
    return value, (end_time - start_time)


# Define fitness function.
@engine.fitness_register
def fitness(indv):
    node_per_layer = 10
    num_layer = indv.solution
    value, _ = eval_nn_performance(node_per_layer, num_layer)
    return -value


if __name__ == "__main__":
    engine.run(ng=4)
示例#27
0
class optimize_ga:
    def __init__(self ,k ,total_implied_variance ,slice_before ,slice_after ,tau):
        self.k =k
        self.total_implied_variance =total_implied_variance
        self.slice_before =slice_before
        self.slice_after = slice_after
        self.tau = tau

        # Define population.
        indv_template = BinaryIndividual(ranges=[(1e-5, 20),(1e-5, 20),(1e-5, 20)], eps=0.001)
        self.population = Population(indv_template=indv_template, size=30).init()

        # Create genetic operators.
        selection = TournamentSelection()
        crossover = UniformCrossover(pc=0.8, pe=0.5)
        mutation = FlipBitMutation(pm=0.1)

        # Create genetic algorithm engine.
        self.engine = GAEngine(population=self.population, selection=selection,
                               crossover=crossover, mutation=mutation,
                               analysis=[FitnessStore])

        # Define fitness function.
        @self.engine.fitness_register
        @self.engine.minimize
        def fitness(indv):
            a, b, m, rho, sigma = indv.solution

            model_total_implied_variance=svi_raw(self.k,np.array([a, b, m, rho, sigma]),self.tau)
            value = norm(self.total_implied_variance - model_total_implied_variance,ord=2)

            # if bool(len(self.slice_before)) and np.array(model_total_implied_variance < self.slice_before).any():
            #     value +=(np.count_nonzero(~np.array(model_total_implied_variance < self.slice_before))*100)
            #     # value = 1e6
            #
            # if bool(len(self.slice_after)) and np.array(model_total_implied_variance > self.slice_after).any():
            #     value += float(np.count_nonzero(~np.array(model_total_implied_variance > self.slice_after)) * 100)
            #     # value = 1e6
            # if np.isnan(value):
            #     value = 1e6

            value = float(value)
            return value


    # Define on-the-fly analysis.
    #     @self.engine.analysis_register
    #     class ConsoleOutputAnalysis(OnTheFlyAnalysis):
    #         interval = 1
    #         master_only = True
    #
    #         def register_step(self, g, population, engine):
    #             best_indv = population.best_indv(engine.fitness)
    #             msg = 'Generation: {}, best fitness: {:.3f}'.format(g, engine.ori_fmax)
    #             self.logger.info(msg)
    #
    #         def finalize(self, population, engine):
    #             best_indv = population.best_indv(engine.fitness)
    #             x = best_indv.solution
    #             y = engine.ori_fmax
    #             msg = 'Optimal solution: ({}, {})'.format(x, y)
    #             self.logger.info(msg)
    def optimize(self):
        self.engine.run(ng=500)
        return self.population.best_indv(self.engine.fitness).solution
示例#28
0
文件: main.py 项目: AlexDreaming/Utah
    node_per_layer, num_layer = indv.solution
    value = -eval_NN_performance(node_per_layer, num_layer, data, max_train_iter)
    return value


@engine.analysis_register
class ConsoleOutputAnalysis(OnTheFlyAnalysis):

    interval = 1
    master_only = True
    
    def register_step(self, g, population, engine):
        best_indv = population.best_indv(engine.fitness)
        print('\033[0;31mGeneration: {}\033[0m'.format(g+1))
        print('-' * 100)

    def finalize(self, population, engine):
        best_indv = population.best_indv(engine.fitness)
        x = best_indv.solution
        y = engine.ori_fmax
        print('\033[0;31Optimal solution: (node_per_layer:{}, num_layer:{}, value:{})\033[0m'.format(x[0], x[1], y))


if '__main__' == __name__:
    start = datetime.now()
    engine.run(ng=5)
    end = datetime.now()
    h, temp = divmod((end - start).total_seconds(), 3600)
    m, s = divmod(temp, 60)
    print('\033[0;31mTotal Time: %dh%dm%ds\033[0m' % (h, m, s))
示例#29
0
    def register_step(self, g, population, engine):
        best_indv = population.best_indv(engine.fitness)
        msg = 'Generation: {}, best fitness: {:.3f}'.format(g, engine.ori_fmax)
        self.logger.info(msg)

    def finalize(self, population, engine):
        best_indv = population.best_indv(engine.fitness)
        x = best_indv.solution
        y = engine.ori_fmax
        msg = 'Optimal solution: ({}, {})'.format(x, y)
        self.logger.info(msg)


if '__main__' == __name__:
    # Run the GA engine and print every generation
    engine.run(ng=500)
    best_indv = engine.population.best_indv(engine.fitness)
    print('Max({0},{1})'.format(best_indv.solution[0],
                                engine.fitness(best_indv)))
    x = np.linspace(0, 15, 10000)
    y = [-3 * (i - 30)**2 * math.sin(i) for i in x]
    plt.plot(x, y)
    plt.xlabel('x')
    plt.ylabel('y')
    plt.title('function')
    plt.axis([-1, 16, -3000, 3000])
    plt.scatter(best_indv.solution[0], engine.fitness(best_indv), color='r')
    a = round(best_indv.solution[0], 4)
    b = round(engine.fitness(best_indv), 4)
    plt.annotate('Max(' + str(a) + ',' + str(b) + ')',
                 xy=(best_indv.solution[0], engine.fitness(best_indv)),