- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊 | 接辅导、项目定制
🏡我的环境:
- 语言环境:Python3.11.4
- 编译器:Jupyter Notebook
- torcch版本:2.0.1
1.加载数据
import torch
import torch. nn as nn
import torchvision
from torchvision import transforms,datasets
import os,PIL, pathlib,warnings
warnings.filterwarnings("ignore")
device = torch. device('mps')
device
device(type='mps')
from torchtext.datasets import AG_NEWS
train_iter = AG_NEWS(split='train')
2.构建词典
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
tokenizer = get_tokenizer('basic_english')
def yield_tokens(data_iter):
for _, text in data_iter:
yield tokenizer(text)
vocab = build_vocab_from_iterator(yield_tokens(train_iter),
specials=["<unk>"])
vocab.set_default_index(vocab["<unk>"])
torchtext.data.utils.get_tokenizer()是一个用于将文本数据分词的函数。它返回一个分词器(tokenizer)函数,可以将一个字符串转换成一个单词的列表。
3.生成数据批次和迭代器
from torch.utils.data import DataLoader
def collate_batch(batch):
label_list,text_list,offsets =[],[],[0]
for (_label,_text) in batch:
#标签列表
label_list.append(label_pipeline(_label))
#文本列表
processed_text = torch.tensor(text_pipeline(_text),dtype=torch.int64)
text_list.append(processed_text)
#偏移量,即语句的总词汇量
offsets.append(processed_text.size(0))
label_list = torch.tensor(label_list,dtype=torch.int64)
text_list = torch.cat(text_list)
offsets = torch.tensor(offsets[:-1]).cumsum(dim=0)
return label_list.to(device), text_list.to(device),offsets.to(device)
dataloader = DataLoader(train_iter,
batch_size=8,
shuffle =False,
collate_fn=collate_batch)
4.定义模型
from torch import nn
class TextClassificationModel(nn.Module):
def __init__(self, vocab_size, embed_dim, num_class):
super(TextClassificationModel, self).__init__()
self.embedding = nn.EmbeddingBag(vocab_size,
embed_dim,
sparse=False)
self.fc = nn.Linear(embed_dim, num_class)
self.init_weights()
def init_weights(self):
initrange = 0.5
self.embedding.weight.data.uniform_(-initrange, initrange)
self.fc.weight.data.uniform_(-initrange, initrange)
self.fc.bias.data.zero_()
def forward(self, text, offsets):
embedded = self.embedding(text, offsets)
return self.fc(embedded)
1.self.embedding :这是神经网络中的词嵌入层(embedding layer)。词嵌入层的作用是将离散的单词表示(通常为整数索引)映射为固定大小的连续向量。向量捕捉了单词之间的语义关系,作为网络的输入。
2.self.embedding.weight: 这是词嵌入层的权重矩阵,它的形状为“vocab_size,embedding_dim,”其中vocab_size是词汇表的大小,embedding_dim是嵌入向量的维度
3.self.embedding.weight.data :这是权重矩阵的数据部分,我们可以在这里直接操作其底层的张量。
4. .uniform_(-initrange,initrange):这是一个原地操作,用于将权重矩阵的值用一个均匀分布进行初始化。均匀分布的范围为[-initrange,initrange],其中initrange是一个正数。
5.定义函数
def train(dataloader):
model.train() # Switch to training mode
total_acc, train_loss, total_count = 0, 0, 0
log_interval = 500
start_time = time.time()
for idx, (label, text, offsets) in enumerate(dataloader):
predicted_label = model(text, offsets)
optimizer.zero_grad() # Zero out gradients
loss = criterion(predicted_label, label) # Compute the loss between predicted and true labels
loss.backward() # Backward pass to compute gradients
optimizer.step() # Update weights based on the computed gradients
# Record accuracy and loss
total_acc += (predicted_label.argmax(1) == label).sum().item()
train_loss += loss.item()
total_count += label.size(0)
# Print training progress
if idx % log_interval == 0 and idx > 0:
elapsed = time.time() - start_time
print('| epoch {:1d} | {:4d}/{:4d} batches '
'| train_acc {:4.3f} train_loss {:4.5f}'.format(epoch, idx, len(dataloader),
total_acc / total_count, train_loss / total_count))
total_acc, train_loss, total_count = 0, 0, 0
start_time = time.time()
def evaluate(dataloader):
model.eval() # Switch to evaluation mode
total_acc, train_loss, total_count = 0, 0, 0
with torch.no_grad():
for idx, (label, text, offsets) in enumerate(dataloader):
predicted_label = model(text, offsets)
loss = criterion(predicted_label, label) # Compute loss without backpropagation
# Record accuracy and loss for evaluation
total_acc += (predicted_label.argmax(1) == label).sum().item()
train_loss += loss.item()
total_count += label.size(0)
return total_acc / total_count, train_loss / total_count
6.训练模型
from torch.utils.data.dataset import random_split
from torch text.data.functional import to_map_style_dataset
EPOCHS =10
LR =5
BATCH_SIZE =64
criterion =torch.nn.CrossEntropyLoss
optimizer =torch.optim.SGD(model.parameters(),lr=LR)
scheduler =torch.optim.lr_scheduler.StepLR(optimizer,1.0,gamma=0.1)
total_accu = None
train_iter,test_iter =AG_News()
train_dataset = to_map_style_dataset(train_iter)
test_dataset = to_map_style_dataset(test_iter)
num_train = int(Len(train_dataset)* 0.95)
split_train_,split_valid_ = random_split(train_dataset,
[num_train,len(train_dataset)-num_train])
train_dataloader =DataLoader(split_train_,batch_size=BATCH_SIZE,
shuffle=True,collate_fn=collate_batch)valid_dataloader =DataLoader(split_train_,batch_size=BATCH_SIZE,
shuffle=True,collate_fn=collate_batch)
test_dataloader =DataLoader(test_dataset,batch_size=BATCH_SIZE,
shuffle=True,collate_fn=collate_batch)
for epoch in range(1,EPOCHS +1):
epoch_start_time =time.time()
train(train_dataloader)
val_acc,val_loss=evaluate(valid_dataloader)
if total_accu is not None and total_accu >val_acc:
scheduler.step()
else:
total_accu= val_acc
print('-'*69)
print('|epoch {:1d}|time:{:4.3f}s|'
'valid_acc{:4.3f}valid_loss{:4.3f}'.format(epoch,
time.time()-epoch_start_time,
val_acc,val_loss))
print('-'*69)
7.小结
AG News(AG's News Topic Classification Dataset)是一个广泛用于文本分类任务的数据集,尤其是在新闻领域。该数据集是由AG's Corpus of News Articles收集整理而来,包含了四个主要的类别:世界、体育、商业和科技。
TorchText 库是专用于自然语言处理的、基于 Pytorch 生态的第三方库,提供了对文本数据进行预处理的各种工具,但是没有如 TorchVision 库一样的各种已定义模型,如需使用定义好的预训练模型,需要使用 transformers 库。
TorchText 提供了 Field 对象来定义字段的处理方式,可以针对不同的数据样本定义不同的处理形式。定义 Field 对象,首先需要定义一个分词器,接着根据指定参数分别定义样本和标签的 Field,定义完 Field 之后,需要定义一个构建数据集的函数,接着使用该函数构建 dataset,构建的 train、valid、test 即可在 Pytorch 中使用。TorchText 可使用 Field 对象的 build_vocab 函数来构建词表,在 TorchText 中,DataLoader 被替换成 Iterator 和 BucketIterator。