在Keras顺序模块中保存和加载Tensorflow概率层

时间:2019-10-07 13:42:40

标签: tensorflow keras tensorflow-probability

我在Keras序列中使用Tensorflow概率层。但是,将模型另存为json,然后加载它会引发异常。我正在使用Launching lib/main.dart on iPhone 11 Pro Max in debug mode... Compiler message: lib/main.dart:52:35: Error: Method not found: 'nativeAdd'. child: Text('1 + 2 == ${nativeAdd(1, 2)}'), ^^^^^^^^^ lib/main.dart:52:35: Error: The method 'nativeAdd' isn't defined for the class '_MyAppState'. - '_MyAppState' is from 'package:native_add_example/main.dart' ('lib/main.dart'). Try correcting the name to the name of an existing method, or defining a method named 'nativeAdd'. child: Text('1 + 2 == ${nativeAdd(1, 2)}'), ^^^^^^^^^ Compiler failed on /Users/me/Desktop/_dev/playground/flutter/flutter_firstflutterapp_part2/native_add/example/lib/main.dart Error launching application on iPhone 11 Pro Max. 来加载自定义图层。 这是再现错误的简单代码。

custom_objects

我收到以下异常:

import tensorflow_probability as tfp

tfk = tf.keras
tfkl = tf.keras.layers
tfpl = tfp.layers

original_dim = 20
latent_dim = 2
model = tfk.Sequential([
    tfkl.InputLayer(input_shape=original_dim),
    tfkl.Dense(10, activation=tf.nn.leaky_relu),
    tfkl.Dense(tfpl.MultivariateNormalTriL.params_size(latent_dim), activation=None),
    tfpl.MultivariateNormalTriL(latent_dim)
])

model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)



loaded_model = tfk.models.model_from_json(
    open('model.json').read(),
    custom_objects={
        'leaky_relu': tf.nn.leaky_relu, 
        'MultivariateNormalTriL': tfpl.MultivariateNormalTriL
    }
)

2 个答案:

答案 0 :(得分:0)

查看以下加载方法是否有效:

loaded_model = tfk.models.model_from_json(
    open('model.json').read(),
    custom_objects={
        'leaky_relu': tf.nn.leaky_relu, 
        'MultivariateNormalTriL': tfpl.MultivariateNormalTriL.params_size(latent_dim)
    }
)

答案 1 :(得分:0)

我有同样的问题。我通过将其添加到custom_objects

来解决它
    def MultivariateNormalTriL_loader(latent_dim):
        def load_MultivariateNormalTriL(name, trainable, type, 
                                        function, function_type, module, 
                                        output_shape, output_shape_type,  
                                        output_shape_module, arguments, 
                                        make_distribution_fn, convert_to_tensor_fn):
            return tfp.layers.MultivariateNormalTriL(latent_dim, name=name, 
                                          trainable=trainable, dtype=dtype, 
                                          convert_to_tensor_fn=convert_to_tensor_fn)
        return load_MultivariateNormalTriL
    # Use the latent_dim here
    custom_objects['MultivariateNormalTriL'] = MultivariateNormalTriL_loader(latent_dim)

我不确定需要哪些参数,但是这些参数对我有用。