Home > Software engineering >  Am trying to append a matrix to a numpy array from a 3d list but It only append first row and when I
Am trying to append a matrix to a numpy array from a 3d list but It only append first row and when I

Time:06-29

I have a certain number of matrix in a list and when I try to append a matrix to the NumPy array It only appends the specified row and when I try to edit the code to append the whole matrix It keep returning the following error:

Traceback (most recent call last):
  File "so.py", line 129, in <module>
    parents = selection(cal_fitness(t1, t2, t3, matlist, 300, arr), 2, matlist)  # 
  File "so.py", line 124, in selection
    parents[i, :] = population[max_fitness_idx[0][0]]    
ValueError: could not broadcast input array from shape (3,5) into shape (5,)

The error related function:

def selection(fitness, num_parents, population):
        fitness = list(fitness)
        parents = numpy.empty((num_parents, len(population)))
        for i in range(num_parents):
            max_fitness_idx = numpy.where(fitness == numpy.max(fitness))
            #parents[i, :] = population[max_fitness_idx[0][0]][2]      
            parents[i, :] = population[max_fitness_idx[0][0]]
            fitness[max_fitness_idx[0][0]] = -999999
        return parents.astype(int)     
    
    
    parents = selection(cal_fitness(t1, t2, t3, matlist, 300, arr), 2, matlist)  
    print(parents)

The full code:

import numpy
import random
import pandas

wsn = numpy.arange(1, 6)
taskn = 3

t1 = numpy.random.randint(30, 200, size=len(wsn))
t2 = numpy.random.randint(30, 200, size=len(wsn))
t3 = numpy.random.randint(30, 200, size=len(wsn))

# print('\nGenerated Data:\t\n\nNumber   \t Task 1  \t   Task 2  \t   Task 3\n')
ni = min(len(t1), len(t2), len(t3))
# for i in range(ni):
#     print('\t {0}    \t   {1}    \t    {2}  \t\t {3}\n'.format(wsn[i], t1[i], t2[i], t3[i]))
# print('\n\n')
qmin = 50
qmax = 140

for i in range(len(t1)):
    if t1[i] <= qmin or t1[i] >= qmax:
        # t1=numpy.delete(t1,i)
        t1[i] = 0
for i in range(len(t2)):
    if t2[i] <= qmin or t2[i] >= qmax:
        # t2=numpy.delete(t2,i)
        t2[i] = 0
for i in range(len(t3)):
    if t3[i] <= qmin or t3[i] >= qmax:
        # t3=numpy.delete(t3,i)
        t3[i] = 0
i = 0
m = max(len(t1), len(t2), len(t3))
if t1[i] == 0 and t2[i] == 0 and t3[i] == 0:
    t1 = numpy.delete(t1, i)
    t2 = numpy.delete(t2, i)
    t3 = numpy.delete(t3, i)
    i  = 1
solperpop = len(wsn)
gen = 20
j = 0
pop_size = (taskn, solperpop)
# print('population size: {}'.format(pop_size))
# for j in range(ni):
#   pop_size=list(solperpop,taskn)
matlist = list()
# print('\n\n')
i = 0
k = 0
nbrofindv = 5
arr = []
for i in range(nbrofindv):
    init_pop = numpy.zeros(pop_size, dtype=int)
    init_pop = init_pop.astype(int)
    k = 0
    l = 0
    for k in range(taskn):
        l = random.randrange(solperpop - 1)
        init_pop[k][l] = 1
        arr.append(l)
    matlist.append(init_pop)

pandas.set_option('display.max_columns', None)
pandas.set_option('display.width', None)
zipped = pandas.DataFrame(list(zip(*matlist)))
# , columns=['Individual 1', 'Individual 2', 'Individual 3', 'Individual 4', 'Individual 5'])
print(zipped)
print('\n\n')
i = 0
for i in range(len(wsn)):
    if t1[i] == 0:
        if init_pop[0][i] != 0:
            init_pop[0][i] == 0
    if t2[i] == 0:
        if init_pop[1][i] != 0:
            init_pop[1][i] == 0
    if t3[i] == 0:
        if init_pop[2][i] != 0:
            init_pop[2][i] == 0

def cal_fitness(task1, task2, task3, matix, mmax, array):
    fitness = numpy.empty(len(matix))
    S1 = numpy.empty(len(matix), dtype=int)
    z = 0
    for i in range(len(matix)):
        S1[i] = task1[array[0   z]]   task2[array[1   z]]   task3[array[2   z]]
        z  = 3
        if S1[i] <= mmax:
            fitness[i] = S1[i]
        else:
            fitness[i] = 0
    return fitness.astype(int)

fitness = cal_fitness(t1, t2, t3, matlist, 300, arr)   

def selection(fitness, num_parents, population):
    fitness = list(fitness)
    parents = numpy.empty((num_parents, len(population)))
    for i in range(num_parents):
        max_fitness_idx = numpy.where(fitness == numpy.max(fitness))
        #parents[i, :] = population[max_fitness_idx[0][0]][2]      
        parents[i, :] = population[max_fitness_idx[0][0]]
        fitness[max_fitness_idx[0][0]] = -999999
    return parents.astype(int)     

parents = selection(cal_fitness(t1, t2, t3, matlist, 300, arr), 2, matlist)  
print(parents)
print('\n\n')

def crossover(parents, num_offsprings):
    offsprings = numpy.empty((num_offsprings, parents.shape[1]))
    crossover_point = int(parents.shape[1] / 2)
    crossover_rate = 0.5
    i = 0
    while parents.shape[0] < num_offsprings:
        parent1_index = i % parents.shape[0]
        parent2_index = (i   1) % parents.shape[0]
        x = random.random()
        if x > crossover_rate:
            continue
        parent1_index = i % parents.shape[0]
        parent2_index = (i   1) % parents.shape[0]
        offsprings[i, 0:crossover_point] = parents[parent1_index, 0:crossover_point]
        offsprings[i, crossover_point:] = parents[parent2_index, crossover_point:]
        i  = 1                       # <== modified
    return offsprings                # <== modified

print(crossover(parents, 2))         # <== modified

CodePudding user response:

This issue is related to dimensions that specified for parents, which is 2d now so must be modified to 3d. So, IIUC, you can achieve this aim by:

def selection(fitness, num_parents, population):
    fitness = list(fitness)

    # parents shape is modified (a new axis with the needed length is added)
    parents = numpy.empty((num_parents, len(population[0]), len(population[0][0])))  # <==

    for i in range(num_parents):
        max_fitness_idx = numpy.where(fitness == numpy.max(fitness))
        parents[i, :] = population[max_fitness_idx[0][0]]
        fitness[max_fitness_idx[0][0]] = -999999
    return parents.astype(int)
  • Related