`tf.keras.layers.Flatten()` 由于某些奇怪的原因无法正常工作

问题描述 投票:0回答:1

我在 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
.

请帮助我理解为什么会这样。提前谢谢你。

python tensorflow keras reshape flatten
1个回答
0
投票

@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)
。这奏效了。感谢您的评论。我发布了答案,这样可以帮助其他人陷入同样的问题。

© www.soinside.com 2019 - 2024. All rights reserved.