pyod icon indicating copy to clipboard operation
pyod copied to clipboard

How to save VAE model

Open csyuhao opened this issue 2 years ago • 8 comments

I have a problem when I want to save the VAE model after the training. This is because this

z = Lambda(self.sampling, output_shape=(self.latent_dim,))(
    [z_mean, z_log])

Specifically, the Lambda layer cannot be saved into file. Could you give me any advice to save it?

csyuhao avatar Aug 07 '21 02:08 csyuhao

I just searched around and realize lambda layer is very fragile. we will have to replace that with a custom layer.

yzhao062 avatar Aug 15 '21 16:08 yzhao062

for self-reference: https://github.com/keras-team/keras/issues/6442

yzhao062 avatar Aug 15 '21 16:08 yzhao062

I solve this problem. While saving the paramters of VAE model, I also save the the initial parameters of VAE class at the same time.

csyuhao avatar Aug 24 '21 06:08 csyuhao

I can't save Deep svdd model, Could you tell me how you saved VAE model?

bai-by avatar Sep 10 '21 08:09 bai-by

As the poster of the issue said, you save the model first, then you save the class.

In the VAE class, there is a build model function. In fit function, it calls the build model function and assign it to self.model_. What you need to do is that you first use keras.save to save the self.model_. Then you make self.model_ = None. Then you can joblib.dump the whole class.

When you load, you first use joblib.load to load the class, then you use keras.load to load self.model_. And you put self.model_ inside the class.

But this will cause error. As I searched, when you are loading the keras model, you need to load the custome Lamda function inside the Lamda layer which is self.sampling. So what you need to do is that copy the self.sampling function in your file, and load it using custome object.

The order looks like this: Save: your VAE class.model_.save() your VAE class.model_ = None

joblib.dump(your VAE class, path)

Load: another VAE class = joblib.load(path) another VAE class.model_ = keras.models.load_model(path, custom_objects={'sampling': sampling})

It works for me. But it needs some testing. At least there is no error saving and loading.

jjjzy avatar Sep 10 '21 20:09 jjjzy

@jjjzy Thanks for this information. This sounds like a workaround for now.

yzhao062 avatar Sep 13 '21 00:09 yzhao062

Thanks for your help.

bai-by avatar Sep 13 '21 01:09 bai-by

I solve this problem. While saving the paramters of VAE model, I also save the the initial parameters of VAE class at the same time.

兄弟,能分享下代码吗谢谢

BlingBlingss avatar Dec 28 '21 07:12 BlingBlingss