迁移学习 - NSP 案例 - 模型搭建
1 课程概览
本课讲解迁移学习 NSP 案例的模型搭建。与案例一(中文分类)一模一样,直接复制代码,不需要修改。将 BERT 的 768 维输出转成 2 维(二分类)。NSP 是二分类问题,与中文分类高度相似。
2 核心概念与定义
- 下游模型:基于 BERT 的 NSP 任务模型。
- 二分类:NSP 是否是下半句,是二分类问题。
- 直接复制:与案例一一样,不需要修改。
3 模型与算法详解
与案例一的关系
与案例一(中文分类)一模一样,直接复制代码。
| 案例 | 输出维度 | 说明 |
|---|---|---|
| 中文分类 | 2 | 二分类(好评/差评) |
| NSP | 2 | 二分类(是/不是下半句) |
模型结构
输入 → BERT(冻结参数) → 768维 → 全连接层 → 2维 → softmax → 分类结果
全连接层
768 → 2(二分类)
self.fc = nn.Linear(768, 2)
直接复制
从案例一复制代码,不需要修改。
- 复制案例一的模型搭建代码
- 不需要做任何修改
- 直接运行测试
4 数学原理与推导
NSP
$$\text{features} = \text{BERT}(\text{sentence}_1, \text{sentence}_2)$$
$$\text{output} = \text{FC}(\text{features})$$
$$\text{prediction} = \text{softmax}(\text{output})$$
其中:
- $\text{BERT}$ 是预训练模型(768 维输出)
- $\text{FC}$ 是全连接层(768 → 2)
- $\text{output}$ 是 2 维输出(是/不是下半句)
5 代码示例
import torch
import torch.nn as nn
from transformers import BertModel
class AiModel(nn.Module):
"""自定义下游模型:基于 BERT 的 NSP 任务模型"""
def __init__(self, my_bert_model):
super(AiModel, self).__init__()
# 1. BERT 预训练模型
self.bert = my_bert_model
# 2. 全连接层:768 → 2(二分类)
self.fc = nn.Linear(768, 2)
def forward(self, input_ids, attention_mask, token_type_ids):
"""
前向传播
Args:
input_ids: 文本的数字编码 [batch_size, max_len]
attention_mask: 注意力掩码 [batch_size, max_len]
token_type_ids: 句子类型标记 [batch_size, max_len]
Returns:
output: 二分类结果 [batch_size, 2]
"""
# 1. 不计算 BERT 的梯度(冻结参数)
with torch.no_grad():
bert_output = self.bert(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids
)
# 2. 取最后一个隐藏层
last_hidden_state = bert_output.last_hidden_state # [batch_size, max_len, 768]
# 3. 取 [CLS] 位置的输出(第 0 个位置)
cls_output = last_hidden_state[:, 0, :] # [batch_size, 768]
# 4. 全连接层分类
output = self.fc(cls_output) # [batch_size, 2]
return output
# 测试
if __name__ == "__main__":
print("=== 迁移学习:NSP 案例 - 模型搭建 ===")
# 加载 BERT 预训练模型
model_name = "bert-base-chinese"
my_bert_model = BertModel.from_pretrained(model_name)
# 创建下游模型(与案例一一样)
my_model = AiModel(my_bert_model)
# 测试模型结构
print(my_model)
print("与案例一(中文分类)一模一样,直接复制")
代码说明
| 代码 | 说明 |
|---|---|
nn.Linear(768, 2) | 全连接层(768 → 2) |
with torch.no_grad(): | 不计算梯度(冻结参数) |
bert_output.last_hidden_state | 最后一个隐藏层 |
last_hidden_state[:, 0, :] | 取 [CLS] 位置 |
self.fc(cls_output) | 全连接层分类 |
6 重难点与易错提醒
- ❗重点:NSP 模型与案例一(中文分类)一模一样。
- ❗重点:直接复制代码,不需要修改。
- ❗重点:NSP 是二分类问题。
- 💡技巧:越往后学越简单,很多案例都是通的。
7 课堂问答精选
Q1:NSP 模型和案例一有什么关系?
A:NSP 模型与案例一(中文分类)一模一样,直接复制代码,不需要修改。因为都是二分类问题。
Q2:为什么 NSP 模型和案例一一样?
A:因为 NSP 是二分类问题(是/不是下半句),与中文分类(好评/差评)一样,都是将 768 维转成 2 维。
Q3:需要修改哪些代码?
A:不需要修改任何代码,直接复制案例一的模型搭建代码即可。
Q4:NSP 的输出维度是多少?
A:输出 2 维,因为是二分类问题(是/不是下半句)。
8 本课小结
- NSP 模型与案例一(中文分类)一模一样。
- 直接复制代码,不需要修改。
- NSP 是二分类问题,输出 2 维。
- 全连接层:768 → 2。
9 延伸思考
- 如何进行模型训练和评估?
- BERT 模型有哪些特点?