tensorflow2.0環境下,以復制方式擴展tensor,可以使用tf.tile()
函數。
該函數定義如下(圖自官網):https://www.tensorflow.org/api_docs/python/tf/keras/backend/tile
tf.tile()可以沿着某個維度對tensor進行指定倍數的復制,如下所示:
import tensorflow as tf
a = tf.constant([1, 2, 3])
tf.tile(a, [2]) # <tf.Tensor: id=2, shape=(6,), dtype=int32, numpy=array([1, 2, 3, 1, 2, 3])>
需要注意的是,tile不能增加tensor的維度,即tensor本身有幾個維度,那么它還是幾個維度,那么如果想要升維擴展呢,可以借助tf.reshape()
import tensorflow as tf
a = tf.constant([1, 2, 3])
a = tf.reshape(a, [1, 3]) # a變成了二維張量
tf.tile(a, [3, 2])
輸出如下:
<tf.Tensor: id=6, shape=(3, 6), dtype=int32, numpy=
array([[1, 2, 3, 1, 2, 3],
[1, 2, 3, 1, 2, 3],
[1, 2, 3, 1, 2, 3]])>