class CharDataset(Dataset): def init(self, data, sequencelength, stride, vocabsize):…
- User
class CharDataset(Dataset): def init(self, data, sequence_length, stride, vocab_size): self.data = data self.sequence_length = sequence_length self.stride = stride self.vocab_size = vocab_size self.sequences = [] self.targets = []
code# Create overlapping sequences with stride for i in range(0, len(data) - sequence_length, stride): self.sequences.append(data[i:i + sequence_length]) self.targets.append(data[i + 1:i + sequence_length + 1]) def __len__(self): return len(self.sequences) def __getitem__(self, idx): sequence = torch.tensor(self.sequences[idx], dtype=torch.long) target = torch.tensor(self.targets[idx], dtype=torch.long) return sequence, target - Assistant
- User
class CharRNN(nn.Module): def init(self, input_size, hidden_size, output_size, embedding_dim=30): super(CharRNN, self).init() self.hidden_size = hidden_size self.embedding = torch.nn.Embedding(output_size, embedding_dim) self.W_e = nn.Parameter(torch.randn(hidden_size, embedding_dim) * 0.01) # Smaller std self.b_e = nn.Parameter(torch.zeros(hidden_size)) self.W_h = nn.Parameter(torch.randn(hidden_size, hidden_size) * 0.01) # Smaller std self.b_h = nn.Parameter(torch.zeros(hidden_size)) #TODO: set the fully connected layer self.fc = nn.Linear(hidden_size, output_size)
code - Assistant
- User
for epoch in range(num_epochs): total_loss, correct_predictions, total_predictions = 0, 0, 0
codehidden = model.init_hidden(batch_size) for batch_idx, (batch_inputs, batch_targets) in tqdm(enumerate(train_loader), total=total_batches, desc=f"Epoch {epoch+1}/{num_epochs}"): batch_inputs, batch_targets = batch_inputs.to(device), batch_targets.to(device) output, hidden = model(batch_inputs, hidden) hidden = hidden.detach() loss = criterion(output.view(-1, output_size), batch_targets.view(-1)) # Flatten the outputs and targets for CrossEntropyLoss optimizer.zero_grad() loss.backward() optimizer.step() with torch.no_grad(): # Calculate accuracy _, predicted_indices = torch.max(output, dim=2) # Predicted characters correct_predictions += (predicted_indices == batch_targets).sum().item() total_predictions += batch_targets.size(0) * batch_targets.size(1) # Total items in this batch total_loss += loss.item() avg_loss = total_loss / len(train_loader) accuracy = correct_predictions / total_predictions * 100 # Convert to percentage print(f"Epoch [{epoch+1}/{num_epochs}], Loss: {avg_loss:.4f}, Accuracy: {accuracy:.2f}%") - Assistant
- User
def sample_from_output(logits, temperature=1.0): """ Sample from the logits with temperature scaling. logits: Tensor of shape [batch_size, vocab_size] (raw scores, before softmax) temperature: a float controlling the randomness (higher = more random) """ # Apply temperature scaling to logits (increase randomness with higher values) scaled_logits = logits / temperature # Scale the logits by temperature # Apply softmax to convert logits to probabilities probabilities = F.softmax(scaled_logits, dim=1)
- Assistant