一、背景介绍¶
本节是一个使用PyTorch实现的简单文本分类实战案例。在这个例子中,我们将使用AG News数据集进行文本分类。
AG News(AG's News Topic Classification Dataset)是一个广泛用于文本分类任务的数据集,尤其是在新闻领域。该数据集是由AG's Corpus of News Articles收集整理而来,包含了四个主要的类别:世界、体育、商业和科技
为了完成本节内容,需要安装好torchtext与portalocker库
二、加载数据¶
In [12]:import torch import torch.nn as nn import torchvision from torchvision import transforms, datasets import os,PIL,pathlib,warnings device = torch.device("cuda" if torch.cuda.is_available() else "cpu") warnings.filterwarnings("ignore") #忽略警告信息
安装torchtext的插曲¶
torchtext需要和pytorch/python版本严格对应,不能随意安装
- 首先在Jupyter里输入下方命令查看本机pytorch版本
- 然后,查看torchtext对应版本: torchtext
- 没有完全对应的版本则使用公式,设pytorch为1.a.b,则torchtext版本应该是0.a+1.b,我的pytorch版本是1.13.0,对应的torchtext版本应该是0.13.0
使用pip install torchtext==0.13.0安装会导致torch版本的升级或者降级,而且最离谱的是会变成CPU版本,所以不能这样子安装
直接pip安装,那么就会同时更新你的torch版本,但是torch版本直接影响到了对显卡的支持,和pysyft之类的库的关联使用。所以我们要指定对应版本来安装,不能让他自动升级我们的torch
卸载torch
pip uninstall torch pip uninstall torchtext
重新安装GPU版本的torch:
但是由于torch版本变了,所以torchvision的版本也要更新:torchvision包含一些常用的数据集、模型、转换函数等等。包括图片分类、语义切分、目标识别、实例分割、关键点检测、视频分类等工具。具体版本对应信息可见:https://github.com/pytorch/vision/blob/main/README.rst
2.0.0 0.15.1 >=3.8, <=3.11
而torchtext的对应信息可见于:https://pypi.org/project/torchtext/0.15.1/
conda install -c pytorch torchtext torchvisionIn [ ]:
# !pip install torchtext==0.13.0 # Installing collected packages: torch, torchtext # Attempting uninstall: torch # Found existing installation: torch 1.13.0 # Uninstalling torch-1.13.0: # Successfully uninstalled torch-1.13.0 # ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts. # torchvision 0.14.0 requires torch==1.13.0, but you have torch 1.12.0 which is incompatible. # torchaudio 0.13.0 requires torch==1.13.0, but you have torch 1.12.0 which is incompatible. # Successfully installed torch-1.12.0 torchtext-0.13.0In [ ]:
# !pip install portalockerIn [4]:
from torchtext.datasets import AG_NEWS train_iter = AG_NEWS(split='train') # 加载 AG News 数据集
torchtext.datasets.AG_NEWS 是一个用于加载 AG News 数据集的 TorchText 数据集类。AG News 数据集是一个用于文本分类任务的常见数据集,其中包含四个类别的新闻文章:世界、科技、体育和商业。torchtext.datasets.AG_NEWS 类加载的数据集是一个列表,其中每个条目都是一个元组,包含以下两个元素:
- 一条新闻文章的文本内容。
- 新闻文章所属的类别(一个整数,从1到4,分别对应世界、科技、体育和商业)。
三、构建词典¶
In [5]:from torchtext.data.utils import get_tokenizer from torchtext.vocab import build_vocab_from_iterator tokenizer = get_tokenizer('basic_english') # 返回分词器函数,训练营内“get_tokenizer函数详解”一文 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)函数,可以将一个字符串转换成一个单词的列表。这个函数可以接受两个参数:tokenizer和language,tokenizer参数指定要使用的分词器的名称。
想了解更多可看此链接:https://www.jianshu.com/p/f44046fdd317
In [6]:vocab(['here', 'is', 'an', 'example'])Out[6]:
[475, 21, 30, 5297]In [7]:
text_pipeline = lambda x: vocab(tokenizer(x)) label_pipeline = lambda x: int(x) - 1 text_pipeline('here is the an example')Out[7]:
[475, 21, 2, 30, 5297]In [8]:
label_pipeline('10')Out[8]:
9
四、生成数据批次和迭代器¶
In [9]: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) #返回维度dim中输入元素的累计和 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)
五、定义模型¶
定义TextClassificationModel模型,首先对文本进行嵌入,然后对句子嵌入之后的结果进行均值聚合
In [10]: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)
self.embedding.weight.data.uniform_(-initrange, initrange)这段代码是在 PyTorch 框架下用于初始化神经网络的词嵌入层(embedding layer)权重的一种方法。这里使用了均匀分布的随机值来初始化权重,具体来说,其作用如下:
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): 这是一个原地操作(in-place operation),用于将权重矩阵的值用一个均匀分布进行初始化。均匀分布的范围为 [-initrange, initrange],其中 initrange 是一个正数。
通过这种方式初始化词嵌入层的权重,可以使得模型在训练开始时具有一定的随机性,有助于避免梯度消失或梯度爆炸等问题。在训练过程中,这些权重将通过优化算法不断更新,以捕捉到更好的单词表示。
六、定义实例¶
In [13]:num_class = len(set([label for (label, text) in train_iter])) vocab_size = len(vocab) em_size = 64 model = TextClassificationModel(vocab_size, em_size, num_class).to(device)
七、定义训练函数与评估函数¶
In [14]:import time def train(dataloader): model.train() # 切换为训练模式 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() # grad属性归零 loss = criterion(predicted_label, label) # 计算网络输出和真实值之间的差距,label为真实值 loss.backward() # 反向传播 optimizer.step() # 每一步自动更新 # 记录acc与loss total_acc += (predicted_label.argmax(1) == label).sum().item() train_loss += loss.item() total_count += label.size(0) 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() # 切换为测试模式 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) # 计算loss值 # 记录测试数据 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
八、拆分数据集并运行模型¶
In [15]:from torch.utils.data.dataset import random_split from torchtext.data.functional import to_map_style_dataset # 超参数 EPOCHS = 10 # epoch LR = 5 # 学习率 BATCH_SIZE = 64 # batch size for training 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_valid_, 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.2f}s | ' 'valid_acc {:4.3f} valid_loss {:4.3f}'.format(epoch, time.time() - epoch_start_time, val_acc,val_loss)) print('-' * 69)
| epoch 1 | 500/1782 batches | train_acc 0.706 train_loss 0.01157 | epoch 1 | 1000/1782 batches | train_acc 0.868 train_loss 0.00617 | epoch 1 | 1500/1782 batches | train_acc 0.881 train_loss 0.00545 --------------------------------------------------------------------- | epoch 1 | time: 8.60s | valid_acc 0.897 valid_loss 0.005 --------------------------------------------------------------------- | epoch 2 | 500/1782 batches | train_acc 0.903 train_loss 0.00458 | epoch 2 | 1000/1782 batches | train_acc 0.906 train_loss 0.00438 | epoch 2 | 1500/1782 batches | train_acc 0.903 train_loss 0.00442 --------------------------------------------------------------------- | epoch 2 | time: 6.21s | valid_acc 0.906 valid_loss 0.004 --------------------------------------------------------------------- | epoch 3 | 500/1782 batches | train_acc 0.919 train_loss 0.00383 | epoch 3 | 1000/1782 batches | train_acc 0.916 train_loss 0.00391 | epoch 3 | 1500/1782 batches | train_acc 0.917 train_loss 0.00380 --------------------------------------------------------------------- | epoch 3 | time: 5.87s | valid_acc 0.904 valid_loss 0.004 --------------------------------------------------------------------- | epoch 4 | 500/1782 batches | train_acc 0.936 train_loss 0.00308 | epoch 4 | 1000/1782 batches | train_acc 0.940 train_loss 0.00296 | epoch 4 | 1500/1782 batches | train_acc 0.938 train_loss 0.00295 --------------------------------------------------------------------- | epoch 4 | time: 5.94s | valid_acc 0.915 valid_loss 0.004 --------------------------------------------------------------------- | epoch 5 | 500/1782 batches | train_acc 0.938 train_loss 0.00298 | epoch 5 | 1000/1782 batches | train_acc 0.941 train_loss 0.00285 | epoch 5 | 1500/1782 batches | train_acc 0.938 train_loss 0.00299 --------------------------------------------------------------------- | epoch 5 | time: 6.40s | valid_acc 0.916 valid_loss 0.004 --------------------------------------------------------------------- | epoch 6 | 500/1782 batches | train_acc 0.942 train_loss 0.00280 | epoch 6 | 1000/1782 batches | train_acc 0.938 train_loss 0.00297 | epoch 6 | 1500/1782 batches | train_acc 0.941 train_loss 0.00285 --------------------------------------------------------------------- | epoch 6 | time: 6.42s | valid_acc 0.915 valid_loss 0.004 --------------------------------------------------------------------- | epoch 7 | 500/1782 batches | train_acc 0.942 train_loss 0.00280 | epoch 7 | 1000/1782 batches | train_acc 0.943 train_loss 0.00283 | epoch 7 | 1500/1782 batches | train_acc 0.944 train_loss 0.00273 --------------------------------------------------------------------- | epoch 7 | time: 5.58s | valid_acc 0.917 valid_loss 0.004 --------------------------------------------------------------------- | epoch 8 | 500/1782 batches | train_acc 0.944 train_loss 0.00271 | epoch 8 | 1000/1782 batches | train_acc 0.944 train_loss 0.00273 | epoch 8 | 1500/1782 batches | train_acc 0.943 train_loss 0.00285 --------------------------------------------------------------------- | epoch 8 | time: 5.36s | valid_acc 0.916 valid_loss 0.004 --------------------------------------------------------------------- | epoch 9 | 500/1782 batches | train_acc 0.943 train_loss 0.00275 | epoch 9 | 1000/1782 batches | train_acc 0.945 train_loss 0.00270 | epoch 9 | 1500/1782 batches | train_acc 0.942 train_loss 0.00283 --------------------------------------------------------------------- | epoch 9 | time: 5.72s | valid_acc 0.916 valid_loss 0.004 --------------------------------------------------------------------- | epoch 10 | 500/1782 batches | train_acc 0.942 train_loss 0.00280 | epoch 10 | 1000/1782 batches | train_acc 0.943 train_loss 0.00280 | epoch 10 | 1500/1782 batches | train_acc 0.943 train_loss 0.00273 --------------------------------------------------------------------- | epoch 10 | time: 6.34s | valid_acc 0.916 valid_loss 0.004 ---------------------------------------------------------------------
torchtext.data.functional.to_map_style_dataset 函数的作用是将一个迭代式的数据集(Iterable-style dataset)转换为映射式的数据集(Map-style dataset)。这个转换使得我们可以通过索引(例如:整数)更方便地访问数据集中的元素。
在 PyTorch 中,数据集可以分为两种类型:Iterable-style 和 Map-style。Iterable-style 数据集实现了 iter() 方法,可以迭代访问数据集中的元素,但不支持通过索引访问。而 Map-style 数据集实现了 getitem() 和 len() 方法,可以直接通过索引访问特定元素,并能获取数据集的大小。
TorchText 是 PyTorch 的一个扩展库,专注于处理文本数据。torchtext.data.functional 中的 to_map_style_dataset 函数可以帮助我们将一个 Iterable-style 数据集转换为一个易于操作的 Map-style 数据集。这样,我们可以通过索引直接访问数据集中的特定样本,从而简化了训练、验证和测试过程中的数据处理。
九、使用测试数据集评估模型¶
In [16]:print('Checking the results of test dataset.') test_acc, test_loss = evaluate(test_dataloader) print('test accuracy {:8.3f}'.format(test_acc))
Checking the results of test dataset. test accuracy 0.910标签:acc,loss,batches,入门,torch,epoch,Pytorch,train,N1 From: https://www.cnblogs.com/cauwj/p/17337713.html