Reti neurali ricorrenti per la classificazione del testo

Deep Learning per il testo con PyTorch

Shubham Jain

Data Scientist

RNN per il testo

  • Gestiscono sequenze di lunghezza variabile
  • Mantengono una memoria interna a breve termine
  • Le CNN rilevano pattern a blocchi
  • Le RNN ricordano parole passate per dare più senso
Deep Learning per il testo con PyTorch

RNN per la classificazione del testo

Immagine sarcasmo

Perché?

  • Le RNN leggono le frasi come noi, una parola alla volta
  • Capiscono contesto e ordine

Esempio: rilevare il sarcasmo in un tweet

"I just love getting stuck in traffic."

  • Sarcastico
Deep Learning per il testo con PyTorch

Ripasso: implementare Dataset e 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 per il testo con PyTorch

Implementazione 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)
  • Allena una RNN a classificare il tweet come positivo o negativo
  • Output: "Positive"
Deep Learning per il testo con PyTorch

Variazione RNN: LSTM

Immagine analisi del sentiment

Tweet:

  "Loved the cinematography, 
  hated the dialogue. 
  The acting was exceptional,
  but the plot fell flat."
  • Le Long Short Term Memory (LSTM) catturano complessità dove le RNN possono faticare
Deep Learning per il testo con PyTorch

LSTM

Architettura LSTM: input gate, forget gate e output gate

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 per il testo con PyTorch

Variazione RNN: GRU

  • Oggetto dell'email:

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

 

  • Le Gated Recurrent Unit (GRU) riconoscono velocemente pattern di spam senza bisogno di tutto il contesto

Email spam

Deep Learning per il testo con 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 per il testo con PyTorch

Esercitiamoci!

Deep Learning per il testo con PyTorch

Preparing Video For Download...