使用TorchText库进行文本分类

使用Torchtext库进行文本分类(官方的例子)

配置:

torch                  1.8.1+cpu
torchtext              0.9.1

官方文档的链接:https://pytorch.org/tutorials/beginner/text_sentiment_ngrams_tutorial.html

文章中关于AG_NEWS数据集一会儿能加载出来,一会儿加载不出来(什么时候是否需要splite),我也没搞懂,感觉不是重点,有大佬懂的话可以在评论区讲一下哈(感谢)!

(1)读入新闻类型的数据,这里使用的AG_NEWS数据集

由于直接使用官网下载会报错,先下载数据集,再使用下面的方法加载数据集

下载数据集的链接:https://pan.baidu.com/s/1Rz_XoaTZWSRiHGOwkACosQ  提取码:j0no 

数据集简介:4类新闻,分别是 World、 Sports、Business、Sci/Tec(依次用0-3表示)

csv文件有三列,分别是label、title、new

import torch
from torchtext.datasets import AG_NEWS

path = 'C:/Users/USER/Desktop/AG_NEWS.data'#改成你数据集存放的路径
train_data, test_dataset = AG_NEWS(root=path, split=('train', 'test'))

(2)构建词汇表

from torchtext.data.utils import get_tokenizer
from collections import Counter
from torchtext.vocab import Vocab

tokenizer = get_tokenizer('basic_english')
train_iter = AG_NEWS(split='train')
counter = Counter()
for (label, line) in train_iter:
    counter.update(tokenizer(line))#统计每次词出现的频率
vocab = Vocab(counter, min_freq=1)#构建词汇表,min_freq表示指定最小的频次是1
#print(vocab.freqs) #查看词汇及其对应的频率

#词汇表将token转换为整数
for token in ['here', 'is', 'an', 'example']:#测试用例    
    print(vocab[token])

Vocab  待补充

https://pytorch.org/text/stable/vocab.html

 

(3)生成数据批处理和迭代器

text_pipeline、label_pipeline建立文本、标签处理管道,用于处理来自数据集迭代器的原始数据字符串(转换为数值型)

text_pipeline = lambda x: [vocab[token] for token in tokenizer(x)]
label_pipeline = lambda x: int(x) - 1
#print(text_pipeline('here is the an example'))#文本管道,将字符串转换为索引,
#输出&

你可能感兴趣的:(深度学习,NLP,自然语言处理,深度学习,pytorch)