Iva*_*tch 3 python sorting numpy python-3.x
我在使用sorted()方法时遇到问题。我在循环中使用此方法对我在循环的每个步骤中升级的列表进行排序。第一次迭代有效,但第二次超越没有,并给我下一个错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
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)
Run Code Online (Sandbox Code Playgroud)
错误发生在以下行中:
puntuados = [i[1] for i in sorted(puntuados)]
Run Code Online (Sandbox Code Playgroud)
我不知道我做错了什么(我不是 Python 专家)。谁能帮我?
提前致谢。
问题出现在元组共享相同的第一个元素的地方,所以
sorted(puntuados)
Run Code Online (Sandbox Code Playgroud)
必须比较两个元组的第二个元素以确定它们的相对顺序,此时您会遇到此异常。
您可以使用
sorted(graded, key=lambda x: x[0])
Run Code Online (Sandbox Code Playgroud)
解决您的问题,如果您只想根据元组的第一个元素进行排序。
| 归档时间: |
|
| 查看次数: |
6197 次 |
| 最近记录: |