前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >NSGA2 Python实现

NSGA2 Python实现

作者头像
全栈程序员站长
发布2022-08-26 16:31:31
4360
发布2022-08-26 16:31:31
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

代码语言:javascript
复制
#importing necessary modules
import math
import random
import matplotlib.pyplot as Plt


#First Function to optimize
def function1(x1,x2):
    value = -x1*2 + x2
    return value
#Second Function to optimize
def function2(x1,x2):

    value = -x1*5*x2
    return value

def index_of(a,list):
    for i in range(0,len(list)):
        if a == list[i]:
            return i
    return 0

#求rank
def cd_index(front,f_values):
    #将front中的目标值排序,
    sorted_index = []
    for i in range(0, len(front)):
        temp_list = []
        temp_index =[]
        for j in front[i]:
            temp_list.append(f_values[j])
        temp_list.sort()
        for n in range(0,len(temp_list)):
            temp_index.append(index_of(temp_list[n],f_values))
        sorted_index.append(temp_index)
    return sorted_index

#求单个目标拥挤度
def crowding_distance(front,f_values):
    #将front中的目标值排序,
    sorted_values = []
    for i in range(0, len(front)):
        temp_list = []
        temp_index =[]
        for j in front[i]:
            temp_list.append(f_values[j])
        temp_list.sort()
        for n in range(0,len(temp_list)):
            temp_index.append(index_of(temp_list[n],f_values))
        sorted_values.append(temp_list)
     #计算拥挤度
    distance = [[] for i in range(0, len(front))]
    for i in range(0, len(front)):
        if len(front[i]) == 1:
            distance[i].append(math.inf)
        elif len(front[i]) == 2:
            distance[i].append(math.inf)
            distance[i].append(math.inf)
        else:
            distance[i].append(math.inf)
            for k in range(1,len(front[i])-1):
                if max(sorted_values[i]) == min(sorted_values[i]):
                    break
                distance[i].append((sorted_values[i][k+1]-sorted_values[i][k-1])/(max(sorted_values[i])-min(sorted_values[i])))
            distance[i].append(math.inf)
    return distance

#求总拥挤度
def Get_TOTAL_Distance(front,f1,f2):
    Tol_Dis = [[] for i in range(0, len(front))]
    tem_tol = []
    crowding_distance1 = crowding_distance(front, f1)  # 每个个体在f1上的拥挤度
    crowding_distance2 = crowding_distance(front, f2)  # 每个个体在f2上的拥挤度
    sorted_index1 = cd_index(front, f1)  # 对f1排序后的个体变换
    sorted_index2 = cd_index(front, f2)  # 对f1排序后的个体变换
    for i in range(0, len(sorted_index1)):
        for j in sorted_index1[i]:
            tem_tol.append(
                crowding_distance1[i][sorted_index1[i].index(j)] + crowding_distance2[i][sorted_index2[i].index(j)])
        Tol_Dis.append(tem_tol)
    return Tol_Dis


def fast_non_dominated_sort(values1,values2):
    S = [[] for i in range(0,len(values1))]
    front = [[]]
    n = [0 for i in range(0,len(values1))]

    for p in range(0,len(values1)):
        #S[p] = []
        #n[p] = 0
        for q in range(0,len(values1)):
            if ( values1[p] < values1[q] and values2[p] < values2[q]) or \
                    (values1[p] < values1[q] and values2[p] <= values2[q]) or \
                    (values1[p] <= values1[q] and values2[p] < values2[q]) :
                S[p].append(q)
            elif ( values1[p] > values1[q] and values2[p] > values2[q]) or \
                    (values1[p] > values1[q] and values2[p] >= values2[q]) or \
                    (values1[p] >= values1[q] and values2[p] > values2[q]) :
                n[p] += 1
        if n[p] == 0:
            front[0].append(p)
    i = 0
    while( front[i] != []):
        Q = []
        for p in front[i]:
            for q in S[p]:
                n[q] -= 1
                if(n[q] == 0):
                    Q.append(q)
        i += 1
        front.append(Q)
    del front[len(front)-1]
    return front

#离散重组
def crossover(a,b):
    r = random.random()
    list = []
    A =[0,0]
    B = [0,0]
    if r>0.5:
        A[0] = mutation(a[0])
        B[1] = mutation(b[1])
        list.append(A[0])
        list.append(B[1])
        return list
    else:
        A[1] = mutation(a[1])
        B[0] = mutation(b[0])
        list.append(B[0])
        list.append(A[1])
        return list

def mutation(a):
    mutation_pro=random.random()
    pop = 0
    if mutation_pro <0.05 :
        pop = min_x[0] + (max_x[0]-min_x[0])*random.random()
        return pop
    elif mutation_pro >0.05 and mutation_pro <0.1 :
        pop = min_x[1] + (max_x[1] - min_x[1]) * random.random()
        return pop
    else:
        return a



#Main program
popsize = 50
max_gen = 200

#Initialization
min_x = [-1,1]
max_x = [2,6]
pop = [[] for i in range(0,popsize)]
for i in range(0,popsize):
    for j in range(0,len(min_x)):
        pop[i].append(min_x[j]+(max_x[j]-min_x[j])*random.random())

gen = 0
while gen<max_gen:
    #Selection
    f1_values = [function1(pop[i][0], pop[i][1]) for i in range(0, popsize)]  # 得到每个个体的目标1值f1
    f2_values = [function2(pop[i][0], pop[i][1]) for i in range(0, popsize)]  # 得到每个个体的目标2值f2
    Front = fast_non_dominated_sort(f1_values[:],f2_values[:])#非支配排序
    #计算拥挤度
    Tol_Dis = Get_TOTAL_Distance(Front,f1_values,f2_values)

    pop2 = pop[:]
    # Generating offsprings
    while (len(pop2)!= 2*popsize) :
        p1 = random.randint(0,popsize-1)
        p2 = random.randint(0, popsize - 1)
        pop2.append(crossover(pop[p1],pop[p2]))

    f1_values1 = [function1(pop2[i][0], pop2[i][1]) for i in range(0, 2*popsize)]  # 得到每个个体的目标1值f1
    f2_values1 = [function2(pop2[i][0], pop2[i][1]) for i in range(0, 2*popsize)]  # 得到每个个体的目标2值f2
    Front1 = fast_non_dominated_sort(f1_values1[:], f2_values1[:])  # 非支配排序
    # 计算拥挤度
    Tol_Dis1 = Get_TOTAL_Distance(Front1, f1_values1, f2_values1)
    #Select
    num = 0
    new_pop_index = []
    for i in range(0, len(Front1)):
        if len(Front1[i]) < (popsize - num):  # 非支配排序选择 popsize是初代种群个数
            for j in range(0,len(Front1[i])):
                new_pop_index.append(Front1[i][j])
        else:  # 拥挤度选择
            for j in range(0, popsize - num):
                new_pop_index.append(Front1[i][j])
                if len(new_pop_index)== popsize:
                    break;
        num += len(Front1[i])
    new_pop = [pop2[i] for i in new_pop_index]
    pop = new_pop
    gen +=1

#plot
function1 = [i * -1  for i in f1_values]
function2 = [j * -1  for j in f2_values]
Plt.xlabel('Function 1 ',fontsize = 15)
Plt.ylabel('Function 2 ',fontsize = 15)
Plt.scatter(function1,function2)
Plt.show()

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/144579.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年5月1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档