首页 > 解决方案 > 如何使用 python 3 实现 SUS?

问题描述

我在遗传算法中使用随机通用抽样。我找到了它的伪代码。我暴露了使用 Python 3 对其进行编码的问题。错误是:一个系列的真值是模棱两可的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。谁能帮我?

伪代码:

SUS(Population, N)
    F := total fitness of Population
    N := number of offspring to keep
    P := distance between the pointers (F/N)
    Start := random number between 0 and P
    Pointers := [Start + i*P | i in [0..(N-1)]]
    return RWS(Population,Pointers)

RWS(Population, Points)
    Keep = []
    for P in Points
        i := 0
        while fitness sum of Population[0..i] < P
            i++
        add Population[i] to Keep
    return Keep

我的试用代码如下:

def susSelection(popRanked, eliteSize):

    df = pd.DataFrame(np.array(popRanked), columns=["Index","Fitness"])
    F = df.Fitness.cumsum()
    P = F/eliteSize
    Start = np.random.uniform(0,P)
    Pointers = [Start + i*P for i in range(0,(eliteSize-1))]
    return RWS(popRanked, Pointers)

def RWS(pop, points):
    Keep = []
    for P in points:
        i = 0
        for j in (0,i):
            df = pd.DataFrame(np.array(pop), columns=["Index","Fitness"])
            sumFit = df.Fitness.cumsum()
        if sumFit< P: 
            i+=1
        else: 
            Keep.append(pop[i])
    return Keep 

标签: python

解决方案


我已经使用 Python 3 使用了以下代码。我希望它可以帮助谁暴露同样的问题。

def susSelection(popRanked, popSize):

    import copy
    sumFitness = np.cumsum([popRanked[i][1] for i in range(len(popRanked))])
    pointerDistance = sumFitness[len(sumFitness)-1]/popSize

    start = np.random.uniform(0, pointerDistance)

    pointers =[]
    for i in range(popSize):
        pointers.append(start + i*pointerDistance)

    cumulativeFit = 0
    newIndiv = 0
    newPop = [None] * popSize
    nPop=[]
    for i in range(len(pointers)):
        while cumulativeFit <= pointers[i]:
            cumulativeFit += popRanked[newIndiv][1]
            newIndiv += 1
        if (newIndiv>= len(popRanked)-1):
            break
        newPop[i] = copy.deepcopy(popRanked[newIndiv][0])

    for i in range(len(pointers)):
        if newPop[i]!= None:
            nPop.append(newPop[i])

    return nPop

推荐阅读