我正在努力保存 tf.keras 模型以轻松加载并能够使用它。我已经使用 tf.keras.Model 子类方法构建了一个带有自定义损失函数的 MLP 模型,如下所示:
class MyModel(tf.keras.Model):
def __init__(self):
super(MyModel, self).__init__()
self.dense1 = Dense(400, activation='relu', kernel_initializer=initializers.glorot_uniform(), input_dim=5)
self.dense2 = Dense(400, activation='relu', kernel_initializer=initializers.glorot_uniform())
self.dense3 = Dense(400, activation='relu', kernel_initializer=initializers.glorot_uniform())
self.dense4 = Dense(400, activation='relu', kernel_initializer=initializers.glorot_uniform())
self.dense_out = Dense(1, activation='relu', kernel_initializer=initializers.glorot_uniform())
@tf.function(input_signature=[tf.TensorSpec(shape=(None, 5), dtype=tf.float32, name='inputs')]) #CHECK tf.saved_model.save docs!
def call(self, inputs, **kwargs):
x = self.dense1(inputs)
x = self.dense2(x)
x = self.dense3(x)
x = self.dense4(x)
return self.dense_out(x)
def get_loss(self, X, Y):
with tf.GradientTape() as tape:
tape.watch(tf.convert_to_tensor(X))
Y_pred = self.call(X)
return tf.reduce_mean(tf.math.square(Y_pred-Y)) + tf.reduce_mean(tf.maximum(0, …Run Code Online (Sandbox Code Playgroud)