pytorch实现的TextCNN(Dataset, DataLoader的使用)

本文介绍了如何使用PyTorch构建TextCNN模型,并探讨了Dataset和DataLoader在训练过程中的应用,旨在提供深度学习文本分类的实践示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要是Dataset, DataLoader的使用


(1)数据处理,生成Batch和向量化词表

import torch
import numpy as np
from tqdm import tqdm
from torch.utils.data import Dataset, DataLoader

tokenizer = lambda x: [y for y in x]
UNK, PAD = '<UNK>', '<PAD>'  # 未知字,padding符号


def build_vocab(path, max_size, freq_min):
    vocab_dic = {
   }
    with open(path, "r", encoding="utf-8") as f:
        for sentences in tqdm(f):
            sentence = sentences.strip()
            if not sentence:
                continue
            content = sentence.split("\t")[0]
            for word in tokenizer(content):
                vocab_dic[word] = vocab_dic.get(word, 0) + 1
        vocab_list = sorted([_ for _ in vocab_dic.items() if _[1] >= freq_min], key=lambda x: x[1], reverse=True)[
                     :max_size]
        vocab_dic = {
   word_count[0]: idx for idx, word_count in enumerate(vocab_list)}
        vocab_dic.update({
   UNK: len(vocab_dic), PAD: len(vocab_dic) + 1})
    return vocab_dic


def load_data(path, padding_size=32):
    contents = []
    vocab = build_vocab(path, max_size=10000, freq_min=1)
    with open(path, "r", encoding="utf-8") as f:
        for sentences in tqdm(f):
            sentence = sentences.strip()
            if not sentence:
                continue
            text, label = sentence.split("\t")
            word_line = []
            token = tokenizer(text)
            seq_len = len(token)
            if padding_size:
                if len(token) < padding_size:
                    token.extend([PAD] * (padding_size - len(token)))
                
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值