bert-base-chinese中文文档分类 - text = []

📅 2026-12-01 👤 拼多多助力营销技巧 📂 拼多多助力2027 👁️ 498 次阅读

文章目录

一、数据准备1.1 代码:1.2 代码解释:

二、bert文本分类2.1 代码2.2 代码解释

三、bert代码的部分架构解释3.1 bert模型的输入3.2 hiden_outputs[0]3.3 微调参数3.4 bert分类结构

bert初学者笔记,有问题欢迎大佬指正!本文介绍了如果查看bert的结构,方便小白进行理解,在看了一些论文资料后,对bert有初步的了解,面对代码可能无从下手,但是在查看bert 的结构以后就清楚很多,对于bert 的输入、输出有具象化的了解。 本文代码参考: 基于BERT的新闻文本分类 BERT文本分类,代码超基础、超详细解析

一、数据准备

1.1 代码:

本文使用的excel存放数据: label表示分类标签,label=0的text都是0类别。本文将类别名称一同放在text,0的第一个text=高等数学(高数)表示0类别的文档标题是高等数学(高数),以此类推。 本文的原始数据是一堆docx文件,将文件名称和内容提出,放入excel,打上标签。

import pandas as pd

from docx import Document

import os

import re

# 读取 .docx 文件内容并分句

def read_doc(file_path):

try:

doc = Document(file_path)

text = []

for paragraph in doc.paragraphs:

text.append(paragraph.text)

content = '\n'.join(text)

# 去除 AAA 和 \n

content = content.replace('AAA', '').replace('\n', ' ').replace('#', ' ').replace('*', ' ')

# 按句号或感叹号分句

sentences = re.split(r'[。!]', content)

# 去除空字符串 拼多多帮助力入口

sentences = [s.strip() for s in sentences if s.strip()]

return sentences

except Exception as e:

print(f"Error reading {file_path}: {e}")

return []

# 从指定文件夹读取所有 .docx 文件并合并到一个 DataFrame 中

def load_data_from_folder(folder_path):

data = {

'label': [],

'text': []

}

id_counter = 0

for filename in os.listdir(folder_path):

if filename.endswith('.docx'):

file_path = os.path.join(folder_path, filename)

sentences = read_doc(file_path)

if sentences:

# 去除文件名中的 .docx 后缀

title = filename[:-5]

# 添加标题

data['label'].append(id_counter)

data['text'].append(title)

# 添加句子

for sentence in sentences:

# 去除句子中的 AAA、*、- 和多余空格

cleaned_sentence = sentence.replace('AAA', '').replace('*', '').replace('-', ' ')

cleaned_sentence = re.sub(r'\s+', ' ', cleaned_sentence).strip()

data['label'].append(id_counter)

data['text'].append(cleaned_sentence)

id_counter += 1

return pd.DataFrame(data)

def main():

folder_path = 'data'

data = load_data_from_folder(folder_path)

data.to_excel('bert.xlsx', index=False)

print("Data has been written to bert.xlsx")

if __name__ == '__main__':

main()

1.2 代码解释:

1.标签是从0开始标的,不是1,读者可以自行修改。 2.读取目录: 这个代码和我的docx文件的目录如下: 项目 ——代码 ——data文件夹 ————docx文件 因此我的folder_path写的就是‘data’,读者自行修改,不知道怎么改的交给ai生成代码。 3.剔除了docx文件中的AAA,#,*,等符号,读者可以自行修改。

二、bert文本分类

2.1 代码

import torch # PyTorch库

import pandas as pd # pandas库

import torch.nn as nn # PyTorch中的神经网络模块

from transformers import BertModel, BertTokenizer # transformer库

from sklearn.model_selection import train_test_split # 用于划分训练集和测试集

from torch.optim.lr_scheduler import StepLR

# 第一部分:加载训练集数据

train_set = pd.read_excel("bert.xlsx") # 读取训练数据

# BERT模型的名字

model_name = "bert-base-chinese"

tokenizer = BertTokenizer.from_pretrained(model_name)

model = BertModel.from_pretrained(model_name)

# 第二部分:定义BERT微调的神经网络模型

class BertClassfication(nn.Module):

def __init__(self):

super(BertClassfication, self).__init__()

self.model_name = 'bert-base-chinese'

self.model = BertModel.from_pretrained(self.model_name)

self.tokenizer = BertTokenizer.from_pretrained(self.model_name)

self.dropout = nn.Dropout(0.3) # 添加Dropout层,设置dropout概率为0.3

self.fc = nn.Linear(768, 4) # 输出4个类别

def forward(self, x):

# 对输入文本进行分词和编码,返回input_ids和attention_mask

batch_tokenized = self.tokenizer.batch_encode_plus(x, add_special_tokens=True,

max_length=148, padding='max_length', truncation=True)

input_ids = torch.tensor(batch_tokenized['input_ids'])

attention_mask = torch.tensor(batch_tokenized['attention_mask'])

# 获取BERT模型的输出

hiden_outputs = self.model(input_ids, attention_mask=attention_mask)

# 获取[CLS]标记对应的输出

