Rețele neuronale recurente pentru clasificarea textului

Deep Learning pentru text cu PyTorch

Shubham Jain

Data Scientist

RNN-uri pentru text

  • Gestionează secvențe de lungimi variabile
  • Mențin o memorie internă pe termen scurt
  • CNN-urile identifică tipare în fragmente
  • RNN-urile rețin cuvintele anterioare pentru un sens mai profund
Deep Learning pentru text cu PyTorch

RNN-uri pentru clasificarea textului

Imagine sarasm

De ce?

  • RNN-urile citesc propozițiile ca oamenii, cuvânt cu cuvânt
  • Înțeleg contextul și ordinea

Exemplu: Detectarea sarcasticului într-un tweet

"I just love getting stuck in traffic."

  • Sarcastic
Deep Learning pentru text cu PyTorch

Recapitulare: Implementarea Dataset și 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 pentru text cu PyTorch

Implementarea 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)
  • Antrenați un model RNN pentru a clasifica tweet-ul ca pozitiv sau negativ
  • Rezultat: „Pozitiv"
Deep Learning pentru text cu PyTorch

Variantă RNN: LSTM

Imagine analiză sentiment

Tweet:

  "Loved the cinematography, 
  hated the dialogue. 
  The acting was exceptional,
  but the plot fell flat."
  • Long Short Term Memory (LSTM) poate surprinde complexități acolo unde RNN-urile pot eșua
Deep Learning pentru text cu PyTorch

LSTM

Arhitectura LSTM: poartă de intrare, poartă de uitare și poartă de ieșire

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 pentru text cu PyTorch

Variantă RNN: GRU

  • Subiect e-mail:

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

 

  • Gated Recurrent Unit (GRU) poate identifica rapid tipare spam fără a necesita contextul complet

E-mail spam

Deep Learning pentru text cu 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 pentru text cu PyTorch

Să exersăm!

Deep Learning pentru text cu PyTorch

Preparing Video For Download...