python - 如何使用 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 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
推荐阅读
- javascript - 光滑的轮播计数器空值
- python - Python Turtle 透明填充?
- python - 如何根据各种线性回归模型的预测开发预测模型?
- swift - 快速隐藏内部类
- ruby-on-rails - 使用 Sidekiq 缓冲和批处理作业
- python - 如何创建一个循环来为相同的 x 曲线拟合 y 的不同数据集?在 Python 中
- python - 在 Pandas 的 .csv 文件中从 DataFrame 中删除索引列
- asp.net-core - Razor Pages,如何将路线值添加到导航链接?
- php - 如何清除已删除实体的 Symfony 项目?
- c - 如何在我的 Lex/Yacc 程序中输入多个输入?