Coggle 30 Days of ML(23年7月)任务十:使用Bert在比赛数据集中完成预训练

简介: Coggle 30 Days of ML(23年7月)任务十:使用Bert在比赛数据集中完成预训练

Coggle 30 Days of ML(23年7月)任务十:使用Bert在比赛数据集中完成预训练

任务十:使用Bert在比赛数据集中完成预训练


  • 说明:在这个任务中,你将使用Bert模型在比赛数据集上完成预训练,通过预训练的Bert模型来提取文本特征。
  • 实践步骤:
  1. 准备比赛数据集和相应的预训练参数。
  2. 使用transformer库中的Bert模型,加载预训练参数。
  3. 使用Bert模型对比赛数据集进行预训练,提取文本特征。


加载与训练模型

在任务九的时候,我们已经介绍了transformer库中其实有一些有关于bert模型的参数,所以我们可以加载预训练的参数


具体的模型选择可以参考:https://huggingface.co/transformers/v3.0.2/pretrained_models.html?highlight=pretrained

# 加载预训练的BERT模型和分词器
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2)
model.to(device)


定义数据集

接下来就使用tokenizer来进行对数据进行提取特征,这里面设计了提取特征,最后返回input_idsattention_masklabel

# 定义自定义数据集类
class CustomDataset(Dataset):
    def __init__(self, texts, labels, tokenizer):
        self.texts = texts
        self.labels = labels
        self.tokenizer = tokenizer
    def __len__(self):
        return len(self.texts)
    def __getitem__(self, idx):
        text = self.texts.iloc[idx]
        # print(text)
        label = self.labels.iloc[idx]
        inputs = self.tokenizer.encode_plus(
            text,
            add_special_tokens=True,
            padding='max_length',
            max_length=128,
            truncation=True,
            return_tensors='pt'
        )
        return inputs['input_ids'].to(device), inputs['attention_mask'].to(device), torch.tensor(label).to(device)

定义训练和验证函数

定义训练和验证函数,训练函数将模型设置为训练模式并使用AdamW优化器进行模型参数更新,验证函数将模型设置为评估模式并计算验证数据集上的损失和准确率。

# 定义训练和验证函数
def train(model, train_loader):
    """
    训练模型的函数
    Args:
        model: 当前的模型
        train_loader: 训练数据集的DataLoader
    Returns:
    """
    # 将模型设置为训练模式
    model.train()
    # 定义优化器
    optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5)
    # 遍历训练数据集
    for batch in tqdm(train_loader, desc='Training'):
        # 获取数据
        input_ids, attention_mask, labels = batch
        # 数据转移到GPU上
        input_ids = input_ids.squeeze().to(device)
        attention_mask = attention_mask.squeeze().to(device)
        labels = labels.to(device)
        # 将梯度缓存归零
        optimizer.zero_grad()
        # 前向传播
        outputs = model(input_ids=input_ids.squeeze(),
                        attention_mask=attention_mask.squeeze(),
                        labels=labels)
        # 计算损失
        loss = outputs.loss
        # 反向传播
        loss.backward()
        # 更新模型参数
        optimizer.step()
def evaluate(model, val_loader):
    """
    验证模型的函数
    Args:
        model: 当前的模型
        val_loader: 验证数据集的DataLoader
    Returns:
        val_loss: 验证数据集上的损失
        accuracy: 模型在验证数据集上的准确率
    """
    # 将模型设置为评估模式
    model.eval()
    val_loss = 0
    correct = 0
    total = 0
    # 禁用梯度计算
    with torch.no_grad():
        # 遍历验证数据集
        for batch in tqdm(val_loader, desc='Evaluating'):
            # 获取数据
            input_ids, attention_mask, labels = batch
            # 数据转移到GPU上
            input_ids = input_ids.squeeze().to(device)
            attention_mask = attention_mask.squeeze().to(device)
            labels = labels.to(device)
            # 前向传播
            outputs = model(input_ids=input_ids.squeeze(),
                            attention_mask=attention_mask.squeeze(),
                            labels=labels)
            # 计算损失
            val_loss += outputs.loss.item()
            # 获取预测结果
            _, predicted = torch.max(outputs.logits, dim=1)
            # 统计预测正确的数量
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    # 计算准确率
    accuracy = correct / total
    return val_loss, accuracy

训练和验证模型

使用Bert模型对比赛数据集进行预训练,提取文本特征,训练10个epoch,验证模型并保存准确率最高的模型。

# 训练和验证
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# 将模型移动到GPU上
model.to(device)
num_epochs = 10
best_accuracy = 0
# 开始训练
for epoch in range(num_epochs):
    # 训练模型
    train(model, train_loader)
    # 验证模型
    val_loss, accuracy = evaluate(model, val_loader)
    # 打印当前模型的验证损失和准确率
    print(f'Epoch {epoch+1}: Validation Loss = {val_loss:.4f}, Accuracy = {accuracy:.4f}')
    # 如果当前模型的准确率更高,则保存当前模型
    if accuracy > best_accuracy:
        best_accuracy = accuracy
        torch.save(model.state_dict(), 'bert_model.pth')  # 保存最佳模型

