I need a tensor with shape [3136, 512]
where i update random value where the column is inside a list of randomly generated column index.
What i mean is that i create a tensor with all 0 and shape [3136, 512]
, create a list with 410
elements that rappresent the column indices of the tensor created before, then i have a tensor with shape [3136, 410]
that contain the values i want to update the first tensor. The problem is that i need to map the first value of the indices list to column 0 of the tensor update.
Example:
Generate 410 random columns index, done.
Convert them to tensor, done.
Update tensor_testing[row][col] with value initial_weight[row][colonna] where colonna is not the index of the
initial_weights(so, it's not 0,1,2,3,4....) but associate the indices to the value randomly generated before. Let's say the random generated the values (6,7,9) then i need to update tensor_testing[row][6] with value initial_weights[row][0] and so on for each row until the end of the generated indices.import tensorflow as tf if __name__ == '__main__': import random # Shape of the tensors shape_for_layer = [3136, 512] subshape = [3136, 410] # Create a random tensor with the shape above initial_weight = tf.random.uniform(subshape, minval=0, maxval=None, dtype=tf.dtypes.float32, seed=None, name=None) # Create a 0s tensor with the shape above tensor_testing = tf.zeros(shape_for_layer, tf.float32) # Generate 410 random value for the column index where i will take the values layer_456_col = random.sample(range(512), 410) # Later on set them in order # Convert to Tensor for tf.gather use indices_col = tf.convert_to_tensor(layer_456_col) # Result to print random = ... # Reshape back to [3136, 512] i don't know if it's really needed since it was the original shape. random = tf.reshape(random, shape_for_layer) print(tf.shape(random))
CodePudding user response:
You can use tf.scatter_nd
Bellow a code with the given input shape
# Shape of the tensors
shape_for_layer = [3136, 512]
subshape = [3136, 410]
# Create a random tensor with the shape above
initial_weight = tf.random.uniform(subshape, minval=0, maxval=None, dtype=tf.dtypes.float32, seed=None,
name=None)
# Create a 0s tensor with the shape above
tensor_testing = tf.zeros(shape_for_layer, tf.float32)
# Generate 410 random value for the column index where i will take the values
layer_456_col = random.sample(range(512), 410) # Later on set them in order
# Convert to Tensor for tf.gather use
indices_col = tf.expand_dims(tf.convert_to_tensor(layer_456_col), 1)
final_tensor = tf.transpose(tf.scatter_nd(updates=tf.transpose(initial_weight, [1, 0]), indices=indices_col, shape=[shape_for_layer[1], shape_for_layer[0]]), [1, 0])