在Geatpy的官方文檔中并沒有多目标+多染色體進化算法的demo,在我實際寫代碼時也出現了一些問題。本篇部落格補充一個調用moea_psy_NSGA2_templet的demo:
目标函數:
max f1 = x1 * x2 + x3
min f2 = x1 + x2 - x3
s.t.
2*x1 + x2 - 1 <= 0
x1 + 2*x3 - 2 <= 0
x1 + x2 + x3 - 1 == 0
1 <= x1 <= 4
-10 <= x2 <= 1
0 < x3 < 2
Myproblem.py:
# -*- coding: utf-8 -*-
import numpy as np
import geatpy as ea
"""
max f1 = x1 * x2 + x3
min f2 = x1 + x2 - x3
s.t.
2*x1 + x2 - 1 <= 0
x1 + 2*x3 - 2 <= 0
x1 + x2 + x3 - 1 == 0
1 <= x1 <= 4
-10 <= x2 <= 1
0 < x3 < 2
"""
class MyProblem(ea.Problem): # 繼承Problem父類
def __init__(self):
name = "MyProblem"
M = 2 # f的數量
maxormins = [-1, 1] # (目标最小最大化标記清單,1:最小化該目标;-1:最大化該目标)
Dim = 3 # x的個數
# x的上下界與定義邊界是開區間還是閉區間
var_types = [0] * Dim # 元素為0表示對應的變量是連續的;1表示是離散的
lb = [1, -10, 0] # 決策變量下界
ub = [4, 1, 2] # 決策變量上界
lbin = [1, 1, 0] # 決策變量下邊界(0表示不包含該變量的下邊界,1表示包含)
ubin = [1, 1, 0] # 決策變量上邊界(0表示不包含該變量的上邊界,1表示包含)
ea.Problem.__init__(self, name, M, maxormins, Dim, var_types, lb, ub, lbin, ubin)
def aimFunc(self, pop): # 目标函數
Vars = pop.Phen # 得到決策變量矩陣
x1 = Vars[:, [0]]
x2 = Vars[:, [1]]
x3 = Vars[:, [2]]
# 目标函數:
f1 = x1 * x2 + x3
f2 = x1 + x2 - x3
pop.ObjV = np.hstack([f1, f2])
# 限制條件:(要全部化為 <= )
c1 = 2 * x1 + x2 - 1
c2 = x1 + 2 * x3 - 2 # 限制條件 <= 0
c3 = np.abs(x1 + x2 + x3 - 1) # 限制條件 = 0
pop.CV = np.hstack([c1, c2, c3])
Main函數中:
注意Encoding與Field都要是數組的結構,否則報錯
# -*- coding: utf-8 -*-
import numpy as np
import geatpy as ea # import geatpy
from MyProblem import MyProblem # 導入自定義問題接口
if __name__ == '__main__':
"""================================執行個體化問題對象==========================="""
problem = MyProblem() # 生成問題對象
"""==================================種群設定==============================="""
NIND = 50 # 種群規模
Encoding = ['RI']
Field = [ea.crtfld(Encoding[0], problem.varTypes, problem.ranges, problem.borders)] # 建立區域描述器
population = ea.PsyPopulation(Encoding, Field, NIND) # 執行個體化種群對象(此時種群還沒被初始化,僅僅是完成種群對象的執行個體化)
"""================================算法參數設定============================="""
myAlgorithm = ea.moea_psy_NSGA2_templet(problem, population) # 執行個體化一個算法模闆對象
myAlgorithm.MAXGEN = 5 # 最大進化代數
"""===========================調用算法模闆進行種群進化======================="""
ndset = myAlgorithm.run()
ndset.save()
print('用時:%s 秒' % (myAlgorithm.passTime))
print('非支配個體數:%s 個' % (ndset.sizes))
print('機關時間找到帕累托前沿點個數:%s 個' % (int(ndset.sizes // myAlgorithm.passTime)))
其他問題:
因為我是在deepin系統中程式設計,在使用Geapy架構時導出圖像時會調用matplotlib,而常見的中文方塊會出現,還會有“黑體”字型找不到報錯,在代碼中添加matplotlib的配置也會被覆寫,希望新版能修正這個問題。