gpt4 book ai didi

python - Keras自定义损失函数报错: 'AttributeError: ' function' object has no attribute 'get_shape'

转载 作者:太空宇宙 更新时间:2023-11-04 00:29:35 26 4
gpt4 key购买 nike

我必须编写自己的自定义损失函数,这些损失函数可以采用 Keras 中 y_truey_pred 参数以外的不同输入。在阅读了一些解决方法后,我决定按如下方式使用内部函数:

from keras import backend as K

lambda_prn_regr = 0.6
lambda_prn_vis = 0.2
lambda_prn_class = 0.2

epsilon = 1e-4

# Person loss
def prn_loss_cls(y_true, y_pred):
def prn_loss_cls_fixed_num(y_true, y_pred):
# lambda * b_ce
return lambda_prn_class * K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1)
return prn_loss_cls_fixed_num

# Regression loss
def prn_loss_regr(num_joints):
def prn_loss_regr_fixed_num(y_true, y_pred):
# lambda * sum(vis * (pose_pred - pose_true)^2) / sum(vis)
return lambda_prn_regr * K.sum(y_true[:, :, :, :2*num_joints] * K.square(y_pred - y_true[:, :, :, 2*num_joints:])) / K.sum(y_true[:, :, :, :2*num_joints])
return prn_loss_regr_fixed_num

# Visibility Loss
def prn_loss_vis(y_true, y_pred):
def prn_loss_regr_fixed_num(y_true, y_pred):
return lambda_prn_vis * K.mean(K.square(y_pred - y_true), axis=-1)
return prn_loss_regr_fixed_num

三个不同的损失函数:每个都有权重,一个需要一个整数参数。

但是我在执行 model.compile 函数时遇到了 AttributeError: 'function' object has no attribute 'get_shape' 错误。整个错误输出如下:

Traceback (most recent call last):
File "train_mppn.py", line 97, in <module>
model_prn.compile(optimizer=optimizer, loss=[losses.prn_loss_cls, losses.prn_loss_regr(C.num_joints), losses.prn_loss_vis(C.num_joints)])
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 899, in compile
sample_weight, mask)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 441, in weighted
ndim = K.ndim(score_array)
File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 439, in ndim
dims = x.get_shape()._dims
AttributeError: 'function' object has no attribute 'get_shape'

编译部分:

model.compile(optimizer=optimizer, loss=[losses.prn_loss_cls, losses.prn_loss_regr(num_joints), losses.prn_loss_vis])

我找不到问题的根源。

最佳答案

您正在传递不返回值的函数,它们返回函数。

你在 num_joints 情况下这样做是可以理解的(而且你实际上是在调用那个函数),但在其他情况下这很奇怪,特别是因为你没有在任何地方调用它们来返回内部函数。

建议:

# Person loss
def prn_loss_cls(y_true, y_pred):
return lambda_prn_class * K.mean(K.binary_crossentropy(y_true,y_pred), axis=-1)


# Visibility Loss
def prn_loss_vis(y_true, y_pred):
return lambda_prn_vis * K.mean(K.square(y_pred - y_true), axis=-1)

关于python - Keras自定义损失函数报错: 'AttributeError: ' function' object has no attribute 'get_shape' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46327294/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com