我在使用 sorted()
方法时遇到问题。我在循环中使用此方法对我在循环的每一步中升级的列表进行排序。第一次迭代有效,但第二次迭代无效,并给出下一个错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
这是我的代码:
import numpy as np
import random as rd
import math
Poblacion = 10
pressure = int(0.3*Poblacion)
mutation_chance = 0.08
Modelo = np.array([[0.60,0.40,0.90],[0.26,0.20,0.02],[0.80,0.00,0.05]])
x = np.array([[1.0,2.0,3.0],[0.70,0.50,0.90],[0.10,0.40,0.20]])
y = np.array([[4.10,0.72,2.30],[1.43,0.30,1.01],[0.40,0.11,0.18]])
def crearIndividuo():
return[np.random.random((3, 3))]
def crearPoblacion():
return [crearIndividuo() for i in range(Poblacion)]
def calcularFitness(individual):
error = 0
i=0
for j in x:
error += np.array(individual).dot(j)-y[i]
i += 1
error = np.linalg.norm(error,ord=1)
fitness = math.exp(-error)
return fitness
def selection_and_reproduction(population):
puntuados = [ (calcularFitness(i), i) for i in population]
puntuados = [i[1] for i in sorted(puntuados)]
population = puntuados
selected = puntuados[(len(puntuados)-pressure):]
j=0
while (j < int(len(population)-pressure)):
padre = rd.sample(selected, 2)
population[j] = 0.5*(np.array(padre[0]) + np.array(padre[1]))
j += 1
population[j] = 1.5*np.array(padre[0]) - 0.5*np.array(padre[1])
j += 1
population[j] = -0.5*np.array(padre[0]) + 1.5*np.array(padre[1])
j += 1
return population
population = crearPoblacion()
for l in range(3):
population = selection_and_reproduction(population)
print("final population: ", population)
错误发生在以下行:
puntuados = [i[1] for i in sorted(puntuados)]
我不知道我做错了什么(我不是Python专家)。谁能帮我吗?
提前致谢。
最佳答案
问题出现在元组共享相同的第一个元素的地方,所以
sorted(puntuados)
必须比较两个元组的第二个元素以确定它们的相对顺序,此时您会遇到此异常。
你可以使用
sorted(graded, key=lambda x: x[0])
如果您只想根据元组的第一个元素进行排序,可以解决您的问题。
关于python - 排序方法 : The truth value of an array with more than one element is ambiguous. 使用 a.any() 或 a.all(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48857017/