如何在自定义损失函数中迭代张量?

How to iterate through tensors in custom loss function?

我正在使用带有 tensorflow 后端的 keras。我的目标是在 自定义损失 函数中查询当前批次的 batchsize。这需要计算依赖于特定观察索引的自定义损失函数的值。鉴于下面的最小可重现示例,我想使这一点更清楚。

(顺便说一句:当然,我可以使用为训练过程定义的批量大小,并在定义自定义损失函数时插入它的值,但有一些原因会导致这种情况发生变化,特别是如果 epochsize % batchsize ( epochsize modulo batchsize) 不等于零,那么一个纪元的最后一批具有不同的大小。我没有在 Whosebug 中找到合适的方法,尤其是例如 and Tensorflow custom loss function in Keras - loop over tensor and 因为显然在构建图形时无法推断出任何张量的形状,而损失函数就是这种情况 - 只有在给定数据进行评估时才有可能进行形状推断,而这只有在给定图形的情况下才有可能。因此,我需要告诉自定义损失函数在不知道维度长度的情况下沿特定维度对特定元素执行某些操作。

(所有例子都一样)

from keras.models import Sequential
from keras.layers import Dense, Activation

# Generate dummy data
import numpy as np
data = np.random.random((1000, 100))
labels = np.random.randint(2, size=(1000, 1))

model = Sequential()
model.add(Dense(32, activation='relu', input_dim=100))
model.add(Dense(1, activation='sigmoid'))

示例 1:没什么特别的,没有问题,没有自定义丢失

model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy'])    

# Train the model, iterating on the data in batches of 32 samples
model.fit(data, labels, epochs=10, batch_size=32)

(省略输出,运行完美)

示例 2:没什么特别的,具有相当简单的自定义损失

def custom_loss(yTrue, yPred):
    loss = np.abs(yTrue-yPred)
    return loss

model.compile(optimizer='rmsprop',
              loss=custom_loss,
              metrics=['accuracy'])

# Train the model, iterating on the data in batches of 32 samples
model.fit(data, labels, epochs=10, batch_size=32)

(省略输出,运行完美)

示例 3:问题

def custom_loss(yTrue, yPred):
    print(yPred) # Output: Tensor("dense_2/Sigmoid:0", shape=(?, 1), dtype=float32)
    n = yPred.shape[0]
    for i in range(n): # TypeError: __index__ returned non-int (type NoneType)
        loss = np.abs(yTrue[i]-yPred[int(i/2)])
    return loss

model.compile(optimizer='rmsprop',
              loss=custom_loss,
              metrics=['accuracy'])

# Train the model, iterating on the data in batches of 32 samples
model.fit(data, labels, epochs=10, batch_size=32)

当然张量还没有形状信息,在构建图形时无法推断,只能在训练时推断。因此 for i in range(n) 出现错误。有什么办法可以做到这一点吗?

输出的回溯:

--------

顺便说一句,如果有任何问题,这是我真正的自定义损失函数。为了清楚和简单起见,我在上面跳过了它。

def neg_log_likelihood(yTrue,yPred):
    yStatus = yTrue[:,0]
    yTime = yTrue[:,1]    
    n = yTrue.shape[0]    
    for i in range(n):
        s1 = K.greater_equal(yTime, yTime[i])
        s2 = K.exp(yPred[s1])
        s3 = K.sum(s2)
        logsum = K.log(y3)
        loss = K.sum(yStatus[i] * yPred[i] - logsum)
    return loss

这是 cox 比例风险模型的部分负对数似然图像。

这是为了澄清评论中的一个问题,以免造成混淆。我认为没有必要详细了解这一点来回答这个问题。

像往常一样,不要循环。存在严重的性能缺陷和错误。除非完全不可避免(通常不是不可避免),否则只使用后端函数


示例 3 的解决方案:

所以,那里有一件非常奇怪的事情......

Do you really want to simply ignore half of your model's predictions? (Example 3)

假设这是真的,只需在最后一个维度复制你的张量,展平并丢弃其中的一半。你有你想要的确切效果。

def custom_loss(true, pred):
    n = K.shape(pred)[0:1]

    pred = K.concatenate([pred]*2, axis=-1) #duplicate in the last axis
    pred = K.flatten(pred)                  #flatten 
    pred = K.slice(pred,                    #take only half (= n samples)
                   K.constant([0], dtype="int32"), 
                   n) 

    return K.abs(true - pred)

你的损失函数的解法:

如果您已将时间从大到小排序,只需进行累加即可。

Warning: If you have one time per sample, you cannot train with mini-batches!!!
batch_size = len(labels)

在一个额外的维度上有时间(每个样本很多次)是有意义的,就像在循环和 1D conv 网络中所做的那样。无论如何,考虑到您所表达的示例,即形状 (samples_equal_times,) for yTime:

def neg_log_likelihood(yTrue,yPred):
    yStatus = yTrue[:,0]
    yTime = yTrue[:,1]    
    n = K.shape(yTrue)[0]    


    #sort the times and everything else from greater to lower:
    #obs, you can have the data sorted already and avoid doing it here for performance

    #important, yTime will be sorted in the last dimension, make sure its (None,) in this case
    # or that it's (None, time_length) in the case of many times per sample
    sortedTime, sortedIndices = tf.math.top_k(yTime, n, True)    
    sortedStatus = K.gather(yStatus, sortedIndices)
    sortedPreds = K.gather(yPred, sortedIndices)

    #do the calculations
    exp = K.exp(sortedPreds)
    sums = K.cumsum(exp)  #this will have the sum for j >= i in the loop
    logsums = K.log(sums)

    return K.sum(sortedStatus * sortedPreds - logsums)