【发布时间】:2018-12-08 13:49:59
【问题描述】:
我需要一些有关 keras 损失函数的帮助。我一直在使用 Tensorflow 后端在 keras 上实现自定义损失函数。
我已经在 numpy 中实现了自定义损失函数,但如果它可以翻译成 keras 损失函数那就太好了。损失函数采用数据框和一系列用户 ID。如果 user_id 不同,则相同 user_id 的欧几里得距离为正数和负数。该函数返回数据帧的总标量距离。
def custom_loss_numpy (encodings, user_id):
# user_id: a pandas series of users
# encodings: a pandas dataframe of encodings
batch_dist = 0
for i in range(len(user_id)):
first_row = encodings.iloc[i,:].values
first_user = user_id[i]
for j in range(i+1, len(user_id)):
second_user = user_id[j]
second_row = encodings.iloc[j,:].values
# compute distance: if the users are same then Euclidean distance is positive otherwise negative.
if first_user == second_user:
tmp_dist = np.linalg.norm(first_row - second_row)
else:
tmp_dist = -np.linalg.norm(first_row - second_row)
batch_dist += tmp_dist
return batch_dist
我已经尝试实现 keras 损失函数。我从 y_true 和 y_pred 张量对象中提取了 numpy 数组。
def custom_loss_keras(y_true, y_pred):
# session of my program
sess = tf_session.TF_Session().get()
with sess.as_default():
array_pred = y_pred.eval()
print(array_pred)
但我收到以下错误。
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'dense_1_input' with dtype float and shape [?,102]
[[Node: dense_1_input = Placeholder[dtype=DT_FLOAT, shape=[?,102], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
我们将不胜感激任何形式的帮助。
【问题讨论】:
标签: python tensorflow keras loss-function