我必须在Keras中编写具有5个参数的自定义损失函数。阅读一些解决方法后,我决定使用内部函数,如下所示:
W = 5
def mycrossentropy(W, W_pre, lam=0.03):
def loss(y_true, y_pre):
loss_1 = K.categorical_crossentropy(y_true, y_pre)
loss_2 = lam*((K.sum(W_pre) - W)**2)
return loss_1 + loss_2
return loss
当我想用keras.model.load_model
加载模型时,我得到了AttributeError:执行model.compile函数时'function'对象没有属性'get_shape'错误。整个错误输出如下:
Traceback (most recent call last):
File "d:/_Learning/_Code/AutoEncoder_Binary/AutoEncoder_Sq.py", line 105, in <module>
autoencoder = load_model("autoencoder.h5",custom_objects={"delta":delta,"loss":mycrossentropy})
File "D:\Anaconda3\lib\site-packages\keras\engine\saving.py", line 419, in load_model
model = _deserialize_model(f, custom_objects, compile)
File "D:\Anaconda3\lib\site-packages\keras\engine\saving.py", line 312, in _deserialize_model
sample_weight_mode=sample_weight_mode)
File "D:\Anaconda3\lib\site-packages\keras\engine\training.py", line 342, in compile
sample_weight, mask)
File "D:\Anaconda3\lib\site-packages\keras\engine\training_utils.py", line 417, in weighted
ndim = K.ndim(score_array)
File "D:\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py", line 619, in ndim
dims = x.get_shape()._dims
AttributeError: 'function' object has no attribute 'get_shape'
编译部分:
model.compile(loss=[mycrossentropy(W=W, W_pre=model.layers[3].output)],
optimizer=optimizer,
metrics=['accuracy'])