#2.1 遗传算法 Genetic Algorithm (进化算法教学教程 Tutorial) 我們來看一下莫凡老大的code在一個不知道答案的時候有沒有一種逼近或者最大效率的一種演算法來求得答案呢 在選擇策略的時候到底可以應用在哪,來做一下小筆記,那麼我的理解是

上次說要應用到決策方式,程式碼大概是說這樣

那大概就是說,

一組DNA可能

code
[000000000000]

產生下一代,將會做隨機分割,還有變異,隨機交配

隨機分割

---

code
[1000000/00000] [00000/0000001]

隨機交配

---

在基因序列李,盡量選擇得分最高也就是fitens最高的進行配對

這將會讓基因越來越棒,

code
[1000000000/00]
[0000000000/01]

也就是

code
[1000000000]
[01]

進行交配

最後交配完可能得到

code
[100000000001]

隨機變異

---

code
[1,0,0,0,0,0,0,0,[0/1],0,0,1]

那麼好的跟好的交配一定更好嗎?

不一定,或許變異後有機率產生更好的DNA也說不定

所以會有基因變異的東東,

交配完後,隨機在DNA裡面挑取一個基因片段進行變異

那麼應用方面應該就是他所周哥所說的fitens

那麼我們要怎樣定義什麼是好的基因呢?

假設產生下一代的話我們對陣列中的元素做計分的動作,

分數越高,就代表基因越優

code
"""
Visualize Microbial Genetic Algorithm to find the maximum point in a graph.
Visit my tutorial website for more: https://morvanzhou.github.io/tutorials/
"""
import numpy as np
import matplotlib.pyplot as plt

DNA_SIZE = 10            # DNA length
POP_SIZE = 20            # population size
CROSS_RATE = 0.6         # mating probability (DNA crossover)
MUTATION_RATE = 0.01     # mutation probability
N_GENERATIONS = 200
X_BOUND = [0, 5]         # x upper and lower bounds


def F(x): return np.sin(10*x)*x + np.cos(2*x)*x     # to find the maximum of this function


class MGA(object):
    def __init__(self, DNA_size, DNA_bound, cross_rate, mutation_rate, pop_size):
        self.DNA_size = DNA_size
        DNA_bound[1] += 1
        self.DNA_bound = DNA_bound
        self.cross_rate = cross_rate
        self.mutate_rate = mutation_rate
        self.pop_size = pop_size

        # initial DNAs for winner and loser
        self.pop = np.random.randint(*DNA_bound, size=(1, self.DNA_size)).repeat(pop_size, axis=0)

    def translateDNA(self, pop):
        # convert binary DNA to decimal and normalize it to a range(0, 5)
        return pop.dot(2 ** np.arange(self.DNA_size)[::-1]) / float(2 ** self.DNA_size - 1) * X_BOUND[1]

    def get_fitness(self, product):
        return product      # it is OK to use product value as fitness in here

    def crossover(self, loser_winner):      # crossover for loser
        cross_idx = np.empty((self.DNA_size,)).astype(np.bool)
        for i in range(self.DNA_size):
            cross_idx[i] = True if np.random.rand() < self.cross_rate else False  # crossover index
        loser_winner[0, cross_idx] = loser_winner[1, cross_idx]  # assign winners genes to loser
        return loser_winner

    def mutate(self, loser_winner):         # mutation for loser
        mutation_idx = np.empty((self.DNA_size,)).astype(np.bool)
        for i in range(self.DNA_size):
            mutation_idx[i] = True if np.random.rand() < self.mutate_rate else False  # mutation index
        # flip values in mutation points
        loser_winner[0, mutation_idx] = ~loser_winner[0, mutation_idx].astype(np.bool)
        return loser_winner

    def evolve(self, n):    # nature selection wrt pop's fitness
        for _ in range(n):  # random pick and compare n times
            sub_pop_idx = np.random.choice(np.arange(0, self.pop_size), size=2, replace=False)
            sub_pop = self.pop[sub_pop_idx]             # pick 2 from pop
            product = F(self.translateDNA(sub_pop))
            fitness = self.get_fitness(product)
            loser_winner_idx = np.argsort(fitness)
            loser_winner = sub_pop[loser_winner_idx]    # the first is loser and second is winner
            loser_winner = self.crossover(loser_winner)
            loser_winner = self.mutate(loser_winner)
            self.pop[sub_pop_idx] = loser_winner

        DNA_prod = self.translateDNA(self.pop)
        pred = F(DNA_prod)
        return DNA_prod, pred


plt.ion()       # something about plotting
x = np.linspace(*X_BOUND, 200)
plt.plot(x, F(x))

ga = MGA(DNA_size=DNA_SIZE, DNA_bound=[0, 1], cross_rate=CROSS_RATE, mutation_rate=MUTATION_RATE, pop_size=POP_SIZE)

for _ in range(N_GENERATIONS):                    # 100 generations
    DNA_prod, pred = ga.evolve(5)          # natural selection, crossover and mutation

    # something about plotting
    if 'sca' in globals(): sca.remove()
    sca = plt.scatter(DNA_prod, pred, s=200, lw=0, c='red', alpha=0.5); plt.pause(0.05)

plt.ioff();plt.show()

弔詭時間

---

我們要怎樣遷入股票這咚咚也就是前幾天所搭建的平台所提到的基因演算法

遺傳演算法最佳化高頻交易策略

額從哪裡下手呢

對策略

接下來要怎麼進行的策略分析.....

參考

---

https://github.com/MorvanZhou/Evolutionary-Algorithm