首页 > 解决方案 > IndexError:字符串索引超出范围。局部搜索的遗传算法

问题描述

population我有这段代码,目的是使用遗传算法在变量中执行局部搜索:

import random

stringSize = 4
top = 10 * stringSize

def value(s):
  return max(-abs(round(0.3*top) - s), .025 - abs(round(0.8 * top) - s))

def ga(times = 10, popSize = 20, mutation_prob = 0.001):
  #population = [int(random.random() * top) for j in range(popSize)]
  population ={0 : [3,2,1],
                1 : [4],
                2 : [6,5],
                3 : [7],
                4 : [8],
                5 : [9]}
  print(len(population))
  print("---")
  history = []
  for i in range(times):
    print(len(population[i]))
    print(i)
    print("above")
    fitness = [value(population[j][i]) for j in range(len(population[i]))]
    fitMax = -float('inf')
    
    for j in range(len(population[i])):
      if fitness[j] > fitMax:
        fitMax = fitness[j]
        jBest = j
    history.append(population[jBest])
    fit_sum = sum(fitness)
    probs = [x/fit_sum for x in fitness]
    cutoff = [sum(probs[:j+1]) for j in range(len(population[i]))]
    children = []

    for j in range(len(population[i])):
      r = random.random()
      for k in range(len(population[i])):
        if r < cutoff[k]:
          break
      print(population[k-1])
      print("above2")    
      par1 = population[k-1]
      par2 = population[int(random.random() * len(population[i]))]
      split = int(random.random() * (stringSize + 1))
      child = str(par1)[:split] + str(par2)[split:]
      if random.random() < mutation_prob:
        where = int(random.random() * stringSize)
        what = str(int(random.random() * 10))
        child = child[0:where] + what + child[where + 1:]
      children.append(child[i])
    population = children
  return population

但是运行这个,它会抛出这个错误:

6
---
3
0
above
[4]
above2
[4]
above2
[3, 2, 1]
above2
1
1
above
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-86-73e983c9ab93> in <module>()
----> 1 ga()

1 frames
<ipython-input-85-0ceb6003f3fa> in <listcomp>(.0)
     17     print(i)
     18     print("above")
---> 19     fitness = [value(population[j][i]) for j in range(len(population[i]))]
     20     fitMax = -float('inf')
     21 

IndexError: string index out of range

我正在修改这段代码,现在我迷路了。我有什么要改变的?感谢你的帮助

标签: pythonarraysgenetic-algorithm

解决方案


推荐阅读