【问题标题】:TypeError: ('Not JSON Serializable:', <tf.Tensor: shape=(), dtype=float32, numpy=123.0>)TypeError: ('Not JSON Serializable:', <tf.Tensor: shape=(), dtype=float32, numpy=123.0>)
【发布时间】:2020-10-14 11:43:40
【问题描述】:

我有一个 production 模型,可以通过 ModelConfig 进行配置,我自己写了一个 class Config(dict)。在那个ModelConfig 中,我正在设置hidden_size=123。以下是我的生产模型代码的简化:

class Config(dict):
  # ..

  def as_dict(self) -> dict:
    return self._serialize()

class ModelConfig(Config):
  hidden_size: int = 123

现在,我有一个自定义的 keras 模型,它是这样实现的:

class MyModel(keras.Model):

  def __init__(self, config: ModelConfig):
    self.config = config

    self.dense = layers.Dense(config.hidden_size)
    # ...

  def get_config():
    return self.config.as_dict()

除了调用MyModel#save之外,一切正常:

model.save(model_path, save_format='tf')

我收到TypeError 说:

TypeError: ('Not JSON Serializable:', <tf.Tensor: shape=(), dtype=float32, numpy=123.0>)

我知道 ModelConfig#hidden_size 是这里成为张量/EagerTensor 的属性。

这里奇怪的是,在我的一个测试脚本中,一切都按预期工作。我创建它是为了查看Config 是否会导致save() 出现问题,但情况似乎并非如此:

因此,此处按预期工作:

import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

from config import Config


class ModelConfig(Config):
    hidden_size: int = 123


class MyLayer(layers.Layer):

    def __init__(self, config, other=None, **kwargs):
        super().__init__(**kwargs)
        self.config = config
        self.other = other if other is not None else None
        self.dense = layers.Dense(config.hidden_size + 1)

    def call(self, inputs, **kwargs):
        x = self.other(inputs, **kwargs) if self.other is not None else inputs
        return self.dense(x, **kwargs)


class MyModel(keras.Model):

    def __init__(self, config: ModelConfig, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.config = config
        self.other = MyLayer(config, other=MyLayer(config))
        self.dense = layers.Dense(config.hidden_size)

    def call(self, inputs, **kwargs):
        x = self.dense(inputs, **kwargs)
        return self.other(x, **kwargs)

    def get_config(self):
        return self.config.to_dict()

    @tf.function(
        input_signature=[tf.TensorSpec(shape=(None, 100))]
    )
    def infer(self, inputs):
        return self.call(inputs)


def main():
    fp = '/tmp/mymodel'
    config = ModelConfig()
    model = MyModel(config)
    model(np.random.rand(1, 100))
    model.save(fp, save_format='tf')
    model = tf.saved_model.load(fp)
    print(model.infer(np.random.rand(1, 100)))

    print('All done.')


if __name__ == '__main__':
    main()

这意味着问题不是 Config 对象,而是由于某种原因在我的生产模型中,它的一个属性导致它在调用 save() 时失败。

这可能是个大问题,但有人知道在哪里寻找问题吗?

在一种情况下,该属性变为无法序列化的 Tensor/EagerTensor(这是有道理的),而在测试脚本的情况下,它仍然是一个 int,可以按预期工作..

我也试过tf.saved_model.save,结果相同。

【问题讨论】:

    标签: tensorflow keras tensorflow2.0


    【解决方案1】:

    我猜是 tf.Tensor 不是 JSON 可序列化的。 您可以尝试将 tf.Tensor 的对象转换为 numpy 数组,然后您应该能够保存配置以供以后重新加载。

    【讨论】:

      猜你喜欢
      • 2021-10-17
      • 2021-03-12
      • 2021-09-13
      • 2020-11-16
      • 2019-06-15
      • 1970-01-01
      • 2021-09-19
      • 2021-04-05
      • 1970-01-01
      相关资源
      最近更新 更多