Keras中的load_model和Lamda层 [英] load_model and Lamda layer in Keras

查看:247
本文介绍了Keras中的load_model和Lamda层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何加载具有lambda层的模型?

How to load model that have lambda layer?

以下是重现行为的代码:

Here is the code to reproduce behaviour:

MEAN_LANDMARKS = np.load('data/mean_shape_68.npy')

def add_mean_landmarks(x):
    mean_landmarks = np.array(MEAN_LANDMARKS, np.float32)
    mean_landmarks = mean_landmarks.flatten()
    mean_landmarks_tf = tf.convert_to_tensor(mean_landmarks)
    x = x + mean_landmarks_tf
    return x

def get_model():
    inputs = Input(shape=(8, 128, 128, 3))
    cnn = VGG16(include_top=False, weights='imagenet', input_shape=(128, 128, 3))
    x = TimeDistributed(cnn)(inputs)
    x = TimeDistributed(Flatten())(x)
    x = LSTM(256)(x)
    x = Dense(68 * 2, activation='linear')(x)

    x = Lambda(add_mean_landmarks)(x)

    model = Model(inputs=inputs, outputs=x)
    optimizer = Adadelta()
    model.compile(optimizer=optimizer, loss='mae')

    return model

模型可以编译并且可以保存,但是当我尝试使用load_model函数加载它时,出现错误:

Model compiles and I can save it, but when I tried to load it with load_model function I get an error:

in add_mean_landmarks
    mean_landmarks = np.array(MEAN_LANDMARKS, np.float32)
NameError: name 'MEAN_LANDMARKS' is not defined

我了解MEAN_LANDMARKS并未作为常数张量并入图中.也与此问题有关:如何在Keras中添加恒定张量?

Аs I understand MEAN_LANDMARKS is not incorporated in graph as constant tensor. Also it's related to this question: How to add constant tensor in Keras?

推荐答案

您需要将custom_objects参数传递给load_model函数:

You need to pass custom_objects argument to load_model function:

model = load_model('model_file_name.h5', custom_objects={'MEAN_LANDMARKS': MEAN_LANDMARKS})

在Keras文档中查找更多信息:

Look for more info in Keras docs: Handling custom layers (or other custom objects) in saved models .

这篇关于Keras中的load_model和Lamda层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