当使用 Python Tensorflow 输入形状 (53,))... 这个逗号是怎么回事?

When using Python Tensorflow input shape (53,))... what's going on with this comma?

我对以下代码行感到困惑:

input_img = Input(shape=(53,))

我有一批 52 张图像,但是一个元组怎么能在逗号后没有任何内容呢?这是什么意思?

它与标量相同,但被解释为形状。

如果你感到困惑,你可以看看列表如何滥用它,例如:

print([
       0,
       1,
       2,  # <- This comma is unnecessary but won't break your code
])

[0, 1, 2]

函数 Input 除了参数 shape

的一个元组

使用逗号可以定义包含单个项目的元组。如果您只是使用 (53) 或 53,它将被解释为一个整数:

type( 53 )
<class 'int'>
type( (53) )
<class 'int'>
type( (53,) )
<class 'tuple'>

这是因为在计算中使用了简单的括号,因此无法解析为元组:

(53) + 2 # would raise an error if (53) was a tuple
(53 + 1)*2 # would also raise an error if (53+1) was a tuple

所以为了用单个项目定义一个元组,你必须添加逗号:(53,)