34

我正在尝试使用 Keras 的 LSTM 和 TensorFlow 后端来实现序列到序列的任务。输入是长度可变的英语句子。为了构建一个具有 2-D shape 的数据集[batch_number, max_sentence_length],我EOF在行尾添加并用足够的占位符填充每个句子,例如#. 然后将句子中的每个字符转换为 one-hot 向量,从而使数据集具有 3-D 形状[batch_number, max_sentence_length, character_number]。在 LSTM 编码器和解码器层之后,计算输出和目标之间的 softmax 交叉熵。

为了消除模型训练中的填充效应,可以对输入和损失函数使用掩码。Keras 中的掩码输入可以使用layers.core.Masking. 在 TensorFlow 中,可以按如下方式对损失函数进行掩码:TensorFlow 中的自定义掩码损失函数

但是,我没有找到在 Keras 中实现它的方法,因为 Keras 中用户定义的损失函数只接受参数y_truey_pred. 那么如何输入真实sequence_lengths的损失函数和掩码呢?

此外,我_weighted_masked_objective(fn)\keras\engine\training.py. 它的定义是

为目标函数添加对掩蔽和样本加权的支持。

但似乎该功能只能接受fn(y_true, y_pred). 有没有办法使用这个功能来解决我的问题?

具体来说,我修改了Yu-Yang的例子。

from keras.models import Model
from keras.layers import Input, Masking, LSTM, Dense, RepeatVector, TimeDistributed, Activation
import numpy as np
from numpy.random import seed as random_seed
random_seed(123)

max_sentence_length = 5
character_number = 3 # valid character 'a, b' and placeholder '#'

input_tensor = Input(shape=(max_sentence_length, character_number))
masked_input = Masking(mask_value=0)(input_tensor)
encoder_output = LSTM(10, return_sequences=False)(masked_input)
repeat_output = RepeatVector(max_sentence_length)(encoder_output)
decoder_output = LSTM(10, return_sequences=True)(repeat_output)
output = Dense(3, activation='softmax')(decoder_output)

model = Model(input_tensor, output)
model.compile(loss='categorical_crossentropy', optimizer='adam')
model.summary()

X = np.array([[[0, 0, 0], [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0]],
          [[0, 0, 0], [0, 1, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0]]])
y_true = np.array([[[0, 0, 1], [0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 1, 0]], # the batch is ['##abb','#babb'], padding '#'
          [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0]]])

y_pred = model.predict(X)
print('y_pred:', y_pred)
print('y_true:', y_true)
print('model.evaluate:', model.evaluate(X, y_true))
# See if the loss computed by model.evaluate() is equal to the masked loss
import tensorflow as tf
logits=tf.constant(y_pred, dtype=tf.float32)
target=tf.constant(y_true, dtype=tf.float32)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(target * tf.log(logits),axis=2))
losses = -tf.reduce_sum(target * tf.log(logits),axis=2)
sequence_lengths=tf.constant([3,4])
mask = tf.reverse(tf.sequence_mask(sequence_lengths,maxlen=max_sentence_length),[0,1])
losses = tf.boolean_mask(losses, mask)
masked_loss = tf.reduce_mean(losses)
with tf.Session() as sess:
    c_e = sess.run(cross_entropy)
    m_c_e=sess.run(masked_loss)
    print("tf unmasked_loss:", c_e)
    print("tf masked_loss:", m_c_e)

Keras 和 TensorFlow 中的输出对比如下:

在此处输入图像描述

如上所示,在某些类型的图层之后会禁用遮罩。那么当这些层被添加时,如何在 Keras 中掩盖损失函数呢?

4

3 回答 3

29

如果您的模型中有掩码,它将逐层传播并最终应用于损失。因此,如果您以正确的方式填充和屏蔽序列,则填充占位符上的损失将被忽略。

一些细节:

解释整个过程有点牵强,所以我将其分解为几个步骤:

  1. compile()中,通过调用收集掩码compute_mask()并将其应用于损失(为清楚起见,忽略不相关的行)。
weighted_losses = [_weighted_masked_objective(fn) for fn in loss_functions]

# Prepare output masks.
masks = self.compute_mask(self.inputs, mask=None)
if masks is None:
    masks = [None for _ in self.outputs]
if not isinstance(masks, list):
    masks = [masks]

