Keras自定义损失函数具有5个参数错误:“函数”对象没有属性“ get_shape”

时间:2019-03-25 14:02:15

标签: python keras deep-learning

我必须在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'])

0 个答案:

没有答案