예제 #1
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)
예제 #2
0
파일: ex波动率.py 프로젝트: dxcv/pyfcim
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
예제 #3
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)
    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
예제 #5
0
    def test_mutate(self):
        ''' Make sure the individual can be mutated correctly.
        '''
        indv_template = BinaryIndividual(ranges=[(0, 10)], eps=0.001)
        population = Population(indv_template=indv_template, size=50).init()

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

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

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

        mutation.mutate(indv_template, engine)
예제 #6
0
from math import sin
from gaft import GAEngine
from gaft.components import BinaryIndividual, Population
from gaft.operators import RouletteWheelSelection, UniformCrossover, FlipBitMutation
from gaft.analysis import ConsoleOutput

# Analysis plugin base class.
from gaft.plugin_interfaces.analysis import OnTheFlyAnalysis

indv_template = BinaryIndividual(ranges=[(0, 15)], eps=0.001)
population = Population(indv_template=indv_template, size=50)
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.1)

engine = GAEngine(population=population,
                  selection=selection,
                  crossover=crossover,
                  mutation=mutation,
                  analysis=[ConsoleOutput])


@engine.fitness_register
def fitness(indv):
    x, = indv.solution
    return (-3) * (x - 30)**2 * sin(x)

from gaft.components import BinaryIndividual  # 二元个体
from gaft.operators import RouletteWheelSelection  # 轮盘选择
from gaft.analysis.console_output import ConsoleOutput  # 输出


# 定义编码
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)
예제 #8
0
from math import sin, cos

# Funkcja Belea
# Oczekiwana wartosc f(3,0.5) =0

# Function boundaries
XB = (-5, 5)
YB = (-5, 5)
# Decrete precision of binary sequence
EPS = 0.0001

# Population size
POPULATION_SIZE = 200

# Selection method
SELECTION = RouletteWheelSelection()

# Crossover method
# pc: probability of crossover (0,1)
PC = 0.8
# pe: probability of gene exchange (0,1)
PE = 0.5

# Mutation
# pm: probability of mutation (0, 1)
PM = 0.05
# pbm: probability of big mutation (5 times bigger than pbm)
PBM = PM * 5
# alpha: intensive factor (0.5, 1)
ALPHA = 0.6