如何在 Tensorflow 中使用自定义模型保存自定义属性?

How to save custom attributes with custom model in Tensorflow?

目标

我正在尝试使用 subclassing 方法在 Tensorflow 中创建自定义模型。我的目标是创建其中包含一些自定义属性的模型,训练它,保存它并在加载后获取模型中自定义属性的值。

我一直在网上寻找解决方案,但我没有找到任何关于这个问题的信息。

问题

我创建了测试自定义模型 class,其中包含 self.custom_att 属性,这是一个列表。我已经用随机数据对其进行了训练,保存并加载。 加载模型后,属性本身在模型对象中,但已更改为ListWrapper对象并且为空。

问题

如何存储此属性,以便保留保存过程之前和加载过程之后的值?

代码

from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense
import numpy as np
from tensorflow.keras.models import load_model


class CustomModel(Model):

    def __init__(self):
        super(CustomModel, self).__init__()
        self.in_dense = Dense(10, activation='relu')
        self.dense = Dense(30, activation='relu')
        self.out = Dense(3, activation='softmax')
        self.custom_att = ['custom_att1', 'custom_att2'] # <- this attribute I want to store

    def call(self, inputs, training=None, mask=None):
        x = self.in_dense(inputs)
        x = self.dense(x)
        x = self.out(x)
        return x

    def get_config(self):
        base_config = super(CustomModel, self).get_config()
        return {**base_config, 'custom_att': self.custom_att}


X = np.random.random((1000, 5))
y = np.random.random((1000, 3))

model = CustomModel()
model.build((1, 5))
model.compile(optimizer='adam', loss='mse', metrics=['accuracy'])
model.summary()
history = model.fit(X, y, epochs=1, validation_split=0.1)
model.save('models/testModel.model')

del model

model = load_model('models/testModel.model', custom_objects={'CustomModel': CustomModel}) # <- here attribute becomes ListWrapper([])
print(model.custom_att)

环境

我不认为在加载模型时使用列表会起作用。替换

self.custom_att = ['custom_att1', 'custom_att2']

self.custom_att = tf.Variable(['custom_att1', 'custom_att2'])

你应该看到这样的东西:

print(model.custom_att.numpy())
# [b'custom_att1' b'custom_att2']

您可以像这样删除字符串中的 b 文字:

print(model.custom_att.numpy()[0].decode("utf-8"))
# custom_att1