outputs = hiden_outputs[0][:, 0, :]

outputs = self.dropout(outputs)

# 通过全连接层输出最终结果

output = self.fc(outputs)

return output

# 第三部分:准备数据集

sentences = train_set['text'].values

targets = train_set['label'].values

train_features, test_features, train_targets, test_targets = train_test_split(sentences, targets)

batch_size = 8

batch_count = int(len(train_features) / batch_size)

batch_train_inputs, batch_train_targets = [], []

for i in range(batch_count):

batch_train_inputs.append(train_features[i * batch_size: (i + 1) * batch_size])

batch_train_targets.append(train_targets[i * batch_size: (i + 1) * batch_size])

# 第四部分:训练模型

bertclassfication = BertClassfication()

lossfuction = nn.CrossEntropyLoss() # 使用交叉熵损失函数

optimizer = torch.optim.Adam(bertclassfication.parameters(), lr= 1e-5, weight_decay=1e-4)

scheduler = StepLR(optimizer, step_size=10, gamma=0.5) # 设置学习率调度器

# optimizer:这是你之前创建的优化器对象,例如 torch.optim.SGD 或 torch.optim.Adam 等。调度器会根据这个优化器来调整其学习率。

# step_size:这是一个整数,表示每隔多少个 epoch 学习率会被更新一次。在这个例子中,step_size=10 表示每 10 个 epoch 更新一次学习率。

# gamma:这是一个浮点数,表示每次更新学习率时的衰减因子。在这个例子中,gamma=0.5 表示每次更新时学习率会乘以 0.5,即减少一半。

epoch = 5

for _ in range(epoch):

los = 0

for i in range(batch_count):

inputs = batch_train_inputs[i]

targets = torch.tensor(batch_train_targets[i])

optimizer.zero_grad()

outputs = bertclassfication(inputs)

loss = lossfuction(outputs, targets) # 注意这里targets已经是0-25的标签

loss.backward()

optimizer.step()

los += loss.item()

if i % 5 == 0:

print(f"Batch:{i}, Loss: {los / 5:.4f}")

los = 0

scheduler.step()

# 第五部分:验证模型

hit = 0

total = len(test_features)

for i in range(total):

outputs = bertclassfication([test_features[i]])

_, predict = torch.max(outputs, 1) # 获取最大概率对应的标签

if predict == test_targets[i]: # 如果预测正确

hit += 1

print(f'准确率为 {hit / len(test_features):.4f}')

# 第六部分:对新文本进行预测

df = pd.read_excel('bert.xlsx')

result_dict = {}

# 遍历每个标签,并提取对应的文本

for label, group in df.groupby('label'):

first_text = group['text'].iloc[0]

result_dict[label] = first_text

# 对新文本进行预测

result = bertclassfication(["线性代数"])

_, result = torch.max(result, 1)

print(result_dict[result.item()])

2.2 代码解释

导入必要的库: 导入了PyTorch、pandas、transformers等库,用于数据处理、模型构建和训练。加载训练集数据: 读取Excel文件中的训练数据。定义BERT微调的神经网络模型: 定义了一个名为BertClassfication的类,继承自nn.Module。 在初始化方法中,加载预训练的BERT模型和分词器,添加Dropout层和全连接层。 在前向传播方法中,对输入文本进行分词和编码,通过BERT模型获取隐藏层输出,提取[CLS]标记对应的输出,通过Dropout层和全连接层输出最终结果。准备数据集: 提取训练数据中的文本和标签。 使用train_test_split将数据集划分为训练集和测试集。 定义批量大小和批量数量,将训练数据按批量组织。训练模型: 实例化模型,并定义损失函数、优化器和学习率调度器。 设定训练轮数,进入训练循环。 对每个批量的数据进行前向传播、计算损失、反向传播和参数更新。 每5个批量输出一次平均损失。 每个epoch结束后更新学习率。验证模型: 初始化命中次数和总样本数。 对每个测试样本进行前向传播,获取预测结果。 比较预测结果和真实标签,统计命中次数。 输出模型在测试集上的准确率。对新文本进行预测: 重新读取训练数据,创建一个字典,存储每个标签对应的一个文本示例。 对新文本进行前向传播,获取预测结果。 根据预测结果从字典中查找对应的文本示例并输出。

三、bert代码的部分架构解释

3.1 bert模型的输入

bert的输入: 代码中BERT模型的输入包括两部分: input_ids:这是经过分词和编码后的文本数据,表示每个单词在词汇表中的索引。每个句子被转换成一个固定长度的向量(在这个例子中,最大长度为148)。 attention_mask:这是一个与input_ids相同形状的张量,用于指示哪些位置是实际的单词(值为1),哪些位置是填充的(值为0)。这有助于模型忽略填充部分,专注于实际的输入文本。 在BERT模型中,通常不需要显式地提供position_ids。这是因为transformers库中的BertTokenizer和BertModel已经自动处理了位置嵌入(Positional Embeddings)

3.2 hiden_outputs[0]

