優(yōu)化算法-2.遺傳算法實(shí)現(xiàn)(python)

本文基于 優(yōu)化算法筆記(六)遺傳算法 - 簡書 (jianshu.com) 進(jìn)行實(shí)現(xiàn),建議先看原理碉碉。

輸出結(jié)果如下

GA.gif

實(shí)現(xiàn)代碼如下

# 遺傳算法
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from PIL import Image
import shutil
import os
import glob 
import random

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用來正常顯示中文標(biāo)簽
plt.rcParams['axes.unicode_minus'] = False  # 用來正常顯示負(fù)號(hào)

def plot_jpg(start, point_best, err, m, n, lower, upper, title):
    point_g = min(start.tolist(), key=target)
    
    plt.figure(figsize=(8, 12))
    gs = gridspec.GridSpec(3, 2)
    
    ax1 = plt.subplot(gs[:2, :2])
    ax1.scatter(start[:, 0], start[:, 1], alpha=0.3, color='green', s=20, label='當(dāng)前位置')  # 當(dāng)前位置
    ax1.scatter(point_g[0], point_g[1], alpha=1, color='blue', s=20, label='當(dāng)前最優(yōu)點(diǎn)')  # 全局最優(yōu)點(diǎn)
    ax1.scatter(point_best[0], point_best[1], alpha=0.3, color='red', label='目標(biāo)點(diǎn)')  # 最優(yōu)點(diǎn)

    for i in range(n):
        ax1.text(start[i][0]+2, start[i][1]+2, f'{i}', alpha=0.3, fontsize=10, color='red')
    
    ax1.grid(True, color='gray', linestyle='-.', linewidth=0.5)
    ax1.set_xlim(lower[0]*1.2, upper[0]*1.2)
    ax1.set_ylim(lower[1]*1.2, upper[1]*1.2)
    ax1.set_xlabel(f'iter:{m}  dist: {err[-1]:.8f}')
    ax1.set_title(title)
    ax1.legend(loc='lower right', bbox_to_anchor=(1, 0), ncol=1)

    ax2 = plt.subplot(gs[2, :])
    ax2.plot(range(len(err)), err, marker='o', markersize=5)
    ax2.grid(True, color='gray', linestyle='-.', linewidth=0.5)
    ax2.set_xlim(0, max_iter)
    ax2.set_ylim(0, np.ceil(max(err)))
    ax2.set_xticks(range(0, max_iter, 5))
    
    plt.savefig(rf'./tmp/tmp_{m:04}.png')
    plt.close()


# 目標(biāo)函數(shù)
def target(point):
    return (point[0]-a)**2 + (point[1]-b)**2


# 選擇
def select(population):
    s = 0
    for i in range(d):
        s += ((upper_lim[i]-lower_lim[i]) ** 2)
    s = s**0.5
    weight = [s-(target(i)**0.5) for i in population]
    weight = list((weight - (min(weight)-0.01))/sum(weight))
    res = []
    # c1 = min(range(n), key= lambda x: target(population[x]))  # 最優(yōu)個(gè)體 
    for i in range(n):
        tmp_i = list(range(n))
        tmp_w = weight[:]
        c1 = random.choices(tmp_i, tmp_w, k=1)[0]
        tmp_i.pop(c1)
        tmp_w.pop(c1)
        c2 = random.choices(tmp_i, tmp_w, k=1)[0]
        res.append([c1, c2])
    return res


# 交叉
def cross(population, res, CR):
    population_new = []
    for i in range(n):
        c1, c2 = res[i]
        population_new.append(list(population[c1]))
        # if random.random() < CR and i > 0:
        if random.random() < CR :
            k = random.randint(0,d-1)
            population_new[i][k] = population[c2][k]
    return np.array(population_new)


# 變異
def mutation(population, AR):
    population_new = population.copy()
    for i in range(n):
        # if random.random() < AR and i > 0:
        if random.random() < AR:
            r, k = random.random(), random.randint(0,d-1)
            population_new[i][k] = r*(upper_lim[k]-lower_lim[k])+lower_lim[k]
    return population_new


