python - Tensorflow keras model.save 使用自定义层引发 InaccessibleTensorError
问题描述
我有一个自定义 keras 模型(使用tf.keras.model
/functional api),我需要为其保存权重和模型架构(使用keras.Model.save
)。
该模型使用标准 keras 组件,如密集、扁平等和一个特定的自定义层:
class NormalizationLayer(tf.keras.layers.Layer):
def __init__(self, name=None, axis=1):
super(NormalizationLayer, self).__init__(name=name)
self.max = None
self.axis = axis
def build(self, input_shape):
pass
def call(self, inputs, inverse=False):
if inverse:
return tf.transpose(tf.math.multiply(tf.transpose(inputs), self.max))
else:
self.max = tf.reduce_max(inputs, axis=self.axis)
if self.axis == 1:
return tf.transpose(tf.math.divide_no_nan(tf.transpose(inputs), self.max))
else:
return tf.math.divide_no_nan(inputs, self.max)
def get_config(self):
custom_config = {'max': self.max,
'axis': self.axis}
base_config = super(NormalizationLayer, self).get_config()
base_config.update(custom_config)
return base_config
get_config
当我首先遇到问题时,我已经添加了该方法。不幸的是,在尝试使用 保存模型时model.save
,我遇到了以下错误:
tensorflow.python.framework.errors_impl.InaccessibleTensorError: The tensor 'Tensor("Max:0", shape=(None,), dtype=float32)' cannot be accessed here: it is defined in another function or code block. Use return values, explicit Python locals or TensorFlow collections to access it. Defined in: FuncGraph(name=input_normalization_layer_call_and_return_conditional_losses, id=140460908747216); accessed from: FuncGraph(name=model_layer_call_and_return_conditional_losses, id=140460638991312)
我的方法总体上是错误的,还是我监督了什么。已经尝试添加@tf.function
-decorator,但遇到了类似的问题。model.save_weights()
按预期保存权重。
我正在使用 tensorflow==2.2.0rc4。
感谢您提前提供任何帮助评论。
解决方案
推荐阅读
- linux - Linux 命令行:id、group 和 getent group 不返回相同的结果
- ruby-on-rails - 具有多个实例的 Rails 迁移
- java - 在 groovy 上包含转义斜杠的文字字符串
- arrays - 获取数组 lop 中的所有 json 值
- firebase - Cloud Functions for Firebase - 检索已部署的代码?
- python - 在 Windows 上使用 sys.path.append for C:\... in IDLE
- html - 无法在css中居中导航栏
- python - 从 python 列表中获取特定元素的索引
- firebase - Firestore:如何按数组对象的字段使用顺序
- linq - 将 varchar 值“Zon7”转换为数据类型 int 时转换失败