как добавить разные возвращаемые значения в список - PullRequest
0 голосов
/ 19 июня 2020

У меня есть функция вроде:

def function(self):
    matrix = []
    for i in range(10):
        contents = [1,0,1,0] #integer values in a list, changes every time when running function()
        matrix .append(contents)
    self.matrix = matrix 
    return matrix 

, и у меня есть еще один пустой список, я пытаюсь добавить matrix в empty_matrix 5 раз, поэтому результат должен быть как:

empty_matrix = [[matrix1],[matrix2],[matrix3],[matrix4],[matrix5]]

Но я не уверен, как заставить Matrix1,2,3,4,5 иметь разные значения. Когда я запускаю только function(self), он возвращает другое значение, но когда я добавляю его в empty_matrix, он добавляет то же значение, например

empty_matrix = [[matrix1],[matrix1],[matrix1],[matrix1],[matrix1]]. 

Любая помощь приветствуется.

Исходный код прилагается ниже:

def generate_population(self):
    model = self.model
    weights_origin = model.get_weights()
    shape_list = []
    matrix= []
    empty_matrix= [[],[],[],[],[]]


    for i, w in enumerate(weights_origin):
        #get shape of w -> save shape into shape_list -> generate binary_value that has the shape of shape_list 
        #-> convert binary_value to float32 -> define it as tf Variable -> append to rand_covers list
        w_shape = tf.shape(w)
        shape_list.append(w_shape)
        binary_value = np.random.randint(2, size = shape_list[i])      
        to_float = tf.cast(binary_value, tf.float32)  
        weights2 = tf.Variable(to_float, name="addition_"+str(i), trainable=True)
        matrix.append(weights2)

    for j in range(5):
        empty_matrix[j].append(matrix)


self.matrix = matrix
return matrix

1 Ответ

1 голос
/ 19 июня 2020

Вместо

for j in range(5):
    empty_matrix[j].append(matrix)

вам понадобится

for j in range(5):
    matrix = function()
    empty_matrix[j].append(matrix)

Если вы хотите использовать ту же матрицу в начале и позже изменить значения в одной из них, не изменяя значения в другие, то вам нужно продублировать их, используя .copy()

matrix = function()

for j in range(5):
    empty_matrix[j].append( matrix.copy() )

или copy.deepcopy() для глубокого дублирования

import copy

matrix = function()

for j in range(5):
    empty_matrix[j].append( copy.deepcopy(matrix.copy) )

EDIT:

Я не понимаю, что вы пытаетесь сделать, но код кажется странным, и я бы написал его

def generate_population(self):
    model = self.model
    weights_origin = model.get_weights()
    shape_list = []

    empty_matrix= [[],[],[],[],[]]

    for j in range(5):

        matrix = []

        for i, w in enumerate(weights_origin):
            #get shape of w -> save shape into shape_list -> generate binary_value that has the shape of shape_list 
            #-> convert binary_value to float32 -> define it as tf Variable -> append to rand_covers list
            w_shape = tf.shape(w)
            shape_list.append(w_shape)
            binary_value = np.random.randint(2, size = shape_list[i])      
            to_float = tf.cast(binary_value, tf.float32)  
            weights2 = tf.Variable(to_float, name="addition_"+str(i), trainable=True)
            matrix.append(weights2)

        empty_matrix[j].append(matrix)

    return empty_matrix

# --- outside function ---

empty_matrix = generate_population()

или

def generate_population(self):
    model = self.model
    weights_origin = model.get_weights()
    shape_list = []

    matrix = []

    for i, w in enumerate(weights_origin):
        #get shape of w -> save shape into shape_list -> generate binary_value that has the shape of shape_list 
        #-> convert binary_value to float32 -> define it as tf Variable -> append to rand_covers list
        w_shape = tf.shape(w)
        shape_list.append(w_shape)
        binary_value = np.random.randint(2, size=shape_list[i])      
        to_float = tf.cast(binary_value, tf.float32)  
        weights2 = tf.Variable(to_float, name="addition_"+str(i), trainable=True)
        matrix.append(weights2)

    return matrix

# --- outside function ---

empty_matrix= [[],[],[],[],[]]

for j in range(5):
    matrix = generate_population()
    empty_matrix[j].append(matrix)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...