Python 在keras自定义对象中加载预先训练的注意模型
我正在使用Python 在keras自定义对象中加载预先训练的注意模型,python,keras,pre-trained-model,attention-model,Python,Keras,Pre Trained Model,Attention Model,我正在使用load\u model()在Keras中加载一个预训练注意力模型 我的注意课程定义如下 # attention class from keras.engine.topology import Layer from keras import initializers, regularizers, constraints from keras import backend as K class Attention(Layer): def __init__(self, ste
load\u model()
在Keras中加载一个预训练注意力模型
我的注意
课程定义如下
# attention class
from keras.engine.topology import Layer
from keras import initializers, regularizers, constraints
from keras import backend as K
class Attention(Layer):
def __init__(self, step_dim, w_regularizer=None, b_regularizer=None,
w_constraint=None, b_constraint=None, bias=True, **kwargs):
self.supports_masking = True
# weight initializer
self.init = initializers.get('glorot_uniform')
self.w_regularizer = regularizers.get(w_regularizer)
self.b_regularizer = regularizers.get(b_regularizer)
self.w_constraint = constraints.get(w_constraint)
self.b_constraint = constraints.get(b_constraint)
self.bias = bias
self.step_dim = step_dim
self.features_dim = 0
super(Attention, self).__init__(**kwargs)
def build(self, input_shape):
assert len(input_shape) == 3
self.w = self.add_weight(shape=(input_shape[-1],),
initializer=self.init, name='{}_w'.format(self.name),
regularizer=self.w_regularizer,
constraint=self.w_constraint)
self.features_dim = input_shape[-1]
if self.bias:
self.b = self.add_weight(shape=(input_shape[1],),
initializer='zero', name='{}_b'.format(self.name),
regularizer=self.b_regularizer,
constraint=self.b_constraint)
else:
self.b = None
self.built = True
def compute_mask(self, input, input_mask=None):
return None
def call(self, x, mask=None):
features_dim = self.features_dim
step_dim = self.step_dim
eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)),
K.reshape(self.w, (features_dim, 1))), (-1, step_dim))
if self.bias:
eij += self.b
eij = K.tanh(eij)
a = K.exp(eij)
if mask is not None:
a *= K.cast(mask, K.floatx())
a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())
a = K.expand_dims(a)
weighted_input = x * a
return K.sum(weighted_input, axis=1)
def compute_output_shape(self, input_shape):
return input_shape[0], self.features_dim
def get_config(self):
config = {
'step_dim': self.step_dim,
'w_regularizer': self.w_regularizer,
'w_constraint': self.w_constraint,
'b_regularizer': self.b_regularizer,
'b_constraint': self.b_constraint,
'bias': self.bias
}
base_config = super(Attention, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
该模型在test\u loadmod.py
as中调用
from attention import Attention
from keras.models import load_model
model = load_model('attention_wo_cval.h5', custom_objects={'Attention': Attention})
print(model)
使用load_model()
可以使用自定义注意模型,并且custom_objects
会按所述传递到该模型中
但是,它似乎找不到步骤dim
属性。抛出下面的错误。你知道怎么做吗?谢谢你的时间和帮助
加载时出错
TypeError:\uuuu init\uuuuuu()缺少1个必需的位置参数:“step\u dim”
File "test_loadmod.py", line 4, in <module>
model = load_model('attention_wo_cval.h5', custom_objects={'Attention': Attention})
File "C:\Users\RV\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\engine\saving.py", line 492, in load_wrapper
return load_function(*args, **kwargs)
File "C:\Users\RV\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\engine\saving.py", line 584, in load_model
model = _deserialize_model(h5dict, custom_objects, compile)
File "C:\Users\RV\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\engine\saving.py", line 274, in _deserialize_model
model = model_from_config(model_config, custom_objects=custom_objects)
File "C:\Users\RV\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\engine\saving.py", line 627, in model_from_config
return deserialize(config, custom_objects=custom_objects)
File "C:\Users\RV\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\layers\__init__.py", line 165, in deserialize
return deserialize_keras_object(config,
File "C:\Users\RV\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\utils\generic_utils.py", line 144, in deserialize_keras_object
return cls.from_config(
File "C:\Users\RV\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\engine\network.py", line 1056, in from_config
process_layer(layer_data)
File "C:\Users\RV\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\engine\network.py", line 1041, in process_layer
layer = deserialize_layer(layer_data,
File "C:\Users\RV\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\layers\__init__.py", line 165, in deserialize
return deserialize_keras_object(config,
File "C:\Users\RV\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\utils\generic_utils.py", line 149, in deserialize_keras_object
return cls.from_config(config['config'])
File "C:\Users\RV\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\engine\base_layer.py", line 1179, in from_config
return cls(**config)
TypeError: __init__() missing 1 required positional argument: 'step_dim'
文件“test_loadmod.py”,第4行,在
模型=加载模型('attention\u wo\u cval.h5',自定义对象={'attention':attention})
文件“C:\Users\RV\AppData\Local\Programs\Python38\lib\site packages\keras\engine\saving.py”,第492行,在load\u包装中
返回加载函数(*args,**kwargs)
文件“C:\Users\RV\AppData\Local\Programs\Python38\lib\site packages\keras\engine\saving.py”,第584行,在load\u模型中
model=\反序列化\模型(h5dict,自定义\对象,编译)
文件“C:\Users\RV\AppData\Local\Programs\Python38\lib\site packages\keras\engine\saving.py”,第274行,在反序列化模型中
模型=来自配置的模型(模型配置,自定义对象=自定义对象)
文件“C:\Users\RV\AppData\Local\Programs\Python38\lib\site packages\keras\engine\saving.py”,第627行,位于\u config的模型\u中
返回反序列化(配置,自定义对象=自定义对象)
文件“C:\Users\RV\AppData\Local\Programs\Python\38\lib\site packages\keras\layers\uuuuu init\uuuuu.py”,第165行,反序列化
返回反序列化对象(配置,
文件“C:\Users\RV\AppData\Local\Programs\Python\38\lib\site packages\keras\utils\generic\u utils.py”,第144行,反序列化\u keras\u对象
从配置返回cls(
文件“C:\Users\RV\AppData\Local\Programs\Python38\lib\site packages\keras\engine\network.py”,第1056行,from\u config
处理层(层数据)
文件“C:\Users\RV\AppData\Local\Programs\Python38\lib\site packages\keras\engine\network.py”,第1041行,进程层
层=反序列化层(层数据,
文件“C:\Users\RV\AppData\Local\Programs\Python\38\lib\site packages\keras\layers\uuuuu init\uuuuu.py”,第165行,反序列化
返回反序列化对象(配置,
文件“C:\Users\RV\AppData\Local\Programs\Python\38\lib\site packages\keras\utils\generic\u utils.py”,第149行,在反序列化\u keras\u对象中
从_config(config['config'])返回cls
文件“C:\Users\RV\AppData\Local\Programs\Python38\lib\site packages\keras\engine\base\u layer.py”,第1179行,在from\u config中
返回cls(**配置)
TypeError:\uuuuu init\uuuuuu()缺少1个必需的位置参数:“step\u dim”
get\u config方法是正确的解决方案,但在更新此方法时,必须注意保存模型。
因此:
如果你在超级调用中传递
super(注意,self)的step\u dim
。\uu init\uuuugs(**kwargs)
?不起作用。如果我传递类似super(注意,self.step\dim)的东西,我的训练思路也会出错。\uu init\uugs(**kwargs)
你用模型的这个精确代码保存了模型吗?(我的意思是-使用get_config方法)。@Thelletz你是对的。我想我在保存模型时弄糟了。谢谢你的提示。@der_radler,太好了!所以我将添加它作为答案,请批准它,这样它将帮助其他用户:)