def GA():
    # 初始化種群
    population = np.random.random(size=(n, d))
    for _ in range(d):
        population[:, _] = population[:, _]*(upper_lim[_]-lower_lim[_])+lower_lim[_]
    
    if os.path.exists(tmp_path):
        shutil.rmtree(tmp_path) 
    os.makedirs(tmp_path, exist_ok=True)
    errors = [target(min(population.tolist(), key=target))**0.5]
    for _ in range(max_iter):
        title = f'GA\nn:{n} CR:{CR} AR:{AR} max_iter:{max_iter}'
        plot_jpg(population, point_best, errors, _, n, lower_lim, upper_lim, title)
        choices = select(population)
        population_new = cross(population, choices, CR)
        population = mutation(population_new, AR)
        errors.append(target(min(population.tolist(), key=target))**0.5)
    plot_jpg(population, point_best, errors, max_iter, n, lower_lim, upper_lim, title)
    return errors


CR = 0.8  # 交叉率
AR = 0.05  # 變異率

n = 20  # 粒子數(shù)量
d = 2  # 粒子維度
max_iter = 200  # 迭代次數(shù)

# 搜索區(qū)間 
lower_lim = [-100, -100]
upper_lim = [100, 100]

# 目標(biāo)點(diǎn)
a, b = 0, 0
point_best = (a, b)

# 臨時(shí)文件路徑
tmp_path = r'./tmp/'

err = GA()

images = [Image.open(png) for png in glob.glob(os.path.join(tmp_path, '*.png'))[::5]]
im = images.pop(0)
im.save(r"./GA.gif", save_all=True, append_images=images, duration=500)

im = Image.open(r"./GA.gif")
im.show()
im.close()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末巧娱,一起剝皮案震驚了整個(gè)濱河市参萄,隨后出現(xiàn)的幾起案子蔓姚,更是在濱河造成了極大的恐慌,老刑警劉巖厌衔,帶你破解...
    沈念sama閱讀 221,548評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件驻襟,死亡現(xiàn)場離奇詭異夺艰,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)沉衣,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評論 3 399
  • 文/潘曉璐 我一進(jìn)店門郁副,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人豌习,你說我怎么就攤上這事存谎。” “怎么了肥隆?”我有些...
    開封第一講書人閱讀 167,990評論 0 360
  • 文/不壞的土叔 我叫張陵既荚,是天一觀的道長。 經(jīng)常有香客問我栋艳,道長恰聘,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,618評論 1 296
  • 正文 為了忘掉前任吸占,我火速辦了婚禮晴叨,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘矾屯。我一直安慰自己兼蕊,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,618評論 6 397
  • 文/花漫 我一把揭開白布件蚕。 她就那樣靜靜地躺著孙技,像睡著了一般产禾。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上牵啦,一...
    開封第一講書人閱讀 52,246評論 1 308
  • 那天亚情,我揣著相機(jī)與錄音,去河邊找鬼蕾久。 笑死势似,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的僧著。 我是一名探鬼主播,決...
    沈念sama閱讀 40,819評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼障簿,長吁一口氣:“原來是場噩夢啊……” “哼盹愚!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起站故,我...
    開封第一講書人閱讀 39,725評論 0 276
  • 序言:老撾萬榮一對情侶失蹤皆怕,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后西篓,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體愈腾,經(jīng)...
    沈念sama閱讀 46,268評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,356評論 3 340
  • 正文 我和宋清朗相戀三年岂津,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了虱黄。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,488評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡吮成,死狀恐怖橱乱,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情粱甫,我是刑警寧澤泳叠,帶...
    沈念sama閱讀 36,181評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站茶宵,受9級特大地震影響危纫,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜乌庶,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,862評論 3 333
  • 文/蒙蒙 一种蝶、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧安拟,春花似錦蛤吓、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽锅棕。三九已至,卻和暖如春淌山,著一層夾襖步出監(jiān)牢的瞬間裸燎,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評論 1 272
  • 我被黑心中介騙來泰國打工泼疑, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留德绿,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,897評論 3 376
  • 正文 我出身青樓退渗,卻偏偏與公主長得像移稳,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子会油,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,500評論 2 359

推薦閱讀更多精彩內(nèi)容