我需要一些keras损失功能的帮助.我一直在使用Tensorflow后端在keras上实现自定义丢失功能.
我已经在numpy中实现了自定义丢失函数,但如果它可以转换为keras损失函数则会很棒.loss函数采用数据帧和一系列用户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
Run Code Online (Sandbox Code Playgroud)
我试图实现keras损失功能.我从y_true和y_pred张量对象中提取了numpy数组. …
我看过另一个StackOverflow线程,它在讨论用于计算欧几里得范数的各种实现,而我很难理解为什么/如何实现特定的实现。
可在MMD度量的实现中找到代码:https : //github.com/josipd/torch-two-sample/blob/master/torch_two_sample/statistics_diff.py
这是一些开始的样板:
import torch
sample_1, sample_2 = torch.ones((10,2)), torch.zeros((10,2))
Run Code Online (Sandbox Code Playgroud)
接下来的部分是我们从上面的代码中提取的内容。我不确定为什么将这些样本连接在一起。
sample_12 = torch.cat((sample_1, sample_2), 0)
distances = pdist(sample_12, sample_12, norm=2)
Run Code Online (Sandbox Code Playgroud)
然后传递给pdist函数:
def pdist(sample_1, sample_2, norm=2, eps=1e-5):
r"""Compute the matrix of all squared pairwise distances.
Arguments
---------
sample_1 : torch.Tensor or Variable
The first sample, should be of shape ``(n_1, d)``.
sample_2 : torch.Tensor or Variable
The second sample, should be of shape ``(n_2, d)``.
norm : float
The l_p norm to be used.
Returns
-------
torch.Tensor …Run Code Online (Sandbox Code Playgroud)