文本生成中的 mask CrossEntropy -Tensorflow

本文介绍了在文本生成任务中,如何使用Tensorflow实现带有mask的CrossEntropy损失函数,以避免序列padding部分的影响。通过示例分别展示了没有mask和应用mask后的CE损失计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文本生成中的真实标签为 index,shape = [n_batch,]
输出的为概率分布,shape = [n_batch, num_decoder_tokens]
计算 loss 时应 mask 序列 padding部分

def categorical_CE_generation(max_len_char,n_decoder_tokens,idx_pad=0):
    def mask_categorical_crossentropy(y_true,y_pred):
        epsilon = K.epsilon()
        y_pred = K.clip(y_pred, epsilon, 1. - epsilon)#避免 loss 为nan
        # print (y_true,y_pred)
        y_true = tf.cast(tf.reshape(y_true,[-1,max_len_char]),tf.int32)
        y_pred = tf.reshape(y_pred,[-1,max_len_char,n_decoder_tokens])
        
        loss_ = tf.nn.sparse_softmax_cross_entropy_with_logits( labels = y_true,logits = y_pred)
        mask = tf.constant(idx_pad,dtype = tf.int32)
        loss_ = tf.boolean_mask(tensor = loss_, mask = tf.not_equal(y_true,mask)) 
        loss_CE = tf.reduce_sum(loss_)/tf.cast(tf.shape(y_true)[0],dtype=tf.float32)
        return loss_CE
    return mask_categorical_crossentropy
Example:
sess = tf.Session()

y_label_onehot = tf.convert_to_tensor([
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值