我需要一個具有形狀的張量,[3136, 512]其中我更新隨機值,其中列位于隨機生成的列索引串列中。
我的意思是,我創建了一個全為 0 和 shape 的張量[3136, 512],創建了一個包含與410之前創建的張量的列索引相符的元素的串列,然后我有一個形狀[3136, 410]包含我想要更新第一個張量的值的張量。問題是我需要將索引串列的第一個值映射到張量更新的第 0 列。
例子:
生成 410 個隨機列索引,完成。
將它們轉換為張量,完成。
用值 initial_weight[row][colonna] 更新 tensor_testing[row][col],其中冒號不是
initial_weights的索引(所以,它不是 0,1,2,3,4....)但將索引關聯到之前隨機生成的值。假設隨機生成了值 (6,7,9) 然后我需要用值 initial_weights[row][0] 更新 tensor_testing[row][6] 等等,直到生成的索引結束。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))
uj5u.com熱心網友回復:
您可以使用tf.scatter_nd
具有給定輸入形狀的代碼
# 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])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/351026.html