hiden_outputs[0] hiden_outputs[0] 是BERT模型的主要输出,表示每个输入序列中每个词的隐藏状态。它的形状为 [batch_size, sequence_length, hidden_size]。 batch_size:批量大小,即一次前向传播处理的样本数量。 sequence_length:输入序列的最大长度。 hidden_size:每个词的隐藏状态的维度。hiden_outputs[0][0] hiden_outputs[0][0] 表示第一个输入序列中每个词的隐藏状态。它的形状为 [sequence_length, hidden_size]。 sequence_length:输入序列的最大长度。 hidden_size:每个词的隐藏状态的维度。hiden_outputs[0][0,0] hiden_outputs[0][0,0] 表示第一个输入序列中第一个词的隐藏状态。它的形状为 [hidden_size]。 hidden_size:每个词的隐藏状态的维度。hiden_outputs[0][0,0,0] hiden_outputs[0][0, 0, 0] 表示批量中的第一个序列的第一个词(即[CLS]标记)的隐藏状态中的第一个特征值。

须知:bert分类任务中使用 [CLS] 标记的隐藏状态作为整个输入序列的表示,因此只用提取所有序列的第一个词的所有特征即可,中间的数字是0. hiden_outputs[0][:, 0, :] 表示每个输入序列中第一个词([CLS]标记)的隐藏状态表示。

3.3 微调参数

optimizer = torch.optim.Adam(bertclassfication.parameters(), lr=1e-5, weight_decay=1e-4)

bertclassfication.parameters() 返回了模型中所有需要优化的参数,包括BERT模型本身的参数、Dropout层的参数和全连接层的参数。Adam优化器会根据梯度更新这些参数。

如果想要打印所有的优化参数:

bertclassfication = BertClassfication()

for name, param in bertclassfication.named_parameters():

print(f"Parameter Name: {name}, Shape: {param.shape}")

输出示例

3.4 bert分类结构

查看模型结构

# 实例化模型

bertclassfication = BertClassfication()

# 打印整个模型的结构

print(bertclassfication)

# 打印 embeddings 层的结构

print("Embeddings Layer:")

print(bertclassfication.model.embeddings)

# 打印 encoder 层的结构

print("Encoder Layer:")

print(bertclassfication.model.encoder)

输出示例

BertClassfication(

(model): BertModel(

(embeddings): BertEmbeddings(

(word_embeddings): Embedding(21128, 768, padding_idx=0)

(position_embeddings): Embedding(512, 768)

(token_type_embeddings): Embedding(2, 768)

(LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)

(dropout): Dropout(p=0.1, inplace=False)

)

(encoder): BertEncoder(

(layer): ModuleList(

(0-11): 12 x BertLayer(

(attention): BertAttention(

(self): BertSdpaSelfAttention(

(query): Linear(in_features=768, out_features=768, bias=True)

(key): Linear(in_features=768, out_features=768, bias=True)

(value): Linear(in_features=768, out_features=768, bias=True)

(dropout): Dropout(p=0.1, inplace=False)

)

(output): BertSelfOutput(

(dense): Linear(in_features=768, out_features=768, bias=True)

(LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)

(dropout): Dropout(p=0.1, inplace=False)

)

)

(intermediate): BertIntermediate(

(dense): Linear(in_features=768, out_features=3072, bias=True)

(intermediate_act_fn): GELUActivation()

)

(output): BertOutput(

(dense): Linear(in_features=3072, out_features=768, bias=True)

(LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)

(dropout): Dropout(p=0.1, inplace=False)

)

)

)

)

(pooler): BertPooler(

(dense): Linear(in_features=768, out_features=768, bias=True)

(activation): Tanh()

)

)

(dropout): Dropout(p=0.3, inplace=False)

(fc): Linear(in_features=768, out_features=26, bias=True)

)

Embeddings Layer:

BertEmbeddings(

(word_embeddings): Embedding(21128, 768, padding_idx=0)

(position_embeddings): Embedding(512, 768)

(token_type_embeddings): Embedding(2, 768)

(LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)

(dropout): Dropout(p=0.1, inplace=False)

)

Encoder Layer:

BertEncoder(

(layer): ModuleList(

(0-11): 12 x BertLayer(

(attention): BertAttention(

(self): BertSdpaSelfAttention(

(query): Linear(in_features=768, out_features=768, bias=True)

(key): Linear(in_features=768, out_features=768, bias=True)

(value): Linear(in_features=768, out_features=768, bias=True)

(dropout): Dropout(p=0.1, inplace=False)

)

(output): BertSelfOutput(

(dense): Linear(in_features=768, out_features=768, bias=True)

(LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)

(dropout): Dropout(p=0.1, inplace=False)

)

)

(intermediate): BertIntermediate(

(dense): Linear(in_features=768, out_features=3072, bias=True)

(intermediate_act_fn): GELUActivation()

)

(output): BertOutput(

(dense): Linear(in_features=3072, out_features=768, bias=True)

(LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)

(dropout): Dropout(p=0.1, inplace=False)

)

)

)

)

本文中的classification拼写为classfication,读者注意一下,不是正常的英语分类单词。

bert-base-chinese中文文档分类

参考阅读

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