N6 word2vec文本分类-前言

时间:2024-07-12 13:47:47

上周学习了训练word2vec模型,这周进行相关实战

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("cuda" if torch.cuda.is_available() else "cpu")
print(device)

import pandas as pd
2. 加载数据
train_data = pd.read_csv('./train.csv', sep='\t', header=None)
print(train_data)
3. 数据预处理
def coustom_data_iter(texts, labels):
    for x, y in zip(texts, labels):
        yield x, y

x = train_data[0].values[:]
y = train_data[1].values[:]

from gensim.models.word2vec import Word2Vec
import numpy as np

w2v = Word2Vec(vector_size=100, min_count=3)
w2v.build_vocab(x)
w2v.train(x, total_examples=w2v.corpus_count, epochs=20)
  • 定义自定义数据迭代器coustom_data_iter
  • 提取文本和标签数据。
  • 使用Word2Vec训练词向量模型,设置词向量维度为100,最小词频为3。
def average_vec(text):
    vec = np.zeros(100).reshape((1, 100))
    for word in text:
        try:
            vec += w2v.wv[word].reshape((1, 100))
        except KeyError:
            continue
    return vec

x_vec = np.concatenate([average_vec(z) for z in x])
w2v.save('w2v_model.pkl')

train_iter = coustom_data_iter(x_vec, y)
print(len(x), len(x_vec))
label_name = list(set(train_data[1].values[:]))
print(label_name)

text_pipeline = lambda x: average_vec(x)
label_pipeline = lambda x: label_name.index(x)

print(text_pipeline("你在干嘛"))
print(label_pipeline("Travel-Query"))
  • 定义函数average_vec,将文本转换为词向量的平均值。
  • 将所有文本转换为词向量并保存Word2Vec模型。
  • 打印文本和向量的数量,以及所有标签的名称。
  • 定义文本和标签的预处理函数text_pipelinelabel_pipeline
4. 数据加载器
from torch.utils.data import DataLoader

def collate_batch(batch):
    label_list, text_list = [], []

    for (_text, _label) in batch:
        label_list.append(label_pipeline(_label))
        processed_text = torch.tensor(text_pipeline(_text), dtype=torch.float32)
        text_list.append(processed_text)

    label_list = torch.tensor(label_list, dtype=torch.int64)
    text_list = torch.cat(text_list)

    return text_list.to(device), label_list.to(device)

dataloader = DataLoader(train_iter, batch_size=8, shuffle=False, collate_fn=collate_batch)
  • 定义函数collate_batch,将批次中的文本和标签转换为张量。
  • 创建数据加载器dataloader
5. 定义模型
class TextClassificationModel(nn.Module):

    def __init__(self, num_class):
        super(TextClassificationModel, self).__init__()
        self.fc = nn.Linear(100, num_class)

    def forward(self, text):
        return self.fc(text)

num_class = len(label_name)
model = TextClassificationModel(num_class).to(device)
  • 定义文本分类模型TextClassificationModel,包含一个全连接层。
  • 初始化模型,设置输出类别数。
6. 训练和评估函数
import time

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

    for idx, (text, label) in enumerate(dataloader):
        predicted_label = model(text)

        optimizer.zero_grad()
        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()
        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, (text, label) in enumerate(dataloader):
            predicted_label = model(text)
            loss = criterion(predicted_label, label)
            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
  • 定义训练函数train和评估函数evaluate
7. 训练模型
from torch.utils.data.dataset import random_split
from torchtext.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 = coustom_data_iter(train_data[0].values[:], train_data[1].values[:])
train_dataset = to_map_style_dataset(train_iter)

split_train_, split_valid_ = random_split(train_dataset, [int(len(train_dataset) * 0.8), int(len(train_dataset) * 0.2)])

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)

for epoch in range(1, EPOCHS + 1):
    epoch_start_time = time.time()
    train(train_dataloader)
    val_acc, val_loss = evaluate(valid_dataloader)

    lr = optimizer.state_dict()['param_groups'][0]['lr']

    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} | lr {:4.6f}'.format(
        epoch, time.time() - epoch_start_time, val_acc, val_loss, lr))
    print('-' * 69)

test_acc, test_loss = evaluate(valid_dataloader)
print('模型准确率为:{:5.4f}'.format(test_acc))
  • 定义超参数并初始化损失函数、优化器和学习率调度器。
  • 创建数据集并进行训练集和验证集的划分。
  • 训练模型并在每个epoch后进行验证。
8. 预测函数
def predict(text, text_pipeline):
    with torch.no_grad():
        text = torch.tensor(text_pipeline(text), dtype=torch.float32)
        print(text.shape)
        output = model(text)
        return output.argmax(1).item()

ex_text_str = "还有双鸭山到淮阴的汽车票吗13号的"
model = model.to("cpu")
print("该文本的类别是:%s" % label_name[predict(ex_text_str, text_pipeline)])
  • 定义预测函数predict,将文本转换为张量并使用模型进行预测。
  • 使用示例文本进行预测并输出结果。

结果

在这里插入图片描述