模型预测

加载最佳模型进行预测并保存结果为CSV文件。

# 加载最佳模型并进行预测
model.load_state_dict(torch.load('bert_model.pth'))
# 将模型移动到GPU上
model.to(device)
# 将模型设置为评估模式
model.eval()
# 加载测试数据
test_texts = test_data['content']
test_labels = np.zeros(test_data.shape[0])
test_dataset = CustomDataset(test_texts, test_labels, tokenizer)
test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False)
# 预测结果
predictions = []
with torch.no_grad():
    for batch in tqdm(test_loader, desc='Predicting'):
        input_ids, attention_mask = batch
        outputs = model(input_ids=input_ids.squeeze(),
                        attention_mask=attention_mask.squeeze())
        _, predicted = torch.max(outputs.logits, dim=1)
        predictions.extend(predicted.tolist())
# 保存预测结果
submit = pd.read_csv('sample_submit.csv')
submit['label'] = predictions
submit.to_csv('bert_predictions.csv', index=None)
相关实践学习
基于阿里云DeepGPU实例,用AI画唯美国风少女
本实验基于阿里云DeepGPU实例,使用aiacctorch加速stable-diffusion-webui,用AI画唯美国风少女,可提升性能至高至原性能的2.6倍。
相关文章
|
7天前
|
机器学习/深度学习 自然语言处理 PyTorch
【自然语言处理NLP】Bert预训练模型、Bert上搭建CNN、LSTM模型的输入、输出详解
【自然语言处理NLP】Bert预训练模型、Bert上搭建CNN、LSTM模型的输入、输出详解
25 0
|
1月前
|
机器学习/深度学习 自然语言处理 数据格式
训练你自己的自然语言处理深度学习模型,Bert预训练模型下游任务训练:情感二分类
训练你自己的自然语言处理深度学习模型,Bert预训练模型下游任务训练:情感二分类
|
1月前
|
机器学习/深度学习 自然语言处理 PyTorch
Coggle 30 Days of ML(23年7月)任务九:学会Bert基础,transformer库基础使用
Coggle 30 Days of ML(23年7月)任务九:学会Bert基础,transformer库基础使用
|
1月前
|
机器学习/深度学习 自然语言处理 数据挖掘
预训练语言模型中Transfomer模型、自监督学习、BERT模型概述(图文解释)
预训练语言模型中Transfomer模型、自监督学习、BERT模型概述(图文解释)
70 0
|
10月前
|
人工智能 自然语言处理 PyTorch
NLP文本匹配任务Text Matching [有监督训练]:PointWise(单塔)、DSSM(双塔)、Sentence BERT(双塔)项目实践
NLP文本匹配任务Text Matching [有监督训练]:PointWise(单塔)、DSSM(双塔)、Sentence BERT(双塔)项目实践
NLP文本匹配任务Text Matching [有监督训练]:PointWise(单塔)、DSSM(双塔)、Sentence BERT(双塔)项目实践
|
11月前
|
机器学习/深度学习 存储 人工智能
大语言模型的预训练[1]:基本概念原理、神经网络的语言模型、Transformer模型原理详解、Bert模型原理介绍
大语言模型的预训练[1]:基本概念原理、神经网络的语言模型、Transformer模型原理详解、Bert模型原理介绍
大语言模型的预训练[1]:基本概念原理、神经网络的语言模型、Transformer模型原理详解、Bert模型原理介绍
|
机器学习/深度学习 缓存 人工智能
深度学习进阶篇-预训练模型[3]:XLNet、BERT、GPT,ELMO的区别优缺点,模型框架、一些Trick、Transformer Encoder等原理详解
深度学习进阶篇-预训练模型[3]:XLNet、BERT、GPT,ELMO的区别优缺点,模型框架、一些Trick、Transformer Encoder等原理详解
深度学习进阶篇-预训练模型[3]:XLNet、BERT、GPT,ELMO的区别优缺点,模型框架、一些Trick、Transformer Encoder等原理详解
|
机器学习/深度学习 人工智能 自然语言处理
从BERT到ChatGPT,百页综述梳理预训练大模型演变史(2)
从BERT到ChatGPT,百页综述梳理预训练大模型演变史
303 0
|
人工智能
从BERT到ChatGPT,百页综述梳理预训练大模型演变史(1)
从BERT到ChatGPT,百页综述梳理预训练大模型演变史
188 0
|
机器学习/深度学习 人工智能 分布式计算
SparK项目原作解读:卷积模型的首个BERT预训练
SparK项目原作解读:卷积模型的首个BERT预训练
205 0

热门文章

最新文章