检测张量流保存模型的第一个/最后一个通道?

Art*_*yom 6 inference tensorflow

有没有办法检测加载为 TF 保存模型的第一个或最后一个格式的通道model=tf.saved_model.load(path)

在 Keras 中,可以model.layers检查层 ll.data_format == 'channels_last'

TF保存的模型有这样的东西吗?我找不到任何合适的 TF 模型细节文档——一切都可以追溯到 Keras。

Yao*_*ang 0

我确信有比这更好的答案,但如果我只是想快速解决这个问题......

如果我已经知道图像尺寸,我会尝试

# Arrange.

tf.saved_model.save(tf.keras.applications.MobileNet(),'/path/to/dir') 
m=tf.saved_model.load('/path/to/dir')
image_size = (224,224) # 

# Act
try:
  m(tf.zeros((1,) + image_size + (3,))
  format='channels_last'
except ValueError:
  try:
    m(tf.zeros((1,3) + image_size)
    format='channels_first'
  except ValueError:
    raise ValueError('input shape is neither None,224,224,3 nor None,3,224,224')
Run Code Online (Sandbox Code Playgroud)

如果我不知道图像尺寸,我会考虑:

  1. 循环使用 29x29、32x32、224x224、256x256 和 299x299 等常见尺寸。

  2. 强力搜索所有 2 ** 20 个图像尺寸组合,最高可达 1024x1024

  3. 使用正则表达式调用m(None)并解析 ValueError 中的 str。它打印出输入形状的 TensorSpec:

>>> m(tf.zeros((1,1,1,3)))
Traceback (most recent call last):
[...]
ValueError: Could not find matching function to call loaded from the SavedModel. Got:
  Positional arguments (3 total):
    * Tensor("inputs:0", shape=(1, 1, 1, 3), dtype=float32)
    * False
    * None
  Keyword arguments: {}

Expected these arguments to match one of the following 4 option(s):

Option 1:
  Positional arguments (3 total):
    * TensorSpec(shape=(None, 224, 224, 3), dtype=tf.float32, name='input_1')
    * True
    * None
  Keyword arguments: {}

Option 2:
  Positional arguments (3 total):
    * TensorSpec(shape=(None, 224, 224, 3), dtype=tf.float32, name='input_1')
    * False
    * None
  Keyword arguments: {}

Option 3:
  Positional arguments (3 total):
    * TensorSpec(shape=(None, 224, 224, 3), dtype=tf.float32, name='inputs')
    * True
    * None
  Keyword arguments: {}

Option 4:
  Positional arguments (3 total):
    * TensorSpec(shape=(None, 224, 224, 3), dtype=tf.float32, name='inputs')
    * False
    * None
  Keyword arguments: {}
Run Code Online (Sandbox Code Playgroud)