<jupyter_start><jupyter_text>Define Field to preprocess raw data<jupyter_code>import torch
from torchtext.datasets import IMDB
train_iter = IMDB(split='train')
next(train_iter)
from torchtext.data.utils import get_tokenizer
from collections import Counter
from torchtext.vocab import Vocab

tokenizer = get_tokenizer('basic_english')
counter = Counter()
for (label, line) in train_iter:
    counter.update(tokenizer(line))
vocab = Vocab(counter, min_freq=1, 
              max_size = 25000, 
              vectors = "glove.6B.100d", 
              unk_init = torch.Tensor.normal_)
vocab.freqs.most_common(20)
text_pipeline = lambda x: [vocab[token] for token in tokenizer(x)]
label_pipeline = lambda x: 0 if x=='neg' else 1
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 = IMDB(split='train')
dataloader = DataLoader(train_iter, batch_size=8, shuffle=False, collate_fn=collate_batch)
for idx, (label, text, offsets) in enumerate(dataloader):
    print(text.shape)
    print(label)<jupyter_output>torch.Size([1805])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([2298])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([2387])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([1764])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([1900])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([2530])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([2432])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([1702])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([2240])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([1800])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([3041])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([2914])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([2056])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([1860])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([1950])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([1639])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([2486])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([2149])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([1956])
tensor([0, 0, 0, 0, 0, 0, 0, 0])
torch.Size([[...]<jupyter_text>Define model<jupyter_code>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=True)
        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)
num_class = 2
vocab_size = len(vocab)
emsize = 64
model = TextClassificationModel(vocab_size, emsize, num_class).to(device)<jupyter_output><empty_output><jupyter_text>Define dataloader<jupyter_code>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()
        predited_label = model(text, offsets)
        loss = criterion(predited_label, label)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 0.1)
        optimizer.step()
        total_acc += (predited_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):
            predited_label = model(text, offsets)
            loss = criterion(predited_label, label)
            total_acc += (predited_label.argmax(1) == label).sum().item()
            total_count += label.size(0)
    return total_acc/total_count
from torch.utils.data.dataset import random_split
# 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 = IMDB()
train_dataset = list(train_iter)
test_dataset = list(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)<jupyter_output>torch.Size([64, 64])<jupyter_text>Evaluation<jupyter_code>print('Checking the results of test dataset.')
accu_test = evaluate(test_dataloader)
print('test accuracy {:8.3f}'.format(accu_test))<jupyter_output>Checking the results of test dataset.
test accuracy    0.853<jupyter_text>Predict on a single instance<jupyter_code>ag_news_label = {0: "negative",
                 1: "positive"}

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


model = model.to("cpu")
ex_text_str = "It was a wonderful educational short journey into the deep blue searching for the king,\
the great white shark , me and my family were fully enjoyed watching this beautiful movie and we were \
fascinated by the magnificent clear blue color under water and the great camera work , unfortunately it\
was too short (only 40 minutes), like we say in Arabic ( happy times passes fast) , but it's really worth our time."

print("This is a %s review" %ag_news_label[predict(ex_text_str, text_pipeline)])<jupyter_output>tensor([[-2.7194,  2.3986]])
This is a positive review
{'fraction_non_alphanumeric': 0.1372856955895825, 'fraction_numerical': 0.04279544562230075, 'mean_word_length': 3.505896226415094, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '40879', 'license': 'MIT', 'n_tokens_mistral': 2943, 'n_tokens_neox': 2690, 'n_words': 654, 'path': 'imdb.ipynb', 'repo_name': 'YaNgZhAnG-V5/nlp_playground', 'size': '7641'}