如何为mtrand.RandomState.choice模块修正错误:“ ValueError:'a'和'p'必须具有相同的大小”?

时间:2019-05-21 01:04:47

标签: python arrays python-3.x numpy numpy-random

我正在实现一种算法来解决8皇后问题:https://en.wikipedia.org/wiki/Eight_queens_puzzle

在尝试遍历整个种群并通过一些交叉创建一个新种群时,我遇到了一个问题。问题出在numpy.random的选择函数中。

我的意图是将population分配给newPopulation(第50行),空的newPopulation(第53行),然后下一次迭代将新的100个子代追加到{{1} }。

有人抱怨输入到choice()的列表大小不一样,即使我在循环之前打印了每一个的len()并且显示它们都是100?

完整错误:

newPopulation

这是我的程序:

Traceback (most recent call last):
  File "test.py", line 44, in <module>
    choice1 = choice(population, p=normalFitness)
  File "mtrand.pyx", line 1141, in mtrand.RandomState.choice
ValueError: 'a' and 'p' must have same size

我认为可能是因为我将normalFitness列表分配给了一个空列表,而不是使用了del。如果我将第53行更改为: 1 import queensState as qs 2 import numpy as np 3 import random 4 from numpy.random import choice 5 6 def cross(state1,state2): 7 return qs.State([state1.state[0],state1.state[1],state1.state[2],state1.state[3],state2.state[4], state2.state[5],state2.state[6],state2.state[7]]) 8 9 #create the initial population 10 population = [] 11 newPopulation = [] 12 normalFitness = [] 13 fitness=np.zeros((100,),dtype=int) 14 15 #step through each state and give 16 #random values to each index in the array 17 for i in range(100): 18 x = [] 19 for h in range(8): 20 d = random.randint(1,8) 21 x.append(d) 22 newState = qs.State(x) 23 #append the current state to the population with 24 #the fitness(hash) and the state array 25 population.append(newState) 26 27 28 for i in range(100): 29 totalFitness = 0 30 for n in range(100): #calculate total fitness 31 totalFitness+=population[n].fitness 32 33 fitness[i]=totalFitness 34 35 #initialize the normalized fitness array 36 for x in range(100): 37 normalFitness.append(population[x].fitness/totalFitness) 38 39 print("poplen: ",len(population)," fitlen: ",len(normalFitness)) #this prints "poplen: 100 fitlen: 100" 40 for x in range(100): #this loop is solely for testing 41 print("Pop: ",population[x].state," normalfit: ", normalFitness[x]) 42 43 for x in range(100): 44 choice1 = choice(population, p=normalFitness) 45 choice2 = choice(population, p=normalFitness) 46 child = cross(choice1,choice2) 47 newPopulation.append(child) 48 #print("State1: ", choice1.state, " State2: ",choice2.state, "Cross: ", child.state) 49 50 population = newPopulation 51 for x in range(100): 52 print(population[x].state) 53 normalFitness=[] 54 print(len(normalFitness)) 55 56 print(fitness) ,则它具有相同的行为。

如果需要,这里是QueensState代码:

del normalFitness[:]

任何想法都将不胜感激!

谢谢。

0 个答案:

没有答案