簡體   English   中英

如何在自定義Keras / Tensorflow Loss函數中對值進行排序?

[英]How can I sort the values in a custom Keras / Tensorflow Loss Function?

介紹

我想為Keras實現自定義丟失功能。 我想這樣做,因為我對我的數據集的當前結果不滿意。 我認為這是因為目前內置的損失函數集中在整個數據集上。 我只想關注數據集中的最高值。 這就是我為自定義丟失函數提出以下想法的原因:

自定義損失功能理念

自定義損失函數應采用具有最高值的前4個預測,並使用相應的真值減去它。 然后從該減法中取絕對值,將其乘以一些權重並將其加到總損失總和中。

為了更好地理解這種自定義丟失功能,我使用列表輸入對其進行了編程。 希望這個例子更容易理解:

以下示例計算損失= 4 * abs(0.7-0.5)+ 3 * abs(0.5-0.7)+ 2 * abs(0.4-0.45)+ 1 * abs(0.4-0.3)= 1.6 i = 0

然后它將div_top除以div_top,在此示例中為10(對於i = 0,它將為0.16),為所有其他i重復所有內容,最后取所有樣本的平均值。

top = 4
div_top = 0.5*top*(top+1)


def own_loss(y_true, y_pred):
    loss_per_sample = [0]*len(y_pred)
    for i in range(len(y_pred)):
        sorted_pred, sorted_true = (list(t) for t in zip(*sorted(zip(y_pred[i], y_true[i]))))
        for k in range(top):
            loss_per_sample[i] += (top-k)*abs(sorted_pred[-1-k]-sorted_true[-1-k])
    loss_per_sample = [t/div_top for t in loss_per_sample]
    return sum(loss_per_sample)/len(loss_per_sample)


y_pred = [[0.1, 0.4, 0.7, 0.4, 0.4, 0.5, 0.3, 0.2],
          [0.3, 0.8, 0.5, 0.3, 0.1, 0.0, 0.1, 0.5],
          [0.5, 0.6, 0.6, 0.8, 0.3, 0.6, 0.7, 0.1]]

y_true = [[0.2, 0.45, 0.5, 0.3, 0.4, 0.7, 0.22, 0.1],
          [0.4, 0.9, 0.3, 0.0, 0.2, 0.1, 0.11, 0.8],
          [0.4, 0.7, 0.4, 0.3, 0.4, 0.7, 0.6, 0.05]]

print(own_loss(y_true, y_pred)) # Output is 0.196667

對Keras的實施

我想在Keras中使用此功能作為自定義丟失功能。 這看起來像這樣:

import numpy as np
from keras.datasets import boston_housing
from keras.layers import LSTM
from keras.models import Sequential
from keras.optimizers import RMSprop

(pre_x_train, pre_y_train), (x_test, y_test) = boston_housing.load_data()
"""
The following 8 lines are to format the dataset to a 3D numpy array
4*101*13. I do this so that it matches my real dataset with is formatted
to a 3D numpy array 47*731*179. It is not important to understand the following 
8 lines for the loss function itself.
"""
x_train = [[0]*101]*4
y_train = [[0]*101]*4
for i in range(4):
    for k in range(101):
        x_train[i][k] = pre_x_train[i*101+k]
        y_train[i][k] = pre_y_train[i*101+k]
train_x = np.array([np.array([np.array(k) for k in i]) for i in x_train])
train_y = np.array([np.array([np.array(k) for k in i]) for i in y_train])


top = 4
div_top = 0.5*top*(top+1)


def own_loss(y_true, y_pred):
    loss_per_sample = [0]*len(y_pred)
    for i in range(len(y_pred)):
        sorted_pred, sorted_true = (list(t) for t in zip(*sorted(zip(y_pred[i], y_true[i]))))
        for k in range(top):
            loss_per_sample[i] += (top-k)*abs(sorted_pred[-1-k]-sorted_true[-1-k])
    loss_per_sample = [t/div_top for t in loss_per_sample]
    return sum(loss_per_sample)/len(loss_per_sample)


model = Sequential()
model.add(LSTM(units=64, batch_input_shape=(None, 101, 13), return_sequences=True))
model.add(LSTM(units=101, return_sequences=False, activation='linear'))
# compile works with loss='mean_absolute_error' but not with loss=own_loss
model.compile(loss=own_loss, optimizer=RMSprop())

model.fit(train_x, train_y, epochs=16, verbose=2, batch_size=1, validation_split=None, shuffle=False)

顯然,上面的Keras示例不起作用。 但我也不知道如何才能開展工作。

解決問題的方法

我閱讀了以下文章,試圖解決問題:

Keras自定義指標迭代

如何為模型使用自定義目標函數?

我還閱讀了Keras后端頁面:

Keras后端

和Tensorflow Top_k頁面:

tf.nn.top_k

對我來說這似乎是最有前途的方法,但在實現它之后,許多不同的方法仍然無效。 在使用top_k進行排序時,我可以獲得正確的pred_y值,但是我無法獲得相應的true_y值。

有沒有人知道如何實現自定義丟失功能?

假設

  • 使用tf.nn.top_k對張量進行排序。 這意味着“如果兩個元素相等,則低級索引元素首先出現”,如API文檔中所述

建議的解決方案

top = 4
div_top = 0.5*top*(top+1)

def getitems_by_indices(values, indices):
    return tf.map_fn(
        lambda x: tf.gather(x[0], x[1]), (values, indices), dtype=values.dtype
    )

def own_loss(y_true, y_pred):
    y_pred_top_k, y_pred_ind_k = tf.nn.top_k(y_pred, top)
    y_true_top_k = getitems_by_indices(y_true, y_pred_ind_k)
    loss_per_sample = tf.reduce_mean(
        tf.reduce_sum(
            tf.abs(y_pred_top_k - y_true_top_k) *
                tf.range(top, 0, delta=-1, dtype=y_pred.dtype),
            axis=-1
        ) / div_top
    )
    return loss_per_sample

model = Sequential()
model.add(LSTM(units=64, batch_input_shape=(None, 101, 13), return_sequences=True))
model.add(LSTM(units=101, return_sequences=False, activation='linear'))
# compile works with loss='mean_absolute_error' but not with loss=own_loss
model.compile(loss=own_loss, optimizer=RMSprop())

model.train_on_batch(train_x, train_y)

評論

  • 是否有更好的getitems_by_indices()
  • getitems_by_indices()的當前實現使用了Sungwoon Kim的想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM