The code: class Attention(nn.Module):
def init(self, hidden_size):
super(Attention, self).init()
self.attn = nn.Linear(hidden_size, hidden_size) # Adjusted the input size
self.v = nn.Parameter(torch.rand(hidden_size))
def forward(self, hidden, encoder_outputs):
# Adjusted the linear layer input size
attn_scores = torch.tanh(self.attn(encoder_outputs))
attn_scores = attn_scores.transpose(1, 2) # Transpose to make dimensions compatible
attn_scores = attn_scores * self.v
attn_probs = F.softmax(attn_scores, dim=2) # Adjusted the dimension
context = torch.bmm(attn_probs, encoder_outputs) # Use batch matrix multiplication
return context, attn_probs
'''
Encoder RNN
'''
class EncoderRNN(nn.Module):
def init(self, input_size, batch_size, hidden_size, dropout_p=0.1):
super(EncoderRNN, self).init()
self.hidden_size = hidden_size
self.batch_size = batch_size
input size = alphabet (features in output)
self.gru = nn.GRU(input_size, hidden_size, batch_first=True)
self.dropout = nn.Dropout(dropout_p)
self.num_directions = 1
def forward(self, input):
# drop out to prevent overfitting
embedded = self.dropout(input.float())
# initialize hidden layer with small random values?
stdv = 1.0 / self.hidden_size # small standard deviation
hidden = torch.randn(self.gru.num_layers * self.num_directions, self.batch_size, self.hidden_size) * stdv
output, hidden = self.gru(embedded, hidden)
return output, hidden
'''
Decoder RNN
'''
class DecoderRNN(nn.Module):
def init(self, hidden_size, output_size, dropout_p=0.1, num_layers=1):
super(DecoderRNN, self).init()
self.hidden_size = hidden_size
self.output_size = output_size
self.num_layers = num_layers
self.gru = nn.GRU(output_size, hidden_size, num_layers=num_layers, batch_first=True)
self.out = nn.Linear(hidden_size * 2, output_size)
self.dropout = nn.Dropout(dropout_p)
def forward(self, encoder_outputs, encoder_hidden, target_tensor=None):
batch_size = encoder_outputs.size(0)
decoder_input = torch.zeros(batch_size, 1, self.output_size)
decoder_hidden = encoder_hidden
decoder_outputs = []
for i in range(MAX_LENGTH):
decoder_output, decoder_hidden = self.forward_step(decoder_input, decoder_hidden)
decoder_outputs.append(decoder_output)
# Teacher forcing or using the predictions for the next input
if target_tensor is not None:
decoder_input = target_tensor[:, i, :].unsqueeze(1)
else:
decoder_input = decoder_output
decoder_outputs = torch.cat(decoder_outputs, dim=1)
return decoder_outputs, decoder_hidden
def forward_step(self, input, hidden):
output, hidden = self.gru(input.float(), hidden)
hidden = hidden.view(self.num_layers, -1, self.hidden_size) # Reshape hidden state to split it into two parts
forward_hidden, backward_hidden = hidden[0], hidden[-1] # Split hidden state into forward and backward parts
output = self.out(torch.cat([forward_hidden, backward_hidden], dim=-1)) # Concatenate forward and backward parts and apply linear layer
return output, hidden
def _init_decoder_hidden(self, encoder_hidden):
# If the encoder is bidirectional, we need to concatenate the forward and backward hidden states
if encoder_hidden.size(0) == self.num_layers * 2: # Check if encoder_hidden is from a bidirectional encoder
forward_hidden = encoder_hidden[0::2]
backward_hidden = encoder_hidden[1::2]
hidden = torch.cat((forward_hidden[-1], backward_hidden[-1]), dim=1)
else:
hidden = encoder_hidden
return hidden
def initialize_input(self, pad_index, alphabet_size, batch_size):
pad_indices = torch.full((batch_size,), pad_index, dtype=torch.long)
decoder_input = F.one_hot(pad_indices, num_classes=alphabet_size).unsqueeze(1).float()
return decoder_input
'''
Training function
'''
def train_model(encoder, decoder, input_batch, target_batch, optimizer, criterion, tf_ratio=0.5, max_norm=10):
optimizer.zero_grad()
Forward pass through encoder
encoder_output, encoder_hidden = encoder(input_batch)
Initialize the decoder hidden state with the final encoder hidden state
decoder_hidden = encoder_hidden
Initialize decoder input with
decoder_input = decoder.initialize_input(pad_index=0, alphabet_size=target_batch.shape[2], batch_size=target_batch.shape[0])
Initialize loss
loss = 0
TF ratio
use_tf = random.random() < tf_ratio
Get the target tensor for decoder's forward method if teacher forcing is used
target_tensor = target_batch if use_tf else None
Forward pass through decoder
decoder_outputs, decoder_hidden = decoder(decoder_input, decoder_hidden, target_tensor)
Calculate loss
for di in range(target_batch.shape[1]):
decoder_output = decoder_outputs[:, di, :]
# Get the target for the current timestep
current_target = target_batch[:, di]
_, target_class_indices = current_target.max(dim=1)
# Accumulate loss
loss += criterion(decoder_output, target_class_indices)
Backpropagation
loss.backward()
Clip the gradient
torch.nn.utils.clip_grad_norm_(parameters=list(encoder.parameters()) + list(decoder.parameters()), max_norm=max_norm)
Update model parameters
optimizer.step()
Return the average loss
return loss.item() / target_batch.shape[1]
'''
Training loop
'''
def train_model_epochs(encoder, decoder, train_loader, optimizer, criterion, scheduler=None, epochs=10):
start_time = time.time()
epoch_times = []
losses = []
epoch_losses = []
for epoch in range(epochs):
# Set the guys to train mode
encoder.train()
decoder.train()
epoch_start_time = time.time()
running_loss = 0.0
for i, (input_batch, target_batch) in enumerate(train_loader):
loss = train_model(encoder, decoder, input_batch, target_batch, optimizer, criterion)
running_loss += loss
losses.append(loss)
if (i+1) % 100 == 0:
print(f'Batch {i+1}/{len(train_loader)}, Epoch {epoch + 1}/{epochs}, Loss: {loss}')
epoch_loss = running_loss / len(train_loader)
epoch_losses.append(epoch_loss) The error: IndexError: too many indices for tensor of dimension 2