我在 Python 中有以下示例代码:
import tensorflow as tf
# Create a tensor of shape (14, 2)
x = tf.constant([[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 10],
[11, 12],
[13, 14],
[15, 16],
[17, 18],
[19, 20],
[21, 22],
[23, 24],
[25, 26],
[27, 28]])
# Flatten the tensor
y = tf.keras.layers.Flatten()(x)
print(x)
print(y)
现在我期望从此代码得到的输出如下:
tf.Tensor(
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]
[11 12]
[13 14]
[15 16]
[17 18]
[19 20]
[21 22]
[23 24]
[25 26]
[27 28]], shape=(14, 2), dtype=int32)
tf.Tensor([ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28], shape=(28,), dtype=int32)
但我得到的不是这个,而是以下输出:
tf.Tensor(
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]
[11 12]
[13 14]
[15 16]
[17 18]
[19 20]
[21 22]
[23 24]
[25 26]
[27 28]], shape=(14, 2), dtype=int32)
tf.Tensor(
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]
[11 12]
[13 14]
[15 16]
[17 18]
[19 20]
[21 22]
[23 24]
[25 26]
[27 28]], shape=(14, 2), dtype=int32)
这表明 Flatten 层对初始张量完全没有影响
x
.
请帮助我理解为什么会这样。提前谢谢你。
@xdurch0
发表的评论暗示解决方案是简单地在初始常量张量周围添加另一个方括号[]
,像这样:
import tensorflow as tf
# Create a tensor of shape (1, 14, 2)
x = tf.constant([[[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 10],
[11, 12],
[13, 14],
[15, 16],
[17, 18],
[19, 20],
[21, 22],
[23, 24],
[25, 26],
[27, 28]]])
# Flatten the tensor
y = tf.keras.layers.Flatten()(x)
print(x)
print(y)
所以现在输入的形状是
(1, 14, 2)
。这奏效了。感谢您的评论。我发布了答案,这样可以帮助其他人陷入同样的问题。