I have a problem using sorted()
method. I am using this method inside a loop to sort a list which I am upgrading in every step of the loop. The first iteration works but the second an beyond doesn't and give me the next error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Here is my code:
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)
The error occurs in the line:
puntuados = [i[1] for i in sorted(puntuados)]
I can't figure out what I m doing wrong (I am not an expert in python). Can anyone help me?
Thanks in advance.
The problem arises where the tuples share the same first element, so
sorted(puntuados)
has to compare the second elements of the two tuples to determine their relative order, at which point you encounter this exception.
You can use
sorted(graded, key=lambda x: x[0])
to solve your problem, if you only want to sort based on the first element of the tuples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With