Deep Learning para texto con PyTorch
Shubham Jain
Instructor
"
"- Codificador: Procesa los datos de entrada
sentences = ["Me encanta este producto", "Esto es terrible", "Podría ser mejor", "Esto es lo mejor"] labels = [1, 0, 0, 1]train_sentences = sentences[:3] train_labels = labels[:3] test_sentences = sentences[3:] test_labels = labels[3:]
"`python
class TransformerEncoder(nn.Module):
----CODE_GLUE---- ```python def __init__(self, embed_size, heads, num_layers, dropout): super(TransformerEncoder, self).__init__()self.encoder = nn.TransformerEncoder( nn.TransformerEncoderLayer(d_model=embed_size, nhead=heads), num_layers=num_layers)self.fc = nn.Linear(embed_size, 2)def forward(self, x):x = self.encoder(x)x = x.mean(dim=1)return self.fc(x)model = TransformerEncoder(embed_size=512, heads=8, num_layers=3, dropout=0.5)
----CODE_GLUE----
python
optimizer = optim.Adam(model.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss(){{10}}"
"python
for epoch in range(5):
----CODE_GLUE----
python for sentence, label in zip(train_sentences, train_labels): tokens = sentence.split()
"`python
def predict(sentence):
model.eval()
----CODE_GLUE---- ```python with torch.no_grad():tokens = sentence.split() data = torch.stack([token_embeddings.get(token, torch.rand((1, 512))) for token in tokens], dim=1)output = model(data)predicted = torch.argmax(output, dim=1)
----CODE_GLUE----
python
return \"Positive\" if predicted.item() == 1 else \"Negative\"{{6}}"
sample_sentence = "Este producto puede ser mejor"
print(f"'{sample_sentence}' es {predict(sample_sentence)}")
'Este producto puede ser mejor' es Negativo
Deep Learning para texto con PyTorch