使用 Tensorflow,如何将两个 arrays/tensors 与每个数组的交换索引结合起来?
With Tensorflow, How to combine two arrays/tensors with interchanging index from each array?
假设我有以下 2 个数组:
a = tf.constant([1,2,3])
b = tf.constant([10,20,30])
我们如何使用 Tensorflow 的方法将它们连接起来,以便通过每次从每个数组中取 1 个数字的间隔来创建新数组? (是否已经有可以做到这一点的功能?)
例如,2 个数组的期望结果是:
[1,10,2,20,3,30]
方法 tf.concat
只是将数组 b 放在数组 a 之后。
a = tf.constant([1,2,3])
b = tf.constant([10,20,30])
c = tf.stack([a,b]) #combine a,b as a matrix
d = tf.transpose(c) #transpose matrix to get the right order
e = tf.reshape(d, [-1]) #reshape to 1-d tensor
您也可以尝试使用 tf.tensor_scatter_nd_update
:
import tensorflow as tf
a = tf.constant([1,2,3])
b = tf.constant([10,20,30])
shape = tf.shape(a)[0] + tf.shape(b)[0]
c = tf.tensor_scatter_nd_update(tf.zeros(shape, dtype=tf.int32),
tf.expand_dims(tf.concat([tf.range(start=0, limit=shape, delta=2), tf.range(start=1, limit=shape, delta=2) ], axis=0), axis=-1),
tf.concat([a, b], axis=0))
# tf.Tensor([ 1 10 2 20 3 30], shape=(6,), dtype=int32)
假设我有以下 2 个数组:
a = tf.constant([1,2,3])
b = tf.constant([10,20,30])
我们如何使用 Tensorflow 的方法将它们连接起来,以便通过每次从每个数组中取 1 个数字的间隔来创建新数组? (是否已经有可以做到这一点的功能?)
例如,2 个数组的期望结果是:
[1,10,2,20,3,30]
方法 tf.concat
只是将数组 b 放在数组 a 之后。
a = tf.constant([1,2,3])
b = tf.constant([10,20,30])
c = tf.stack([a,b]) #combine a,b as a matrix
d = tf.transpose(c) #transpose matrix to get the right order
e = tf.reshape(d, [-1]) #reshape to 1-d tensor
您也可以尝试使用 tf.tensor_scatter_nd_update
:
import tensorflow as tf
a = tf.constant([1,2,3])
b = tf.constant([10,20,30])
shape = tf.shape(a)[0] + tf.shape(b)[0]
c = tf.tensor_scatter_nd_update(tf.zeros(shape, dtype=tf.int32),
tf.expand_dims(tf.concat([tf.range(start=0, limit=shape, delta=2), tf.range(start=1, limit=shape, delta=2) ], axis=0), axis=-1),
tf.concat([a, b], axis=0))
# tf.Tensor([ 1 10 2 20 3 30], shape=(6,), dtype=int32)