问题描述
我正在尝试为三元组损失编写一个自定义损失函数(使用 keras),它需要 3 个参数锚点,正负。三元组使用 gru 层生成,model.fit 的参数通过数据生成器提供。
我面临的问题是训练时:
TypeError: Cannot convert a symbolic Keras input/output to a numpy array.
This error may indicate that you're trying to pass a symbolic value to a NumPy
call,which is not supported. Or,you may be trying to pass Keras symbolic
inputs/outputs to a TF API that does not register dispatching,preventing Keras from automatically
converting the API call to a lambda layer in the Functional Model.
损失函数的实现
def batch_hard_triplet_loss(self,anchor_embeddings,pos_embeddings,neg_embeddings,margin):
def loss(y_true,y_pred):
'''print(anchor_embeddings)
print(pos_embeddings)
print(neg_embeddings)'''
# distance between the anchor and the positive
pos_dist = K.sum(K.square(anchor_embeddings - pos_embeddings),axis=-1)
max_pos_dist = K.max(pos_dist)
# distance between the anchor and the negative
neg_dist = K.sum(K.square(anchor_embeddings - neg_embeddings),axis=-1)
max_neg_dist = K.min(neg_dist)
# compute loss
basic_loss = max_pos_dist - max_neg_dist + margin
tr_loss = K.maximum(basic_loss,0.0)
return tr_loss
#return triplet_loss
return loss
这可能是因为 keras 期望数组作为返回损失,但我提供的是标量值吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)