【发布时间】:2019-06-25 10:26:54
【问题描述】:
我正在处理序列数据(一个热编码序列),并且正在寻找一种方法来编写自定义损失函数,该函数使用基于 y_pred 和 y_true 的值字典中的权重,并取决于这些值训练时(所以我不能在调用 fit 时使用恒定权重)。
基本上,对于序列矩阵中的每个 argmax 索引位置,我可以检索一个字符。 对于每两个字符,我可以检索一个权重。 这些字典如下:
values =
{0: 'A',
1: 'C',
2: 'D',
...}
matrix = array
([[ 4, -1, -2, -2, 0, -1, -1, 0, -2, -1, -1, -1, -1, -2, -1, 1,
0, -3, -2, 0, -2, -1, 0, -4],
[-1, 5, 0, -2, -3, 1, 0, -2, 0, -3, -2, 2, -1, -3, -2, -1,
-1, -3, -2, -3, -1, 0, -1, -4],
[-2, 0, 6, 1, -3, 0, 0, 0, 1, -3, -3, 0, -2, -3, -2, 1,
0, -4, -2, -3, 3, 0, -1, -4],
...]])
我想做这样的事情:
y_true (n,155,20) ---K.argmax(.., axis=2)---> a:(n,155)
y_pred (n,155,20) ---K.argmax(.., axis=2)---> b:(n,155)
for i in range(n):
for j in range(155):
weights[i,j] = matrix[values[a[i,j]], values[b[i,j]]]
想象一下有一种方法可以通过其他一些字典获取上面的矩阵值。
然后我想像这样使用我的weights 矩阵:
def custom_loss_mse(y_true,y_pred):
w = getWeights(y_true,y_pred)
return K.mean(K.dot(w, K.square(y_pred-y_true)), axis=-1)
到目前为止,我只发现this question 有帮助,而且并不是很相似。
这很容易,但由于计算图模型,keras 让我更难做到。应该有一些快速的方法来做到这一点,但我没有想法。
我会很感激任何帮助,因为我对 numpy 和 keras 还很陌生。
【问题讨论】:
-
我会回答我自己的问题,以防这对其他人有帮助。我创建了一个矩阵,它保留了我想使用来自
argmax的索引查询的值,如下所示:lang-py blMatrix = tf.constant(prepare_matrix())我的损失函数如下所示:lang-py def custom_loss(y_true, y_pred) y_true_argmax = K.argmax(y_true, axis=2) y_pred_argmax = K.argmax(y_pred, axis=2) result = tf.gather_nd(blMatrix, tf.stack((y_true_argmax, y_pred_argmax), -1))
标签: python numpy tensorflow keras loss-function