这是我的代码:
from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import LSTM, RepeatVectorModel = Sequential([ LSTM(2, input_shape=(3,2)), RepeatVector(5)])inputs = [[[1,2], [3,4], [5,6]]]print(Model.predict(inputs))
这会产生以下输出:
[[[0.03203796 0.00486411][0.03203796 0.00486411][0.03203796 0.00486411][0.03203796 0.00486411][0.03203796 0.00486411]]]
现在看来,添加RepeatVector只是将相同的输出重复了n
次。如果RepeatVector只是将输出重复n
次,那么这是否意味着RepeatVector(n)
与将输出自身拼接n
次是相同的呢?
回答:
根据RepeatVector
和concatenate
的文档,其中一个区别是输出形状。
对于RepeatVector
,输出形状为:(num_samples, n, features)
对于concatenate
,输出形状为:(num_samples, features*n)
(如果axis=-1
)
让我们来可视化一下。这里是一些虚拟输入:
import tensorflow as tfx = tf.reshape(tf.range(1, 10), (3, 3))
<tf.Tensor: shape=(3, 3), dtype=int32, numpy=array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])>
让我们重复这个向量:
tf.keras.layers.RepeatVector(n=3)(x)
<tf.Tensor: shape=(3, 3, 3), dtype=int32, numpy=array([[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[4, 5, 6], [4, 5, 6], [4, 5, 6]], [[7, 8, 9], [7, 8, 9], [7, 8, 9]]])>
让我们进行拼接:
tf.keras.layers.concatenate([x, x, x])
<tf.Tensor: shape=(3, 9), dtype=int32, numpy=array([[1, 2, 3, 1, 2, 3, 1, 2, 3], [4, 5, 6, 4, 5, 6, 4, 5, 6], [7, 8, 9, 7, 8, 9, 7, 8, 9]])>
另一个区别当然是重复和拼接之间的概念差异。
重复:
[0, 0, 0, 1, 1, 1, 2, 2, 2]
拼接:
[0, 1, 2, 0, 1, 2, 0, 1, 2]