# Compute total loss.
total_loss = None
with K.name_scope('loss'):
    for i in range(len(self.outputs)):
        y_true = self.targets[i]
        y_pred = self.outputs[i]
        weighted_loss = weighted_losses[i]
        sample_weight = sample_weights[i]
        mask = masks[i]
        with K.name_scope(self.output_names[i] + '_loss'):
            output_loss = weighted_loss(y_true, y_pred,
                                        sample_weight, mask)
  1. 在里面Model.compute_mask()run_internal_graph()被称为。
  2. 在内部,模型中的掩码通过迭代run_internal_graph()调用每一层从模型的输入逐层传播到输出。Layer.compute_mask()

因此,如果您Masking在模型中使用层,则不必担心填充占位符的丢失。正如您可能已经在里面看到的那样,这些条目的损失将被掩盖_weighted_masked_objective()

一个小例子:

max_sentence_length = 5
character_number = 2

input_tensor = Input(shape=(max_sentence_length, character_number))
masked_input = Masking(mask_value=0)(input_tensor)
output = LSTM(3, return_sequences=True)(masked_input)
model = Model(input_tensor, output)
model.compile(loss='mae', optimizer='adam')

X = np.array([[[0, 0], [0, 0], [1, 0], [0, 1], [0, 1]],
              [[0, 0], [0, 1], [1, 0], [0, 1], [0, 1]]])
y_true = np.ones((2, max_sentence_length, 3))
y_pred = model.predict(X)
print(y_pred)
[[[ 0.          0.          0.        ]
  [ 0.          0.          0.        ]
  [-0.11980877  0.05803877  0.07880752]
  [-0.00429189  0.13382857  0.19167568]
  [ 0.06817091  0.19093043  0.26219055]]

 [[ 0.          0.          0.        ]
  [ 0.0651961   0.10283815  0.12413475]
  [-0.04420842  0.137494    0.13727818]
  [ 0.04479844  0.17440712  0.24715884]
  [ 0.11117355  0.21645413  0.30220413]]]

# See if the loss computed by model.evaluate() is equal to the masked loss
unmasked_loss = np.abs(1 - y_pred).mean()
masked_loss = np.abs(1 - y_pred[y_pred != 0]).mean()

print(model.evaluate(X, y_true))
0.881977558136

print(masked_loss)
0.881978

print(unmasked_loss)
0.917384

从这个例子可以看出,被屏蔽部分的损失( 中的零点y_pred)被忽略了, 的输出model.evaluate()等于masked_loss


编辑:

如果存在带有 的循环层return_sequences=False,则掩码停止传播(即,返回的掩码为None)。在RNN.compute_mask()

def compute_mask(self, inputs, mask):
    if isinstance(mask, list):
        mask = mask[0]
    output_mask = mask if self.return_sequences else None
    if self.return_state:
        state_mask = [None for _ in self.states]
        return [output_mask] + state_mask
    else:
        return output_mask

在您的情况下,如果我理解正确,您需要一个基于 的掩码y_true,并且每当 的值为y_true[0, 0, 1]“#”的单热编码)时,您都希望掩盖损失。如果是这样,您需要以与 Daniel 的回答有些相似的方式掩盖损失值。

主要区别在于最终平均值。平均值应超过未屏蔽值的数量,即K.sum(mask). 而且,y_true可以直接与 one-hot 编码向量进行比较[0, 0, 1]

def get_loss(mask_value):
    mask_value = K.variable(mask_value)
    def masked_categorical_crossentropy(y_true, y_pred):
        # find out which timesteps in `y_true` are not the padding character '#'
        mask = K.all(K.equal(y_true, mask_value), axis=-1)
        mask = 1 - K.cast(mask, K.floatx())

        # multiply categorical_crossentropy with the mask
        loss = K.categorical_crossentropy(y_true, y_pred) * mask

        # take average w.r.t. the number of unmasked entries
        return K.sum(loss) / K.sum(mask)
    return masked_categorical_crossentropy

masked_categorical_crossentropy = get_loss(np.array([0, 0, 1]))
model = Model(input_tensor, output)
model.compile(loss=masked_categorical_crossentropy, optimizer='adam')

上述代码的输出然后显示损失仅在未屏蔽的值上计算:

model.evaluate: 1.08339476585
tf unmasked_loss: 1.08989
tf masked_loss: 1.08339

该值与您的值不同,因为我已将axis参数tf.reverse从 from更改为[0,1]to [1]

于 2017-11-01T17:47:06.890 回答
2

