3.GitHub pytorch sentiment analysis(Fast版)

文章目录

FastTest model

这篇文章会采用"FastText"模型,跟之前的LSTM的84%左右的精确度相比差不多,但速度快上一倍,只需要训练LSTM一般的模型参数。

1.准备数据

FastText 模型中有个重要概念,是计算输入句子的n-grams,并将其附在句子的后面。这里我们使用bi-grams,就是一个句子里连续的一对词

例如句子是 “how are you ?”, bi-gram:“how are”, “are you” and “you ?”.

创建一个generate_bigrams函数,接收的是一个已经tokenized的句子,计算bi-grams然后将其放到tokenized list的最后。

def generate_bigrams(x):
    n_grams = set(zip(*[x[i:] for i in range(2)]))
    for n_gram in n_grams:
        x.append(' '.join(n_gram))
    return x

举例:

generate_bigrams(['This', 'film', 'is', 'terrible'])

[‘This’, ‘film’, ‘is’, ‘terrible’, ‘This film’, ‘film is’, ‘is terrible’]

TorchText Fields对象有一个preprocessing参数。如果将一个函数传进这个参数,那么一个句子被tokenized后,且在被数字化成索引向量之前,会被应用上传进去的那个函数
因为我们不是用的RNN,不需要对句子进行pad操作,因此不需要设置include_lengths = True.

import torch
from torchtext import data
from torchtext import datasets

SEED = 1234

torch.manual_seed(SEED)
torch.backends.cudnn.deterministic = True

TEXT = data.Field(tokenize = 'spacy', preprocessing = generate_bigrams) # 预处理步骤
LABEL = data.LabelField(dtype = torch.float)

加载数据

import random

train_data, test_data = datasets.IMDB.splits(TEXT, LABEL)

train_data, valid_data = train_data.split(random_state = random.seed(SEED))

构建单词表和预训练的词向量

MAX_VOCAB_SIZE = 25_000

TEXT.build_vocab(train_data, 
                 max_size = MAX_VOCAB_SIZE, 
                 vectors = "glove.6B.100d", 
                 unk_init = torch.Tensor.normal_)

LABEL.build_vocab(train_data)

构建迭代器

BATCH_SIZE = 64

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

train_iterator, valid_iterator, test_iterator = data.BucketIterator.splits(
    (train_data, valid_data, test_data), 
    batch_size = BATCH_SIZE, 
    device = device)

构建模型

这个模型有较少的训练参数,因为它只有两层,嵌入层和线性连接层 embedding layer and the linear layer.

首先模型先用Embedding layer(蓝色的那层)为每个词计算word embedding,然后计算所有词的平均word embedding(粉红色),将结果输进线性连接层(白色)。
3.GitHub pytorch sentiment analysis(Fast版)
使用的是avg_pool2d来做平均,

import torch.nn as nn
import torch.nn.functional as F

class FastText(nn.Module):
    def __init__(self, vocab_size, embedding_dim, output_dim, pad_idx):
        
        super().__init__()
        
        self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=pad_idx)
        
        self.fc = nn.Linear(embedding_dim, output_dim)
        
    def forward(self, text):
        
        #text = [sent len, batch size]
        
        embedded = self.embedding(text)
                
        #embedded = [sent len, batch size, emb dim]
        
        embedded = embedded.permute(1, 0, 2)
        
        #embedded = [batch size, sent len, emb dim]
        
        pooled = F.avg_pool2d(embedded, (embedded.shape[1], 1)).squeeze(1)  # 池化层
        
        #pooled = [batch size, embedding_dim]
                
        return self.fc(pooled)

构建FastText实例

INPUT_DIM = len(TEXT.vocab)
EMBEDDING_DIM = 100
OUTPUT_DIM = 1
PAD_IDX = TEXT.vocab.stoi[TEXT.pad_token]

model = FastText(INPUT_DIM, EMBEDDING_DIM, OUTPUT_DIM, PAD_IDX)

查看有多少模型参数


def count_parameters(model):
    return sum(p.numel() for p in model.parameters() if p.requires_grad)

print(f'The model has {count_parameters(model):,} trainable parameters')

将预训练词向量传进模型中的embedding layer层

pretrained_embeddings = TEXT.vocab.vectors

model.embedding.weight.data.copy_(pretrained_embeddings)

将unknown 和 pad token 的词向量初始化为0

UNK_IDX = TEXT.vocab.stoi[TEXT.unk_token]

model.embedding.weight.data[UNK_IDX] = torch.zeros(EMBEDDING_DIM)
model.embedding.weight.data[PAD_IDX] = torch.zeros(EMBEDDING_DIM)

设置优化器

import torch.optim as optim

