Función torch.nn.GRU de PyTorch
Manual de referencia de PyTorch torch.nn
torch.nn.GRUEs el módulo de unidad recurrente con compuertas (GRU) en PyTorch.
GRU es una versión simplificada de LSTM, con menos parámetros, cálculo más rápido y resultados similares.
Definición de la función
torch.nn.GRU(input_size, hidden_size, num_layers=1, bias=True, batch_first=True, dropout=0, bidirectional=False)
Ejemplos de uso
Ejemplo 1: Uso básico
Ejemplo
import torch
import torch.nn as nn
# GRU: entrada de 256, oculto de 256, 2 capas
gru = nn.GRU(input_size=256, hidden_size=256, num_layers=2, batch_first=True)
# Entrada: batch=4, secuencia=10, features=256
x = torch.randn(4, 10, 256)
output, hidden = gru(x)
print(Forma de entrada:, x.shape)
print(Forma de salida:, output.shape)
print(Forma del estado oculto:, hidden.shape)
import torch.nn as nn
# GRU: entrada de 256, oculto de 256, 2 capas
gru = nn.GRU(input_size=256, hidden_size=256, num_layers=2, batch_first=True)
# Entrada: batch=4, secuencia=10, features=256
x = torch.randn(4, 10, 256)
output, hidden = gru(x)
print(Forma de entrada:, x.shape)
print(Forma de salida:, output.shape)
print(Forma del estado oculto:, hidden.shape)
Ejemplo 2: Comparación con LSTM
Ejemplo
import torch
import torch.nn as nn
import time
# LSTM y GRU con la misma configuración
lstm = nn.LSTM(256, 256, 1, batch_first=True)
gru = nn.GRU(256, 256, 1, batch_first=True)
x = torch.randn(32, 100, 256)
# Comparación de rendimiento
for model, name in [(lstm, "LSTM"), (gru, "GRU")]:
start = time.time()
for _ in range(100):
_ = model(x)
print(f"{name} tiempo: {time.time()-start:.3f}s")
import torch.nn as nn
import time
# LSTM y GRU con la misma configuración
lstm = nn.LSTM(256, 256, 1, batch_first=True)
gru = nn.GRU(256, 256, 1, batch_first=True)
x = torch.randn(32, 100, 256)
# Comparación de rendimiento
for model, name in [(lstm, "LSTM"), (gru, "GRU")]:
start = time.time()
for _ in range(100):
_ = model(x)
print(f"{name} tiempo: {time.time()-start:.3f}s")
Ejemplo 3: Tarea de clasificación
Ejemplo
import torch
import torch.nn as nn
class GRUClassifier(nn.Module):
def __init__(self, vocab_size, embed_dim, hidden_dim, num_classes):
super(GRUClassifier, self).__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.gru = nn.GRU(embed_dim, hidden_dim, batch_first=True, bidirectional=True)
self.fc = nn.Linear(hidden_dim * 2, num_classes)
def forward(self, x):
embedded = self.embedding(x)
_, hidden = self.gru(embedded)
# Concatenar el último estado oculto bidireccional
hidden = torch.cat([hidden[-2], hidden[-1]], dim=1)
return self.fc(hidden)
model = GRUClassifier(10000, 128, 128, 2)
x = torch.randint(0, 10000, (8, 50))
output = model(x)
print(Entrada:, x.shape, -> Salida:, output.shape)
import torch.nn as nn
class GRUClassifier(nn.Module):
def __init__(self, vocab_size, embed_dim, hidden_dim, num_classes):
super(GRUClassifier, self).__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.gru = nn.GRU(embed_dim, hidden_dim, batch_first=True, bidirectional=True)
self.fc = nn.Linear(hidden_dim * 2, num_classes)
def forward(self, x):
embedded = self.embedding(x)
_, hidden = self.gru(embedded)
# Concatenar el último estado oculto bidireccional
hidden = torch.cat([hidden[-2], hidden[-1]], dim=1)
return self.fc(hidden)
model = GRUClassifier(10000, 128, 128, 2)
x = torch.randint(0, 10000, (8, 50))
output = model(x)
print(Entrada:, x.shape, -> Salida:, output.shape)
LSTM vs GRU
| Aspecto | LSTM | GRU |
|---|---|---|
| Cantidad de parámetros | Más | Menos |
| Compuertas | 3 compuertas | 2 compuertas |
| Cálculo | Más lento | Más rápido |
Casos de uso
- Modelado de secuencias: texto, audio
- Prototipado rápido: cuando los recursos son limitados
- Traducción automática: en el lado del encoder
Otras extensiones