当索引tf.shape(张量)的结果时,张量形状似乎消失了



当我试图对tf.shape(tensor)的结果进行索引时,其中tensor是某个张量,结果似乎意外地变成了None。例如,我运行了以下代码:

>>> from ray.rllib.models.utils import try_import_tf
>>> tf1, tf, tfv = try_import_tf() 
>>> tf.compat.v1.enable_eager_execution()  
>>> inp = tf.keras.layers.Input(shape=([19, 33, 1]), name='input')
>>> tf.shape(inp)
<KerasTensor: shape=(4,) dtype=int32 inferred_value=[None, 19, 33, 1] (created by layer 'tf.compat.v1.shape')>

结果如预期。然而,当我接下来尝试运行以下代码时:

>>> tf.shape(inp)[0]
<KerasTensor: shape=() dtype=int32 inferred_value=[None] (created by layer 'tf.__operators__.getitem')>
>>> tf.shape(inp)[1]
<KerasTensor: shape=() dtype=int32 inferred_value=[None] (created by layer 'tf.__operators__.getitem_1')>
>>> tf.shape(inp)[2]
<KerasTensor: shape=() dtype=int32 inferred_value=[None] (created by layer 'tf.__operators__.getitem_2')>
>>> tf.shape(inp)[3]
<KerasTensor: shape=() dtype=int32 inferred_value=[None] (created by layer 'tf.__operators__.getitem_3')>

推断出的值均为None。这是怎么回事?这是预期的行为吗?

给定的代码与Tensorflow 2.8.0 一起工作

import tensorflow as tf
print(tf.__version__)
inp = tf.keras.layers.Input(shape=([19, 33, 1]), name='input')
tf.shape(inp)
2.8.0
<KerasTensor: shape=(4,) dtype=int32 inferred_value=[None, 19, 33, 1] (created by layer 'tf.compat.v1.shape_5')>
>>tf.shape(inp)[0]
<KerasTensor: shape=() dtype=int32 inferred_value=[None] (created by layer 'tf.__operators__.getitem')>
>>tf.shape(inp)[1]
<KerasTensor: shape=() dtype=int32 inferred_value=[19] (created by layer 'tf.__operators__.getitem_1')>
>>tf.shape(inp)[2]
<KerasTensor: shape=() dtype=int32 inferred_value=[33] (created by layer 'tf.__operators__.getitem_2')>
>>tf.shape(inp)[3]
<KerasTensor: shape=() dtype=int32 inferred_value=[1] (created by layer 'tf.__operators__.getitem_3')>

相关内容

  • 没有找到相关文章

最新更新