F.softmax(cls) + 1e-4

 这个代码段中的 softmax 操作结合了一个微小的常数,这个常数通常被称为平滑化参数。softmax 函数将原始的分类输出转换为概率分布,其公式如下:

在实践中,当某些分类得分特别大时,softmax 函数会将对应的概率接近于 1,而其他分类的概率会接近于 0。这可能会导致模型在训练过程中对训练数据过度自信,增加了过拟合的风险。

为了减轻这种过拟合的可能性,可以在 softmax 操作中添加一个微小的常数(通常为 1e-4 或类似的小值),即在原始的分类得分中加上一个小的偏置。这样做的目的是使得模型对于分类得分的细微差异更加敏感,从而在一定程度上抑制过拟合的发生。

因此,这种平滑化操作有助于提高模型的鲁棒性,使得模型更加能够泛化到未见过的数据,并减少在训练集上过度拟合的可能性。

我想要减小分类损失,添加使用Focal Loss缓解类别不平衡问题。我将提供loss.py和metrics.py中的相关代码,请帮我进行补充,保证box_loss的减小,同时实现cls_loss的减小 loss.py中代码: def forward(self, pred_dist, pred_bboxes, anchor_points, target_bboxes, target_scores, target_scores_sum, fg_mask): """IoU loss.""" weight = target_scores.sum(-1)[fg_mask].unsqueeze(-1) # iou = bbox_iou(pred_bboxes[fg_mask], target_bboxes[fg_mask], xywh=False, CIoU=True) # loss_iou = ((1.0 - iou) * weight).sum() / target_scores_sum iou = bbox_iou(pred_bboxes[fg_mask], target_bboxes[fg_mask],xywh=False, alpha_iou=True, alpha=3.0) loss_iou = ((1.0 - iou) * weight).sum() / target_scores_sum if type(iou) is tuple: if len(iou) == 2: loss_iou = ((1.0 - iou[0]) * iou[1].detach() * weight).sum() / target_scores_sum else: loss_iou = (iou[0] * iou[1] * weight).sum() / target_scores_sum else: loss_iou = ((1.0 - iou) * weight).sum() / target_scores_sum metrics.py中代码: def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False,alpha_iou=False,alpha=3.0, eps=1e-7): #中间不变 # IoU iou = inter / union if CIoU or DIoU or GIoU: cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # convex (smallest enclosing box) width ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # convex height if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1 c2 = cw.pow(2) + ch.pow(2) + eps # convex diagonal squared rho2 = ( (b2_x1 + b2_x2 - b1_x1 - b1_x2).pow(2) + (b2_y1 + b2_y2 - b1_y1 - b1_y2).pow(2) ) / 4 # center dist**2 if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47 v = (4 / math.pi**2) * ((w2 / h2).atan() - (w1 / h1).atan()).pow(2) with torch.no_grad(): alpha = v / (v - iou + (1 + eps)) return iou - (rho2 / c2 + v * alpha) # CIoU return iou - rho2 / c2 # DIoU c_area = cw * ch + eps # convex area return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf # 添加Alpha-IoU计算 if alpha_iou: alpha = alpha if alpha > 0 else 3.0 # 默认α=3 alpha_iou = 1 - ((1 - iou) ** alpha) # Alpha-IoU公式 return alpha_iou return iou # IoU
最新发布
03-31
import tensorflow as tf from transformers import BertTokenizer, TFBertModel from tensorflow.keras import layers, models from tensorflow.keras.optimizers import Adam from tensorflow.keras.layers import Conv1D, GlobalMaxPooling1D, Dense, Dropout, Lambda, Concatenate # 设置 GELU 激活函数 def set_gelu(activation_type): if activation_type == 'tanh': return tf.nn.gelu else: return tf.nn.gelu # 默认返回 Gelu 函数 # 自定义 CNN 特征提取层 def textcnn(inputs, kernel_initializer): cnn1 = Conv1D( 256, 3, strides=1, padding='same', activation='relu', kernel_initializer=kernel_initializer )(inputs) # shape=[batch_size,maxlen-2,256] cnn1 = GlobalMaxPooling1D()(cnn1) # shape=[batch_size,256] cnn2 = Conv1D( 256, 4, strides=1, padding='same', activation='relu', kernel_initializer=kernel_initializer )(inputs) cnn2 = GlobalMaxPooling1D()(cnn2) cnn3 = Conv1D( 256, 5, strides=1, padding='same', kernel_initializer=kernel_initializer )(inputs) cnn3 = GlobalMaxPooling1D()(cnn3) output = Concatenate(axis=-1)([cnn1, cnn2, cnn3]) output = Dropout(0.2)(output) return output # 构建 BERT 模型 def build_bert_model(model_path, class_nums): # 使用 transformers 库加载本地的 BERT 模型和分词器 tokenizer = BertTokenizer.from_pretrained(model_path) bert_model = TFBertModel.from_pretrained(model_path, output_hidden_states=True) # 通过 BertModel 获取输出 input_ids = layers.Input(shape=(None,), dtype=tf.int32, name="input_ids") attention_mask = layers.Input(shape=(None,), dtype=tf.int32, name="attention_mask") # 获取 BERT 的输出,返回的是 [last_hidden_state, pooler_output] # bert_output = bert_model(input_ids, attention_mask=attention_mask) # all_token_embedding = bert_output[0] # [batch_size, maxlen-2, 768] # cls_features = Lambda(lambda x: x[:, 0])(bert_output[0]) # 获取 [CLS] token 特征 # print("all_token_embedding:",all_token_embedding.shape) ##获取BERT的多层CLS特征 hidden_states = bert_model(input_ids, attention_mask=attention_mask).hidden_states print("all_hidden_states:", len(hidden_states)) # 取最后4层的CLS向量 [batch_size, 768] *4 last_4_cls = [Lambda(lambda x: x[:, 0])(layer) for layer in hidden_states[-4:]] # 拼接多层CLS cls_features = Concatenate(axis=-1)(last_4_cls) # shape=[batch_size, 768*4] cls_features = Dense(768, activation='gelu')(cls_features) # 降维融合 # # 使用 CNN 提取特征 kernel_initializer = tf.keras.initializers.GlorotUniform() # 这里使用 GlorotUniform 作为初始化器 # cnn_features = textcnn(all_token_embedding, kernel_initializer) # shape=[batch_size, cnn_output_dim] # CNN特征提取 token_embeddings = hidden_states[-1] # 最后一层输出 cnn_features = textcnn(token_embeddings, 'glorot_uniform') # 拼接 [CLS] 特征和 CNN 特征 concat_features = Concatenate(axis=-1)([cls_features, cnn_features]) # 全连接层 dense = Dense( units=512, activation='gelu', kernel_initializer=kernel_initializer, kernel_regularizer=tf.keras.regularizers.l2(1e-4) )(concat_features) # 输出层 output = Dense( units=class_nums, activation='softmax', kernel_initializer=kernel_initializer, dtype=tf.float32 )(dense) # 定义模型 model = models.Model(inputs=[input_ids, attention_mask], outputs=output) return model # 主程序 # if __name__ == '__main__': # model_path = './bert-base-chinese' # 配置文件路径 # class_nums = 13 # 分类数量 # # # 构建 BERT + CNN 模型 # model = build_bert_model(model_path, class_nums) # model.summary() 怎么在这个模型上添加在CNN后添加自注意力层,聚焦关键局部特征这个功能
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值