使用自定义图层对象的Keras'load_model'

时间:2017-12-30 09:59:08

标签: python keras keras-layer

我有一个简单的自定义图层对象,可以通过cholesky分解生成多变量的正常噪声。一切正常,但'load_model'加载了'ModelCheckPoint'保存的最佳模型。

自定义图层是:

import kears as ks
import keras.backend as K


class MVGaussianNoise(Layer):
def __init__(self, sigma_ind=None, sigma_dep=None,
             noise_level=1.0, seed=None, **kwargs):

    self.sigma_ind = sigma_ind
    self.sigma_dep = sigma_dep
    self.noise_level = noise_level
    self.supports_masking = True
    self.seed = seed

    self._lut_ind = scipy.linalg.cholesky(self.sigma_ind)
    self._lut_dep = scipy.linalg.cholesky(self.sigma_dep)
    super(MVGaussianNoise, self).__init__(**kwargs)

def call(self, inputs, training=None):
    def noised():
        z_ind = K.random_normal(
            shape=K.shape(inputs),
            mean=0.0,
            seed=self.seed,
            stddev=1.0)
        noised_ind = self.noise_level * K.dot(z_ind, self._lut_ind)
        return inputs + noised_ind

    return K.in_train_phase(noised, inputs, training=training)

def get_config(self):
    config = {'sigma_ind': self.sigma_ind, 
              'sigma_dep': self.sigma_dep,
              'noise_level': self.noise_level,
              'seed': self.seed}
    base_config = super(MVGaussianNoise, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

这里'sigma_ind'和'sigma_dep'是'numpy.ndarray(float)'类型,用于定义协方差。

加载模型:

with ks.utils.CustomObjectScope({'MVGaussianNoise': MVGaussianNoise}):
    best_model = ks.models.load_model('best_model' + '.h5')

发出错误消息:

  .
  .
  .
  File "/home/aidin/miniconda3/envs/keras-theano/lib/python2.7/site-packages/keras/utils/generic_utils.py", line 141, in deserialize_keras_object
    return cls.from_config(config['config'])

  File "/home/aidin/miniconda3/envs/keras-theano/lib/python2.7/site-packages/keras/engine/topology.py", line 1252, in from_config
    return cls(**config)

  File "hsipydeep/keraskit/noise.py", line 99, in __init__
    self._lut_ind = scipy.linalg.cholesky(self.sigma_ind)

  File "/home/aidin/miniconda3/envs/keras-theano/lib/python2.7/site-packages/scipy/linalg/decomp_cholesky.py", line 91, in cholesky
    check_finite=check_finite)

  File "/home/aidin/miniconda3/envs/keras-theano/lib/python2.7/site-packages/scipy/linalg/decomp_cholesky.py", line 37, in _cholesky
    c, info = potrf(a1, lower=lower, overwrite_a=overwrite_a, clean=clean)

TypeError: float() argument must be a string or a number

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

在您的__init__函数中,您的sigma_ind参数的默认值为None,如果您不通过,这将是一个问题初始化期间sigma_ind,因为scipy.linalg.cholesky期望值。

答案 1 :(得分:0)

I solved this by changing the data type to 'python.array', seem Keras can not handle numpy.array input args through model loading.