Rekurentní neuronové sítě pro klasifikaci textu

Deep Learning for Text with PyTorch

Shubham Jain

Data Scientist

RNN pro text

  • Zpracovávají sekvence různých délek
  • Udržují krátkodobou paměť
  • CNN rozpoznávají vzory v blocích
  • RNN si pamatují předchozí slova pro lepší porozumění
Deep Learning for Text with PyTorch

RNN pro klasifikaci textu

Obrázek sarkasmu

Proč?

  • RNN čtou věty jako lidé – slovo po slovu
  • Chápou kontext a pořadí

Příklad: Detekce sarkasmu v tweetu

"I just love getting stuck in traffic."

  • Sarkastické
Deep Learning for Text with PyTorch

Rekapitulace: Implementace Dataset a DataLoader

# Import libraries
from torch.utils.data import Dataset, DataLoader

# Create a class class TextDataset(Dataset):
def __init__(self, text): self.text = text
def __len__(self): return len(self.text)
def __getitem__(self, idx): return self.text[idx]
Deep Learning for Text with PyTorch

Implementace RNN

sample_tweet = "This movie had a great plot and amazing acting."
# Preprocess the review and convert it to a tensor (not shown for brevity)
# ...
sentiment_prediction = model(sample_tweet_tensor)
  • Trénování modelu RNN pro klasifikaci tweetu jako pozitivní nebo negativní
  • Výstup: „Positive"
Deep Learning for Text with PyTorch

Varianta RNN: LSTM

Obrázek analýzy sentimentu

Tweet:

  "Loved the cinematography, 
  hated the dialogue. 
  The acting was exceptional,
  but the plot fell flat."
  • Long Short Term Memory (LSTM) zachytí složitosti, se kterými mají RNN potíže
Deep Learning for Text with PyTorch

LSTM

Architektura LSTM: vstupní brána, brána zapomínání a výstupní brána

class LSTMModel(nn.Module):

def __init__(self, input_size, hidden_size, output_size): super(LSTMModel, self).__init__() self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True) self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x): _, (hidden, _) = self.lstm(x) output = self.fc(hidden.squeeze(0)) return output
Deep Learning for Text with PyTorch

Varianta RNN: GRU

  • Předmět e-mailu:

       "Congratulations!
        You've won a free trip 
        to Hawaii!"
    

 

  • Gated Recurrent Unit (GRU) rychle rozpozná spamové vzory bez potřeby plného kontextu

Spamový e-mail

Deep Learning for Text with PyTorch

GRU

class GRUModel(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(GRUModel, self).__init__()
        self.gru = nn.GRU(input_size, hidden_size, batch_first=True)
        self.fc = nn.Linear(hidden_size, output_size)

def forward(self, x): _, hidden = self.gru(x) output = self.fc(hidden.squeeze(0)) return output
Deep Learning for Text with PyTorch

Pojďme si procvičit!

Deep Learning for Text with PyTorch

Preparing Video For Download...