optimizer = optim.Adam(model.parameters())

定义损失函数

criterion = nn.BCEWithLogitsLoss()

model = model.to(device)
criterion = criterion.to(device)

定义求精确度的函数

def binary_accuracy(preds, y):
    """
    Returns accuracy per batch, i.e. if you get 8/10 right, this returns 0.8, NOT 8
    """

    #round predictions to the closest integer
    rounded_preds = torch.round(torch.sigmoid(preds))
    correct = (rounded_preds == y).float() #convert into float for division 
    acc = correct.sum() / len(correct)
    return acc

定义训练函数

因为我们不再使用dropout 所以我们不需要调用model.train()

def train(model, iterator, optimizer, criterion):
    
    epoch_loss = 0
    epoch_acc = 0
    
    model.train()
    
    for batch in iterator:      
        optimizer.zero_grad()
        predictions = model(batch.text).squeeze(1)
        loss = criterion(predictions, batch.label)
        acc = binary_accuracy(predictions, batch.label)
        loss.backward()
        optimizer.step()
        epoch_loss += loss.item()
        epoch_acc += acc.item()
        
    return epoch_loss / len(iterator), epoch_acc / len(iterator)

定义评估函数

尽管不需要dropout,还是调用model.eval()

def evaluate(model, iterator, criterion):    
    epoch_loss = 0
    epoch_acc = 0
    
    model.eval()
    
    with torch.no_grad():
    
        for batch in iterator:
            predictions = model(batch.text).squeeze(1)
            loss = criterion(predictions, batch.label)
            acc = binary_accuracy(predictions, batch.label)
            epoch_loss += loss.item()
            epoch_acc += acc.item()
        
    return epoch_loss / len(iterator), epoch_acc / len(iterator)

定义计算耗时的函数

import time

def epoch_time(start_time, end_time):
    elapsed_time = end_time - start_time
    elapsed_mins = int(elapsed_time / 60)
    elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
    return elapsed_mins, elapsed_secs

训练模型

N_EPOCHS = 5

best_valid_loss = float('inf')

for epoch in range(N_EPOCHS):

    start_time = time.time()
    
    train_loss, train_acc = train(model, train_iterator, optimizer, criterion)
    valid_loss, valid_acc = evaluate(model, valid_iterator, criterion)
    
    end_time = time.time()

    epoch_mins, epoch_secs = epoch_time(start_time, end_time)
    
    if valid_loss < best_valid_loss:
        best_valid_loss = valid_loss
        torch.save(model.state_dict(), 'tut3-model.pt')
    
    print(f'Epoch: {epoch+1:02} | Epoch Time: {epoch_mins}m {epoch_secs}s')
    print(f'\tTrain Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.2f}%')
    print(f'\t Val. Loss: {valid_loss:.3f} |  Val. Acc: {valid_acc*100:.2f}%')

Epoch: 01 | Epoch Time: 0m 6s
Train Loss: 0.688 | Train Acc: 57.23%
Val. Loss: 0.642 | Val. Acc: 71.23%
Epoch: 02 | Epoch Time: 0m 5s
Train Loss: 0.653 | Train Acc: 71.09%
Val. Loss: 0.521 | Val. Acc: 75.28%
Epoch: 03 | Epoch Time: 0m 5s
Train Loss: 0.582 | Train Acc: 78.88%
Val. Loss: 0.449 | Val. Acc: 79.64%
Epoch: 04 | Epoch Time: 0m 5s
Train Loss: 0.505 | Train Acc: 83.15%
Val. Loss: 0.426 | Val. Acc: 82.12%
Epoch: 05 | Epoch Time: 0m 5s
Train Loss: 0.439 | Train Acc: 85.99%
Val. Loss: 0.397 | Val. Acc: 85.02%

测试


model.load_state_dict(torch.load('tut3-model.pt'))

test_loss, test_acc = evaluate(model, test_iterator, criterion)

print(f'Test Loss: {test_loss:.3f} | Test Acc: {test_acc*100:.2f}%')

实际预测

要实际预测时,对输入的句子添加bi-grams

import spacy
nlp = spacy.load('en')

def predict_sentiment(model, sentence):
    model.eval()
    tokenized = generate_bigrams([tok.text for tok in nlp.tokenizer(sentence)])
    indexed = [TEXT.vocab.stoi[t] for t in tokenized]
    tensor = torch.LongTensor(indexed).to(device)
    tensor = tensor.unsqueeze(1)
    prediction = torch.sigmoid(model(tensor))
    return prediction.item()
predict_sentiment(model, "This film is terrible")
上一篇:深度学习(神经网络)[1]——单层感知器


下一篇:[转]用深度学习给黑白照片上色