PyTorch翻译官网教程-TEXT CLASSIFICATION WITH THE TORCHTEXT LIBRARY

【NLP工具】——torchtext 概述 在处理NLP任务时除了需要优秀的神经网络还需要方便、高效的数据预处理工具。今天介绍一款优秀的NLP数据处理工具torchtext。 NLP常见的数据预处理工作如下: Load File:数据文件加载; Tokenization:分词; Create Vocabulary:创建字典; Indexify:将词与索引进行映射; Word Vectors:创建或加载词向量; Padding or ... 阅读详情

官网链接

Text classification with the torchtext library — PyTorch Tutorials 2.0.1+cu117 documentation

使用torchtext库进行文本分类

在本教程中,我们将展示如何使用torchtext库来构建用于文本分类分析的数据集。

  • 使用迭代器访问原始数据
  • 构建数据处理管道,将原始文本字符串转换为torch.Tensor ,可以用来训练模型
  • 使用torch.utils.data.DataLoader对数据进行清洗和迭代

先决条件

在运行本教程之前,需要安装portalocker包的最新2.x版本。例如,在Colab环境中,可以通过在脚本顶部添加以下行来完成:

!pip install -U portalocker>=2.0.0`

访问原始数据集迭代器

torchtext库提供了一些原始数据集迭代器,用于生成原始文本字符串。例如,AG_NEWS数据集迭代器以标签和文本元组的形式生成原始数据。

要访问torchtext数据集,请按照https://github.com/pytorch/data上的说明安装torchdata。

import torch
from torchtext.datasets import AG_NEWS

train_iter = iter(AG_NEWS(split="train"))

next(train_iter)
>>> (3, "Fears for T N pension after talks Unions representing workers at Turner
Newall say they are 'disappointed' after talks with stricken parent firm Federal
Mogul.")

next(train_iter)
>>> (4, "The Race is On: Second Private Team Sets Launch Date for Human
Spaceflight (SPACE.com) SPACE.com - TORONTO, Canada -- A second\\team of
rocketeers competing for the  #36;10 million Ansari X Prize, a contest
for\\privately funded suborbital space flight, has officially announced
the first\\launch date for its manned rocket.")

next(train_iter)
>>> (4, 'Ky. Company Wins Grant to Study Peptides (AP) AP - A company founded
by a chemistry researcher at the University of Louisville won a grant to develop
a method of producing better peptides, which are short chains of amino acids, the
building blocks of proteins.')

准备数据处理管道

我们回顾了torchtext库的基本组件,包括词汇表、词向量和分词器。这些是原始文本字符串的基本数据处理模块。

下面是一个使用分词器和词汇表进行典型NLP数据处理的示例。第一步是使用原始训练数据集构建一个词汇表。这里我们使用内置的工厂函数build_vocab_from_iterator,它接受生成列表的迭代器或者单词列表的迭代器。用户还可以传递任何要添加到词汇表中的特殊符号。

from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator

tokenizer = get_tokenizer("basic_english")
train_iter = AG_NEWS(split="train")


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>"])

词汇表块将单词列表转换为整数。

vocab(['here', 'is', 'an', 'example'])
>>> [475, 21, 30, 5297]

使用分词器和词汇表准备文本处理管道。文本和标签管道将用于处理来自数据集迭代器的原始数据字符串。

text_pipeline = lambda x: vocab(tokenizer(x))
label_pipeline = lambda x: int(x) - 1

文本管道根据词汇表中定义的查找表将文本字符串转换为整数列表。标签管道将标签转换为整数。例如,

text_pipeline('here is the an example')
>>> [475, 21, 2, 30, 5297]
label_pipeline('10')
>>> 9

生成数据批处理和迭代器

建议PyTorch用户使用torch.utils.data.DataLoader(这里有一个教程here).它使用map风格的数据集,实现了getitem()和len()协议,表示从索引/键到数据样本的映射。它也适用于shuffle参数为False的可迭代数据集。

在发送到模型之前,collate_fn函数处理从DataLoader生成的一批样本。collate_fn的输入是DataLoader中批量大小相同的一批数据,collate_fn根据之前声明的数据处理管道来处理它们。注意这里,确保collate_fn被声明为顶级定义。这确保了该函数在每个worker中都可用。

在这个例子中,原始数据批量输入中的文本条目被打包到一个列表中,并连接为一个张量,用于nn.EmbeddingBag 的输入。偏移量是一个分隔符张量,表示文本张量中单个序列的起始索引。Label是一个张量,保存每个文本条目的标签。

from torch.utils.data import DataLoader

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")


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)
    offsets = torch.tensor(offsets[:-1]).cumsum(dim=0)
    text_list = torch.cat(text_list)
    return label_list.to(device), text_list.to(device), offsets.to(device)


train_iter = AG_NEWS(split="train")
dataloader = DataLoader(
    train_iter, batch_size=8, shuffle=False, collate_fn=collate_batch
)

定义模型

该模型由 nn.EmbeddingBag 层和用于分类的线性层组成。使用模式模式”mean“ 的nn.EmbeddingBag 计算”bag“ Embedding的平均值。尽管这里的文本条目具有不同的长度,但nn.EmbeddingBag模块在这里不需要填充,因为文本长度保存在偏移量中。

此外,由于nn.EmbeddingBag在运行中累计了所有Embedding的平均值,因此nn.EmbeddingBag可以提高处理一系列张量的性能和内存效率。

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)


初始化实例

AG_NEWS数据集有4个标签,因此类别数为4

1 : World
2 : Sports
3 : Business
4 : Sci/Tec


我们构建了一个embedding维度为64的模型。词汇表的大小等于词汇表实例的长度。类别的数量等于标签的数量,

train_iter = AG_NEWS(split="train")
num_class = len(set([label for (label, text) in train_iter]))
vocab_size = len(vocab)
emsize = 64
model = TextClassificationModel(vocab_size, emsize, num_class).to(device)

定义函数来训练模型和评估结果

import time


def train(dataloader):
    model.train()
    total_acc, total_count = 0, 0
    log_interval = 500
    start_time = time.time()

    for idx, (label, text, offsets) in enumerate(dataloader):
        optimizer.zero_grad()
        predicted_label = model(text, offsets)
        loss = criterion(predicted_label, label)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 0.1)
        optimizer.step()
        total_acc += (predicted_label.argmax(1) == label).sum().item()
        total_count += label.size(0)
        if idx % log_interval == 0 and idx > 0:
            elapsed = time.time() - start_time
            print(
                "| epoch {:3d} | {:5d}/{:5d} batches "
                "| accuracy {:8.3f}".format(
                    epoch, idx, len(dataloader), total_acc / total_count
                )
            )
            total_acc, total_count = 0, 0
            start_time = time.time()


def evaluate(dataloader):
    model.eval()
    total_acc, total_count = 0, 0

    with torch.no_grad():
        for idx, (label, text, offsets) in enumerate(dataloader):
            predicted_label = model(text, offsets)
            loss = criterion(predicted_label, label)
            total_acc += (predicted_label.argmax(1) == label).sum().item()
            total_count += label.size(0)
    return total_acc / total_count

分割数据集并运行模型

由于原始AG_NEWS没有验证数据集,我们将训练数据集划分为训练集/验证集,划分比为0.95(训练集)和0.05(验证集)。这里我们使用torch.utils.data.dataset.random_split 。PyTorch核心库中的random_split函数。

CrossEntropyLoss(交叉熵损失)准则将nn.LogSoftmax()和nn.NLLLoss()组合在一个类中。当训练包含C类的分类问题时,它很有用。SGD采用随机梯度下降法作为优化器。初始学习率设置为5.0。这里使用StepLR 通过epoch调整学习率。

from torch.utils.data.dataset import random_split
from torchtext.data.functional import to_map_style_dataset

# Hyperparameters
EPOCHS = 10  # epoch
LR = 5  # learning rate
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)
    accu_val = evaluate(valid_dataloader)
    if total_accu is not None and total_accu > accu_val:
        scheduler.step()
    else:
        total_accu = accu_val
    print("-" * 59)
    print(
        "| end of epoch {:3d} | time: {:5.2f}s | "
        "valid accuracy {:8.3f} ".format(
            epoch, time.time() - epoch_start_time, accu_val
        )
    )
    print("-" * 59)

输出

| epoch   1 |   500/ 1782 batches | accuracy    0.694
| epoch   1 |  1000/ 1782 batches | accuracy    0.856
| epoch   1 |  1500/ 1782 batches | accuracy    0.877
-----------------------------------------------------------
| end of epoch   1 | time: 12.46s | valid accuracy    0.886
-----------------------------------------------------------
| epoch   2 |   500/ 1782 batches | accuracy    0.898
| epoch   2 |  1000/ 1782 batches | accuracy    0.899
| epoch   2 |  1500/ 1782 batches | accuracy    0.906
-----------------------------------------------------------
| end of epoch   2 | time: 11.99s | valid accuracy    0.895
-----------------------------------------------------------
| epoch   3 |   500/ 1782 batches | accuracy    0.916
| epoch   3 |  1000/ 1782 batches | accuracy    0.913
| epoch   3 |  1500/ 1782 batches | accuracy    0.915
-----------------------------------------------------------
| end of epoch   3 | time: 12.07s | valid accuracy    0.894
-----------------------------------------------------------
| epoch   4 |   500/ 1782 batches | accuracy    0.930
| epoch   4 |  1000/ 1782 batches | accuracy    0.932
| epoch   4 |  1500/ 1782 batches | accuracy    0.929
-----------------------------------------------------------
| end of epoch   4 | time: 12.06s | valid accuracy    0.902
-----------------------------------------------------------
| epoch   5 |   500/ 1782 batches | accuracy    0.932
| epoch   5 |  1000/ 1782 batches | accuracy    0.933
| epoch   5 |  1500/ 1782 batches | accuracy    0.931
-----------------------------------------------------------
| end of epoch   5 | time: 12.04s | valid accuracy    0.902
-----------------------------------------------------------
| epoch   6 |   500/ 1782 batches | accuracy    0.933
| epoch   6 |  1000/ 1782 batches | accuracy    0.932
| epoch   6 |  1500/ 1782 batches | accuracy    0.935
-----------------------------------------------------------
| end of epoch   6 | time: 12.02s | valid accuracy    0.903
-----------------------------------------------------------
| epoch   7 |   500/ 1782 batches | accuracy    0.934
| epoch   7 |  1000/ 1782 batches | accuracy    0.933
| epoch   7 |  1500/ 1782 batches | accuracy    0.935
-----------------------------------------------------------
| end of epoch   7 | time: 12.09s | valid accuracy    0.903
-----------------------------------------------------------
| epoch   8 |   500/ 1782 batches | accuracy    0.935
| epoch   8 |  1000/ 1782 batches | accuracy    0.933
| epoch   8 |  1500/ 1782 batches | accuracy    0.935
-----------------------------------------------------------
| end of epoch   8 | time: 12.10s | valid accuracy    0.904
-----------------------------------------------------------
| epoch   9 |   500/ 1782 batches | accuracy    0.934
| epoch   9 |  1000/ 1782 batches | accuracy    0.934
| epoch   9 |  1500/ 1782 batches | accuracy    0.934
-----------------------------------------------------------
| end of epoch   9 | time: 12.05s | valid accuracy    0.904
-----------------------------------------------------------
| epoch  10 |   500/ 1782 batches | accuracy    0.934
| epoch  10 |  1000/ 1782 batches | accuracy    0.936
| epoch  10 |  1500/ 1782 batches | accuracy    0.933
-----------------------------------------------------------
| end of epoch  10 | time: 12.00s | valid accuracy    0.905
-----------------------------------------------------------


使用测试数据集评估模型

检查测试数据集的结果……

print("Checking the results of test dataset.")
accu_test = evaluate(test_dataloader)
print("test accuracy {:8.3f}".format(accu_test))

输出

Checking the results of test dataset.
test accuracy    0.907

测试一个随机的新闻

使用迄今为止最好的模型,测试一个高尔夫新闻。

ag_news_label = {1: "World", 2: "Sports", 3: "Business", 4: "Sci/Tec"}


def predict(text, text_pipeline):
    with torch.no_grad():
        text = torch.tensor(text_pipeline(text))
        output = model(text, torch.tensor([0]))
        return output.argmax(1).item() + 1


ex_text_str = "MEMPHIS, Tenn. – Four days ago, Jon Rahm was \
    enduring the season’s worst weather conditions on Sunday at The \
    Open on his way to a closing 75 at Royal Portrush, which \
    considering the wind and the rain was a respectable showing. \
    Thursday’s first round at the WGC-FedEx St. Jude Invitational \
    was another story. With temperatures in the mid-80s and hardly any \
    wind, the Spaniard was 13 strokes better in a flawless round. \
    Thanks to his best putting performance on the PGA Tour, Rahm \
    finished with an 8-under 62 for a three-stroke lead, which \
    was even more impressive considering he’d never played the \
    front nine at TPC Southwind."

model = model.to("cpu")

print("This is a %s news" % ag_news_label[predict(ex_text_str, text_pipeline)])

输出

This is a Sports news

 

基于IC动态加权的机器学习多因子选股策略:从模型融合到实战回测 在量化投资领域,多因子选股模型通过挖掘市场数据中的有效信号来预测股票收益。其核心原理在于利用统计学与机器学习算法,从海量因子中识别出与未来收益具有稳定相关性的特征。这一技术的核心价值在于将主观投资决策转化为系统化、可重复的客观过程,从而在控制风险的前提下追求超额收益。其典型应用场景包括股票阿尔法策略构建、Smart Beta产品设计以及资产配置中的股票筛选环节。本文聚焦于如何通过信息系数(IC)这一关键指标,动态融合Ridge回归、MLP神经网络和随机森林等多个预测模型,构建一个能够自适应市场风格轮动的选股 阅读详情

相关推荐

Bulk / Smart-seq2数据分析一般流程

Bulk RNA-seq(RNA-Seq of bulk samples)是一种RNA-Seq技术应用,它是通过将整个组织或细胞群体的RNA提取并混合,进行高通量测序来分析基因表达的技术。转录本定量结果可以用于后续的差异表达分析和聚类分析。功能注释和富集分析:对差异表达基因进行功能注释和富集分析,以帮助理解差异表达基因的功能和调控网络,从而获得对研究样品的更深入的理解。数据可视化:最后,将聚类分析的结果进行可视化,可以使用常见的数据可视化工具,如ggplot2、Plotly等,来帮助用户更好地理解数据。

weixin_54519672的博客 5353

安装完anaconda以及pytorch后,torchtext的安装步骤

pytorch安装 torchtext安装

qq_43515340的博客 4358

Frida动态Hook实战:逆向美团外卖mtgsig3.0签名算法

在移动应用安全与数据爬取领域,API签名是保障请求合法性与数据完整性的核心机制。其原理是通过特定算法,将请求参数、时间戳等动态要素加密生成唯一字符串,服务器端通过验签防止数据篡改与伪造。这项技术的核心价值在于,它构建了客户端与服务器之间的可信通道,是移动端数据交互安全的基础。在自动化测试、安全审计、市场数据分析等应用场景中,理解并能够获取或绕过签名验证是关键前提。本文聚焦于美团外卖App的核心签名参数mtgsig3.0,针对其复杂的算法逻辑,提供了一套基于Frida的动态Hook解决方案。通过Hook技术,

weixin_33935636的博客 835

如何下载指定版本的torchtext

命令: pip install torchtext==0.9.0 目前最新的是0.10.0,但是要求torch=1.9.0。所以我换了低版本的torchtext。 其他版本见 进入官网:https://pypi.org/project/torchtext/0.9.0/#history。

qq_43391414的博客 5652

ESP32蓝牙广播数据自定义指南:让你的设备更容易被手机发现

本文详细介绍了如何通过自定义ESP32蓝牙广播数据提升设备在手机端的可发现性。从广播数据结构、扫描响应优化到跨平台兼容性设置,提供了全面的技术指南和实战代码示例,帮助开发者解决智能硬件开发中的蓝牙连接难题。

weixin_29172201的博客 273

三维点云孔洞修复(附Python代码和公共点云数据集链接)

(1)物体自身缺失(2)物体自身形状复杂,很多凹凸面不够规则甚至存在空腔,空腔内部无法被三维激光扫描仪扫描到(3)物体部分区域对激光扫描不敏感,未被扫描上(4)扫描仪的扫描稳定性。

yanghl1215的博客 6954

torchtext安装实坑

关于torchtext安装的注意点

weixin_45893089的博客 1119

互联网金融项目实战(大数据Hadoop hive)

什么是互联网金融? 互联网金融 --> 信贷(信用贷款) --> 支付宝率先搞了一个信用体系 互联网金融: 在线支付、P2P 银行: 只会锦上添画、不喜欢雪中送炭 银行害怕出现坏账 ( 储户存钱,银行放贷 赚个利息差 ) 银行是可以倒闭的 保险公司不允许倒闭 银行分为:商业银行(自生自灭的)和非商业银行(国家的) 中国工商银行 全球第一大行 招商银行(清朝的一个李鸿章) 中国银行(历史超过 100 年了) 国家政策:希望银行能够扶持中小型企业 p2p:网络借贷平台 民间吸纳贷款 -->

weixin_58276266的博客 1553

安装torchtext

在阅读pytroch版本的《动手学深度学习》第七章时,源码需要安装torchtext。直接使用pip安装 pip install torchtext 会更新pytorch,这时会卸载旧的pytorch,安装的新版本pytorch可能会不兼容。 最后我在 https://github.com/pytorch/text/找到pytorch与torchtext版本对应关系: 我的pytorch是1.8版本,因此安装0.8版本的torchtext,命令如下: pip install torchtext==0.8

weixin_41496173的博客 2718

如何用Python+Librosa实现轴承异响检测?5步搞定工业设备故障预警

本文详细介绍了如何利用Python和Librosa库,通过5个步骤构建工业轴承异响检测与故障预警系统。从音频采集、预处理、频谱特征提取,到构建机器学习模型并进行实时监测,提供了完整的代码级解决方案。该方法能有效识别轴承早期故障特征,实现低成本、高效的设备预测性维护。

rnn9storyteller的博客 634

safetymonitorapi

Summary of SA8653 Safety Monitor API Introduction This document details Safety Monitor APIs for the SA8653 QNNX platform, covering dual interfaces of APSS and SAIL. It defines core data structures and enumerations for subsystems, fault severity and health

qq_39257814的博客 1592

Pytorch笔记-6

Text Classification with the torchtext library 本教程,我们将展示如何使用torchtext库,构建文本分类分析用的数据集。用户将能灵活做以下几项: Access to raw data as iterator Build data processing pipeline to convert the raw text strings into torch.Tensor that can be used to train the model Shuffle a

寒飞雪的博客 741

GLM-4本地部署的实战教程

本文主要介绍了GLM-4-9B本地部署的实战教程,希望对学习和使用大模型的同学们有所帮助。 文章目录 1. 前言 2. 配置环境 2.1 安装虚拟环境 2.2 安装依赖库 2.3 下载模型文件 3. 运行glm-4-9b-chat

herosunly的博客 25万+

五大主流神经网络原理与实战速成:从CNN到GNN的完整指南

神经网络作为人工智能的核心技术,通过模拟人脑神经元连接进行信息处理,其核心原理在于通过层次化结构自动学习数据特征。从基础的卷积神经网络(CNN)到处理序列的循环神经网络(RNN),再到近年来兴起的Transformer和生成对抗网络(GAN),每种架构都针对特定数据类型和任务设计,在图像识别、自然语言处理等领域展现出巨大技术价值。本文聚焦于五大主流架构的实战应用,通过PyTorch代码示例,手把手指导读者在经典数据集上实现模型,帮助初学者快速跨越从理论到实践的鸿沟,掌握构建和调试神经网络的关键技能。

weixin_30808693的博客 309

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Torchtext 0.12+新版API学习与使用示例(1)

torchtext 文档页面:https://pytorch.org/text/stable/index.html torchtext github页面:https://github.com/pytorch/text 示例代码 from torchtext.vocab import vocab from collections import Counter, OrderedDict sentence = "Natural language processing strives to build mach

呆萌的代Ma 3009

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

Torchtext下的AG_NEWS数据集进行分类(官方文档代码)

原链接:Text classification with the torchtext library — PyTorch Tutorials 1.11.0+cu102 documentation (1)导入数据集(经常会出现数据集下载失败的情况),有大佬的网盘:https://pan.baidu.com/s/1Rz_XoaTZWSRiHGOwkACosQ,提取码:j0no 下载完直接放到当前打开jupyter notebook的目录下,地址就到AG_NEWS.data文件夹即可 (现在的版本好像要..

killer2021的博客 6136

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

torchtext安装教程

记录一下我安装torchtext的过程和坑。由于程序需要调用torchtext,但pycharm里没有,因此只能通过命令行安装。ps:最好先看看你代码里调的库在哪些版本里有、你的需求是什么,有的库在较老的版本才有。是torchtext官网,可查看对应pytorch和python的版本。

weixin_65589309的博客 1159

安装torchtext终极办法

由上图可以看到torch版本为1.11.0,所以我要下载的torchtext版本为0.12.0.查看pytorch版本,然后对应下表找到对应的torchtext版本。

swx595182208的博客 552

torchtext使用教程(文本预处理、数据集封装)

 ????torchtext是一个用于文本预处理的库,使用起来也十分简便。  这是torchtext的github链接:https://github.com/pytorch/text 它主要包含了以下3大组件: ⭐Field对象:  指定要如何处理某个字段,比如指定分词方法,是否转成小写,起始字符,结束字符,补全字符以及词典等。 ⭐Dataset类:  用于加载数据,torchtext的Dataset是继承自pytorch的Dataset,提供了一个可以下载压缩数据并解压的方法(支持.zip, .gz, .

weixin_43646592的博客 4434

PyTorch官方教程笔记:文本主题

本文是对本人所撰写文本主题的PyTorch官方教程的笔记的总体目录。

诸神缄默不语的博客 2352

torchtext简要使用说明

原文链接:https://blog.youkuaiyun.com/u012436149/article/details/79310176 torchtext官方文档:https://torchtext.readthedocs.io/en/latest/data.html 以下文章转载部分 文章部分翻译自 http://anie.me/On-Torchtext/ API一览 torchtext.data torchtext.data.Example : 用来表示一个样本,数据+标签 torchtext.voca

rocking_struggling的博客 1642

torchtext 安装,与pytorch版本匹配

目录报错:ModuleNotFoundError: No module named ‘torchtext’1. torchtext版本与pytorch版本匹配的问题1.1 查看pytorch版本1.2 查找对应 torchtext版本2. pip安装torchtext 没想到安装一个torchtext,查看了好几篇博客!于是梳理总结了一下~ 报错:ModuleNotFoundError: No module named ‘torchtext’ torchtext是pytorch框架中用于文本处理的。需要im

qq_41386947的博客 2万+

torchtext 安装

在Anaconda Prompt窗口中输入命令:conda install -c derickl torchtext 即可安装成功

Janice的博客 6255

torch 、torchtext、python 对应版本

goodfake 1万+

torchtext入门教程,轻松玩转文本数据处理

用深度学习做nlp也有一段时间了,熟悉这块内容的同学都知道,实践算法的时候,写模型是个简单的事,最麻烦的是数据处理,数据处理不仅会浪费我们大部分时间,而且会消耗很大的计算资源,浪费人力物力。今年开始接触pytorch,简洁的API,动态图,更加灵活的编写模式,诸多优点不用多说。最近尝试使用torchtext工具,这里想先说明的是,torchtext并不是pytorch所独有的,使用其它深度学习框架...

u014514939的博客 3813

torchtext学习总结

文章目录TorchText概述Field对象Dataset迭代器具体使用使用Dataset类自定义Dataset类构建数据集构建词表最简单的方法:build_vocab()方法中传入用于构建词表的数据集使用预训练词向量构建迭代器批数据的使用在模型中指定Embedding层的权重使用torchtext构建的数据集用于LSTM一个使用torchtext内置数据集的例子读取json文件并生成batch设...

Leokb24的博客 2万+
上一篇: PyTorch翻译官网教程-NLP FROM SCRATCH: TRANSLATION WITH A SEQUENCE TO SEQUENCE NETWORK AND ATTENTION
下一篇: PyTorch翻译官网教程-PROFILING YOUR PYTORCH MODULE
poorCoder_
博客等级 码龄10年 129粉丝 41原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值