如何仅通过导入模块来加载模型及其常量?

时间:2019-07-22 16:25:39

标签: python tf.keras

我想通过导入将模型及其常量加载到该模块的模块自动加载到模块中,就像这样:

model.py中:

import pickle

from tensorflow import keras

def load_model_vars():
    return pickle.load(open('./file.pkl', 'rb'))

def load_model():
    return keras.models.load_model('./model.h5')

# model needs these two constants to be loaded successfully
a, b = load_model_vars()
model = load_model()

another.py中,将model.py导入到其中,以及将在其中使用模型的地方:

from model import *

if __name__ == '__main__':
        results = use_model(model, input)

但是,我总是会遇到一个错误,即模型找不到这两个变量,而且我也找不到原因。

我尝试使用全局或局部变量,但是模型仍然找不到这两个变量,导致无法成功加载。

到目前为止,这是我的一些尝试:

model.py中:

import pickle

from tensorflow import keras

def load_model()

    constants = pickle.load(open('./file.pkl', 'rb'))

    # these three doesn't work, and model throws an error saying these weren't defined; why?    
    a = constants[0]
    b = constants[1]

    globals()['a'] = constants[0]
    globals()['b'] = constants[1]

    # these causes another error
    locals()['a'] = constants[0]
    locals()['b'] = constants[1]

    globals()['model'] = keras.models.load_model('./model.h5')

load_model()

another.py中,该模型仍会查找两个变量,即使已将其加载到另一个模块中,也会引发错误,并且我找不到指向它的方法。

这是我当前解决此问题的方法:

model.py中:

import pickle

from tensorflow import keras

def load_model_vars():
    return pickle.load(open('./file.pkl', 'rb'))

def load_model():
    return keras.models.load_model('./model.h5')

another.py中:

from model import load_model_vars, load_model

if __name__ == '__main__':  
        a, b = load_model_vars()
        model = load_model()

        # model loaded from file by load_model() requires a and b to be initialized, 
        # or it will raise a NameError: name 'a' is not defined
        # model is then used here:
        results = use_model(model, input_data)

基本上,我希望有一种方法可以在模块中加载模型所需的变量和模型本身,并公开已加载的模型以供其他模块使用。

编辑: 我想对这些变量进行建模的方式与此相同:

a.py中:

def load_variables():
    globals()['foo'] = 42
    globals()['bar'] = 21

load_variables()

b.py中:

import a

print(a.foo)

但是模型需要上述变量才能成功加载。

0 个答案:

没有答案