如果你没有像 Yu-Yang 的回答那样使用口罩,你可以试试这个。

如果您的目标数据Y具有长度并用掩码值填充,您可以:

import keras.backend as K
def custom_loss(yTrue,yPred):

    #find which values in yTrue (target) are the mask value
    isMask = K.equal(yTrue, maskValue) #true for all mask values

    #since y is shaped as (batch, length, features), we need all features to be mask values
    isMask = K.all(isMask, axis=-1) #the entire output vector must be true
        #this second line is only necessary if the output features are more than 1

    #transform to float (0 or 1) and invert
    isMask = K.cast(isMask, dtype=K.floatx())
    isMask = 1 - isMask #now mask values are zero, and others are 1

    #multiply this by the inputs:
       #maybe you might need K.expand_dims(isMask) to add the extra dimension removed by K.all
     yTrue = yTrue * isMask   
     yPred = yPred * isMask

     return someLossFunction(yTrue,yPred)

如果您仅对输入数据进行填充,或者如果 Y 没有长度,则可以在函数外部使用自己的掩码:

masks = [
   [1,1,1,1,1,1,0,0,0],
   [1,1,1,1,0,0,0,0,0],
   [1,1,1,1,1,1,1,1,0]
]
 #shape (samples, length). If it fails, make it (samples, length, 1). 

import keras.backend as K

masks = K.constant(masks)

由于掩码取决于您的输入数据,因此您可以使用掩码值来知道在哪里放置零,例如:

masks = np.array((X_train == maskValue).all(), dtype='float64')    
masks = 1 - masks

#here too, if you have a problem with dimensions in the multiplications below
#expand masks dimensions by adding a last dimension = 1.

并使您的函数从外部获取掩码(如果您更改输入数据,则必须重新创建损失函数):

def customLoss(yTrue,yPred):

    yTrue = masks*yTrue
    yPred = masks*yPred

    return someLossFunction(yTrue,yPred)

有谁知道 keras 是否会自动屏蔽损失函数?因为它提供了一个掩蔽层并且没有说明输出,所以它可能会自动执行它?

于 2017-11-01T15:47:35.420 回答
2

我采用了两种方法,并为多个时间步、单个缺失目标值、LSTM(或其他 RecurrentNN)的损失以及 return_sequences=True 提供了一种方法。

Daniels Answer 无法满足多个目标,因为isMask = K.all(isMask, axis=-1). 删除此聚合可能会使函数不可微。我不知道舒尔,因为我从不运行纯函数,也无法判断它是否适合模型。

我将 Yu-Yangs 和 Daniels 的答案融合在一起,效果很好。


from tensorflow.keras.layers import Layer, Input, LSTM, Dense, TimeDistributed
from tensorflow.keras import Model, Sequential
import tensorflow.keras.backend as K
import numpy as np


mask_Value = -2
def get_loss(mask_value):
    mask_value = K.variable(mask_value)
    def masked_loss(yTrue,yPred):
        
        #find which values in yTrue (target) are the mask value
        isMask = K.equal(yTrue, mask_Value) #true for all mask values
    
        #transform to float (0 or 1) and invert
        isMask = K.cast(isMask, dtype=K.floatx())
        isMask = 1 - isMask #now mask values are zero, and others are 1
        isMask
        
        #multiply this by the inputs:
        #maybe you might need K.expand_dims(isMask) to add the extra dimension removed by K.all
        yTrue = yTrue * isMask   
        yPred = yPred * isMask
        
        # perform a root mean square error, whereas the mean is in respect to the mask
        mean_loss = K.sum(K.square(yPred - yTrue))/K.sum(isMask)
        loss = K.sqrt(mean_loss)
    
        return loss
        #RootMeanSquaredError()(yTrue,yPred)
        
    return masked_loss

# define timeseries data
n_sample = 10
timesteps = 5
feat_inp = 2
feat_out = 2

X = np.random.uniform(0,1, (n_sample, timesteps, feat_inp))
y = np.random.uniform(0,1, (n_sample,timesteps, feat_out))

# define model
model = Sequential()
model.add(LSTM(50, activation='relu',return_sequences=True, input_shape=(timesteps, feat_inp)))
model.add(Dense(feat_out))
model.compile(optimizer='adam', loss=get_loss(mask_Value))
model.summary()

# %%
model.fit(X, y, epochs=50, verbose=0)

于 2021-11-26T15:14:32.040 回答