Inside CharRNN.init(), you’ll need to define the learned parameters of the RNN
Your task: Randomly initialize each parameter using nn.Parameter(...), and follow the structure discussed in lecture. Keep standard deviations small (e.g., * 0.01).
how should I get started on this task
Assistant
To implement the parameter initialization for the CharRNN model in PyTorch, you will be making use of the nn.Parameter class to define your learned parameters. Here is a general guide to get you started:
Understand the architecture: The RNN typically has input weights, recurrent weights, and biases. You'll need to define these parameters based on the input size, hidden size, and output size of your model.
Define the parameters:
input_size: This is the size of the input (e.g., size of the character set or vocabulary).
hidden_size: This is the dimensionality of the hidden state in the RNN.
output_size: This is typically the same as input_size for character prediction.
Parameter initialization:
Use torch.randn() to create random tensors initialized with a normal distribution, and scale them by multiplying with a small standard deviation (e.g., 0.01).
Wrap them in nn.Parameter() to ensure they are recognized as parameters of the model that need to be learned during training.
Here is an example implementation to guide you:
python
import torch
import torch.nn as nn
class CharRNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(CharRNN, self).__init__()
# Initialize parameters
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
# Weight matrices
self.W_xh = nn.Parameter(torch.randn(hidden_size, input_size) * 0.01) # Input to hidden
self.W_hh = nn.Parameter(torch.randn(hidden_size, hidden_size) * 0.01) # Hidden to hidden
self.b_h = nn.Parameter(torch.zeros(hidden_size)) # Hidden bias
self.W_hy = nn.Parameter(torch.randn(output_size, hidden_size) * 0.01) # Hidden to output
self.b_y = nn.Parameter(torch.zeros(output_size)) # Output bias
def forward(self, x, hidden):
# Define the forward pass
pass # This would contain the RNN forward logic
def init_hidden(self, batch_size):
# Initialize hidden state
return torch.zeros(batch_size, self.hidden_size)
Key steps in the code:
The constructor __init__() initializes all required parameters, with weight matrices initialized to small random values and biases initialized to zeros.
nn.Parameter() wraps the tensors, indicating that these should be considered as model parameters and will be updated during training.
Next Steps:
Implement the forward method to define how your RNN processes input over time.
Implement the methods for training, including loss calculation and backpropagation.
Make sure to replace any placeholder comments in the provided code with the actual implementation of the RNN logic as per your requirements and model structure.
User
for t in range(l):
# TODO: Implement forward pass for a single RNN timestamp
pass
can you show me some hints to implement this ?
Assistant
Certainly! To implement the forward pass of a single timestamp in an RNN, you'll typically need to follow these steps:
Prepare Inputs: The input for the current timestamp. This could be the one-hot encoded vector or the embedding of the character at that timestamp.
Calculate Current Hidden State: You will use the input at the current timestamp and the hidden state from the previous timestamp to compute the new hidden state. This is done using the formula:
This will give you the raw predictions for the output, which you can then pass through a softmax function if you're dealing with classification of characters.
Return Outputs and Hidden State: Finally, return the output and the hidden state.
Here's a snippet of how your forward method might look based on the given hints:
python
def forward(self, x, hidden):
# Assuming x is of shape (batch_size, input_size)
# Initialize empty output tensor (for example)
outputs = []
for t in range(x.size(1)): # Iterate over time steps
# Get the input at this timestamp; you may need to select the correct slice
input_t = x[:, t, :].view(-1, self.input_size) # Ensure it is the correct shape (batch_size, input_size)
# Calculate the new hidden state
hidden = torch.tanh(torch.mm(input_t, self.W_xh.t()) + torch.mm(hidden, self.W_hh.t()) + self.b_h)
# Calculate the output
output_t = torch.mm(hidden, self.W_hy.t()) + self.b_y
outputs.append(output_t)
# Stack outputs over time
outputs = torch.stack(outputs, dim=1) # Shape (batch_size, sequence_length, output_size)
return outputs, hidden
this is what I impented, is there anything can be proved?
Assistant
Your implementation looks quite promising, and you're on the right track! However, there are a few improvements and additional implementations you may want to consider to ensure correctness and completeness. Let's take a look at each part:
Embedding Extraction: Ensure that x_embed is properly defined before this loop and that it is the appropriate shape (i.e., you're using embeddings for the current timestep).
Calculating the New Hidden State: Your current implementation for updating the hidden state looks generally correct, but let’s ensure that h_t_minus_1 is initialized properly before the loop begins. It should start as the initial hidden state (which could be zeros).
Output Calculation: At the end of the loop, you’ll need to include a way to compute the logits for each timestep's output based on the final hidden state h_t. You’ll want logits for classification tasks (like character prediction).
Output List Initialization: Make sure to initialize the output list before the loop starts.
Final Hidden State Cloning: Correctly clone h_t_minus_1 by calling .clone()(), since clone is a method, not a property.
Logits Calculation: After you've gathered the outputs from each timestep, you need to compute logits for each h_t. This is typically done by applying the linear transformation with the weight matrix W_hy followed by adding the bias b_y.
Here is an improved version of your snippet that includes these considerations:
python
User
for epoch in range(num_epochs):
total_loss = 0
hidden = None
for batch_inputs, batch_targets in tqdm(train_loader, desc=f"Epoch {epoch+1}/{num_epochs}"):
batch_inputs, batch_targets = batch_inputs.to(device), batch_targets.to(device)
code
output, hidden = model(batch_inputs, hidden)
# Detach removes the hidden state from the computational graph.
# This is prevents backpropagating through the full history, and
# is important for stability in training RNNs
hidden = hidden.detach()
optimizer.zero_grad()
# Reshape output and targets
output = output.reshape(-1, output_size)
batch_targets = batch_targets.reshape(-1)
loss = criterion(output, batch_targets)
loss.backward()
optimizer.step()
total_loss += loss.item()
print(f"Epoch {epoch+1}, Loss: {total_loss/len(train_loader):.4f}")
this is my test loop, is there anything I can improve?
Assistant
Your training loop for the RNN looks well-structured, but there are a few modifications and best practices you can consider to further improve it. Here are some suggestions:
Hidden State Initialization:
It looks like the hidden state (hidden) is not being re-initialized for each batch. This can be fine if you're handling sequences without resetting the hidden state, but if you use the same hidden state across different batches, it can lead to unexpected behavior. A common practice is to initialize it to zeros at the beginning of each batch or each epoch.
If you want to apply a sequence length or multi-batch RNN, you might need special consideration for how you manage hidden states.
Gradient Clipping:
RNNs can suffer from exploding gradients. Consider adding gradient clipping before the optimizer step:
Replace max_norm with a suitable value (e.g., 5.0).
Batch Size:
If your train_loader is providing different batch sizes, remember to check that your input handling in the model accommodates that correctly.
Device Management:
Ensure that all parameters, including the model weights and other tensors, are consistently on the same device (CPU/GPU). Check your model definition, loss function, and optimizer setup to ensure they are on the correct device.
Loss Averaging:
You could average the loss by the number of batches at the end of the epoch as you do, but also consider printing it conditionally for every few batches to monitor training progress.
Progress Monitoring:
Consider saving model checkpoints after specific epochs or if the loss improves significantly to not lose progress in case of a long training session.
You could also add a validation phase to evaluate your model's performance on a validation set after each epoch.
Here's a revised version of your training loop with these improvements incorporated:
python
User
am i make this part correct?
To debug your model you should start with a simple sequence an RNN should predict this perfectly
sequence = "abcdefghijklmnopqrstuvwxyz" * 100
sequence = read_file("warandpeace.txt") # Uncomment to read from file
vocab = sorted(set(sequence))
char_to_idx = {char: idx for idx, char in enumerate(vocab)}
idx_to_char = {idx: char for idx, char in enumerate(vocab)}
data = [char_to_idx[char] for char in sequence]
Understand and adjust the hyperparameters once the code is running
sequence_length = 30 # Length of each input sequence
stride = 2 # Stride for creating sequences
embedding_dim = 32 # Dimension of character embeddings
hidden_size = 128 # Number of features in the hidden state of the RNN
learning_rate = 0.1 # Learning rate for the optimizer
num_epochs = 10 # Number of epochs to train
batch_size = 64 # Batch size for training
vocab_size = len(vocab)
input_size = len(vocab)
output_size = len(vocab)
Assistant
Your code snippet for preparing a simple sequence in order to debug your RNN model looks good, but there are a few key aspects to consider to ensure it's fully functional and optimal. I'll walk through your code and highlight any necessary adjustments or improvements:
Sequence Generation:
You are generating a sequence composed of the lowercase alphabet repeated 100 times, which should work for testing basic predictions of an RNN model as characters are predictable in this case.
If you decide to use a different text source, like "warandpeace.txt", make sure that the file is properly read and processed before use. You should include code to handle reading from a file (such as encoding and stripping unwanted characters) if needed.
Vocabulary Creation:
Your vocabulary setup is correct. Using sorted(set(sequence)) ensures you get a sorted list of unique characters, which is good practice for consistency in mapping.
Character Index Mapping:
Creating char_to_idx and idx_to_char mappings is also correctly implemented. Be aware that both mappings should be reversible, which you've handled properly.
Data Preparation:
You convert characters in sequence to their corresponding indices, which is essential for feeding data into the RNN.
Hyperparameters:
The hyperparameters appear reasonable for a simple character-level RNN. Here are some observations:
Sequence Length: A sequence_length of 30 is a good choice. This means you'll be feeding 30 characters at a time into the model, and it's a manageable size.
Stride: Using a stride of 2 means that you’ll be overlapping your sequences significantly, which is useful in character-level prediction tasks.
Embedding Dimension: An embedding dimension of 32 should be sufficient for a model tasked with character predictions.
Hidden Size: 128 features in the hidden state is a common choice and should provide sufficient capacity.
Learning Rate: 0.1 is relatively high for most use cases; you might want to start lower (e.g., 0.01 or 0.001) and adjust based on training stability.
Num Epochs: 10 epochs will give your model sufficient time to learn the simple patterns in the character sequences.
User
Training loop
for epoch in range(num_epochs):
total_loss = 0
hidden = model.init_hidden(batch_size) # Re-initialize hidden state for each epoch
hidden = hidden.to(device) # Ensure hidden state is on the correct device
code
for batch_inputs, batch_targets in tqdm(train_loader, 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)
# Detach removes the hidden state from the computational graph.
# This is prevents backpropagating through the full history, and
# is important for stability in training RNNs
hidden = hidden.detach()
optimizer.zero_grad()
# Reshape output and targets
output = output.reshape(-1, output_size)
batch_targets = batch_targets.reshape(-1)
loss = criterion(output, batch_targets)
loss.backward()
optimizer.step()
total_loss += loss.item()
print(f"Epoch {epoch+1}, Loss: {total_loss/len(train_loader):.4f}")
Test the model
TODO: Implement a test loop to evaluate the model on the test set
can you help me create the test loop
Assistant
Sure! To create a test loop for evaluating your RNN model, you want to follow a similar structure to your training loop but with a few key differences. During testing, you typically do not perform backpropagation or update the model weights, and you also want to disable gradient computation to save memory and improve speed.
Here’s how you can implement a basic testing loop:
Set the Model to Evaluation Mode: This is important because layers like dropout and batch normalization behave differently during evaluation than during training. You enable this by calling model.eval().
Disable Gradient Calculation: Use the torch.no_grad() context manager to turn off gradients, which saves memory and increases speed during evaluation.
Initialize Variables: You may want to initialize some variables to collect losses or predictions during the evaluation.
Loop Through Test Data: Just like in training, you’ll iterate over your test data loader, but without the backpropagation steps.
Calculate Loss: You'll still want to compute the loss to understand how well your model is performing.
Here's a sample implementation of the test loop:
python
# Test Loop
model.eval() # Set the model to evaluation mode
total_test_loss = 0
correct_predictions = 0
num_samples = 0
# Iterate over the test data
with torch.no_grad(): # No gradients needed for testing
for batch_inputs, batch_targets in tqdm(test_loader, desc="Testing"):
batch_inputs, batch_targets = batch_inputs.to(device), batch_targets.to(device)
# Forward pass
output, hidden = model(batch_inputs, hidden)
# Reshape output and targets for loss calculation
output = output.reshape(-1, output_size)
batch_targets = batch_targets.reshape(-1)
# Calculate loss
loss = criterion(output, batch_targets)
total_test_loss += loss.item()
# Calculate predictions
predicted_indices = torch.argmax(output, dim=1)
correct_predictions += (predicted_indices == batch_targets).sum().item() # Count correct predictions
num_samples += batch_targets.size(0)
# Average loss
average_test_loss = total_test_loss / len(test_loader)
accuracy = correct_predictions / num_samples * 100 # Convert to percentage
print(f"Test Loss: {average_test_loss:.4f}, Test Accuracy: {accuracy:.2f}%")
User
this is what I have. am i missing something?
Understand and adjust the hyperparameters once the code is running
sequence_length = 30 # Length of each input sequence
stride = 2 # Stride for creating sequences
embedding_dim = 32 # Dimension of character embeddings
hidden_size = 128 # Number of features in the hidden state of the RNN
learning_rate = 0.1 # Learning rate for the optimizer
num_epochs = 10 # Number of epochs to train
batch_size = 64 # Batch size for training
vocab_size = len(vocab)
input_size = len(vocab)
output_size = len(vocab)
data_tensor = torch.tensor(data, dtype=torch.long)
train_size = int(len(data_tensor) * 0.9)
#Split the data into 90:10 ratio with PyTorch indexing
train_data = data_tensor[:train_size]
test_data = data_tensor[train_size:]
for epoch in range(num_epochs):
total_loss = 0
hidden = model.init_hidden(batch_size) # Re-initialize hidden state for each epoch
hidden = hidden.to(device) # Ensure hidden state is on the correct device
code
for batch_inputs, batch_targets in tqdm(train_loader, 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)
# Detach removes the hidden state from the computational graph.
# This is prevents backpropagating through the full history, and
# is important for stability in training RNNs
hidden = hidden.detach()
optimizer.zero_grad()
# Reshape output and targets
output = output.reshape(-1, output_size)
batch_targets = batch_targets.reshape(-1)
loss = criterion(output, batch_targets)
loss.backward()
optimizer.step()
total_loss += loss.item()
print(f"Epoch {epoch+1}, Loss: {total_loss/len(train_loader):.4f}")
Assistant
Your code for training and testing the RNN model looks mostly solid, but there are a few areas you could improve or confirm to ensure that everything works smoothly. Here’s a breakdown of what you have and any potential issues or enhancements to consider:
1. Dataset Class for CharDataset
Ensure that you have a proper implementation for the CharDataset class. It should handle extracting sequences from your data tensor and returning sequences and targets. Make sure it follows PyTorch's Dataset interface, so it will work seamlessly with the DataLoader. Here’s a quick example if you need one:
python
class CharDataset(torch.utils.data.Dataset):
def __init__(self, data, seq_length, stride, output_size):
self.data = data
self.seq_length = seq_length
self.stride = stride
self.output_size = output_size
def __len__(self):
return (len(self.data) - self.seq_length) // self.stride
def __getitem__(self, index):
start = index * self.stride
end = start + self.seq_length
sequence = self.data[start:end]
target = self.data[end] # Next character is the target
return sequence, target
2. Hidden State Initialization
In your test loop, you reset the hidden state to None. Depending on your RNN's design, you may want to initialize it to zeros instead. If your model's init_hidden method can create a fresh hidden state, consider calling that in the testing loop.
Example initialization:
python
hidden = model.init_hidden(batch_size).to(device)
However, since you're usually processing batches in testing, ensure that the hidden state is correctly shaped.
3. Train-Test Split Approach
You implemented the train-test split correctly with slicing, but ensure that you include sufficient checks to handle cases when the dataset is too small. Given the 90-10 split, your training set must have a meaningful amount of data.
4. Hyperparameters and Learning Rate
As mentioned previously, a learning rate of 0.1 might be too high. You might want to start with something smaller, like or , to see how the model performs initially. Adjusting the learning rate based on real data can lead to better convergence.
Dataset releases
Not yet included in a published release.
Key Points in this Implementation:
Input Shape: Ensure that input_t is in the correct shape for matrix multiplication. It is vital that the dimensions match (batch_size × input_size for inputs).
Activation Function: Here, we used torch.tanh, but depending on your requirements, you might choose another activation function.
Output Collection: You accumulate outputs for each timestep and stack them at the end to get a tensor of shape (batch_size, sequence_length, output_size).
Additional Considerations:
Batch Size: Make sure that your forward function handles batches of data correctly. Often RNNs are implemented in a way that processes batches of sequences.
Hidden State Initialization: Make sure to initialize the hidden state (hidden) properly when processing the first input in a sequence.
With these hints, you should be able to implement the forward pass of your RNN for a single timestamp effectively!
# Assuming some initialization like:
# h_t_minus_1 = self.init_hidden(batch_size) # If you have an initializer
# output = [] # Initialize output list
# l = sequence length
# batch_size = batch size from x_embed
for t in range(l):
x_t = x_embed[t] # Get the embedding for timestep t
h_t = torch.tanh(
x_t @ self.W_xh.T + h_t_minus_1 @ self.W_hh.T + self.b_h
)
output.append(h_t) # Capture current hidden state
h_t_minus_1 = h_t # Update hidden state for next timestep
# Stack outputs into a tensor; shape will be [l, b, h]
output = torch.stack(output)
# Transpose output to [b, l, h] if needed, for batch processing later
output = output.transpose(0, 1)
# Clone the final hidden state
final_hidden = h_t_minus_1.clone() # Ensure to call clone as a method
# Calculate logits (output predictions).
# Assuming self.W_hy is the hidden to output weight matrix and self.b_y is the bias for output
logits = output @ self.W_hy.T + self.b_y # Shape [b, l, vocab_size]
# If you are doing character prediction, logits should be of size [batch_size, sequence_length, vocab_size]
Key Enhancements and Fixes:
Initialization of h_t_minus_1: Ensure you initialize the hidden state outside the loop.
Logits Calculation: Make sure to calculate logits from the output and pass them through softmax if they are meant for classification tasks.
Correct Cloning: Use clone() correctly to create a copy of the hidden state if you want to keep it unchanged.
Additional Notes:
If you're using GPU, make sure all your parameters and inputs are moved to the same device (cuda or cpu) before computations to avoid device mismatch errors.
Consider adding dropout or other regularization techniques if you're planning to train this RNN to help prevent overfitting.
These adjustments should help make your implementation more robust and ready for training or further processing!
for epoch in range(num_epochs):
total_loss = 0
hidden = model.init_hidden(batch_size) # Re-initialize hidden state for each epoch
hidden = hidden.to(device) # Ensure hidden state is on the correct device
for batch_inputs, batch_targets in tqdm(train_loader, desc=f"Epoch {epoch+1}/{num_epochs}"):
batch_inputs, batch_targets = batch_inputs.to(device), batch_targets.to(device)
# Forward pass
output, hidden = model(batch_inputs, hidden)
# Detach removes the hidden state from the computational graph
hidden = hidden.detach()
optimizer.zero_grad()
# Reshape output and targets
output = output.reshape(-1, output_size)
batch_targets = batch_targets.reshape(-1)
# Calculate loss
loss = criterion(output, batch_targets)
# Backward pass
loss.backward()
# Gradient clipping
nn.utils.clip_grad_norm_(model.parameters(), max_norm=5.0)
optimizer.step()
total_loss += loss.item()
print(f"Epoch {epoch+1}, Loss: {total_loss/len(train_loader):.4f}")
# Optional: You can add validation and model checkpointing here
Additional Considerations:
Validation Phase: Implement a validation loop after each training epoch to monitor your model performance on unseen data.
Learning Rate Scheduling: Consider using a learning rate scheduler to adjust the learning rate based on the number of epochs or validation loss.
Logging: Utilize logging libraries (like TensorBoard) if your project allows, to visualize the training process more effectively, track metrics over time, and easily compare runs.
With these improvements, you should have a more robust training loop that can handle issues commonly encountered in training RNNs.
Batch Size: 64 is a common choice and should work well unless you face memory issues.
Here’s how you might want to set up your data preparation to convert it into a format suitable for training your RNN:
python
import numpy as np
# Prepare training sequences
def create_sequences(data, seq_length, stride):
inputs = []
targets = []
for i in range(0, len(data) - seq_length, stride):
inputs.append(data[i:i + seq_length])
targets.append(data[i + seq_length]) # Predict the next character
return np.array(inputs), np.array(targets)
# Create the training data
inputs, targets = create_sequences(data, sequence_length, stride)
# Convert to torch tensors
import torch
inputs = torch.tensor(inputs, dtype=torch.long) # Shape: [num_sequences, seq_length]
targets = torch.tensor(targets, dtype=torch.long) # Shape: [num_sequences]
# Define dataset and dataloader if needed
from torch.utils.data import DataLoader, TensorDataset
train_dataset = TensorDataset(inputs, targets)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
Summary of Improvements:
Data Preparation: The function create_sequences helps divide the input data into sequences and corresponding targets for training, ensuring that your RNN learns to predict the next character from a given sequence.
Batch Loader: Utilizing DataLoader makes the training process easier and more efficient.
With these adjustments, your setup will be ready for training your RNN to learn from character sequences effectively. If you run into issues during training, consider monitoring your learning progress and modifying hyperparameters as necessary.
Key Parts Explained:
Evaluation Mode: Using model.eval() sets the model in evaluation mode, affecting layers like dropout and batch normalization if you were using them.
No Gradient Calculation: The with torch.no_grad(): context manager allows you to run this block without tracking gradients, which is the right approach in testing/evaluation.
Reshaping Output: Reshape your output and targets similarly to training so that they can be compared properly when calculating the loss.
Correct Predictions Calculation: The way you compute accuracy (or any other metric) is important. Here, we count how many predicted indices match the target indices, which gives you the number of correct predictions.
Printing Results: Finally, it computes and prints the average test loss and the accuracy of the model.
Additional Enhancements:
Saving Model Checkpoints: You might consider saving the model checkpoints based on the best validation accuracy during training.
Learning Rate Adjustment: If your performance does not improve, you may consider implementing learning rate scheduling based on test/validation loss.
This test loop will give you insights into how well your trained model generalizes to unseen data, which is crucial for evaluating performance in machine learning tasks.
Test the model
TODO: Implement a test loop to evaluate the model on the test set
with torch.no_grad(): # No gradients needed for testing
hidden = None # Reset hidden for evaluation
for batch_inputs, batch_targets in tqdm(test_loader, desc="Testing"):
batch_inputs, batch_targets = batch_inputs.to(device), batch_targets.to(device)
print(f"Test Loss: {average_test_loss:.4f}, Test Accuracy: {accuracy:.2f}%")
0.01
0.001
5. Performance Monitoring
While you're printing the loss after each epoch, consider adding validation loss computation after each epoch to see how well the model generalizes. This involves creating a validation set and calculating loss after training on the training set.
6. Validation Dataset (Optional)
It’s often useful to have a separate validation dataset to monitor performance during training. If you want to track overfitting, separating some data for validation can be useful.
Full Example Structure
Here’s how you could structure your complete testing code, incorporating all the enhancements and checks mentioned:
python
# Test Loop
model.eval() # Set the model to evaluation mode
total_test_loss = 0
correct_predictions = 0
num_samples = 0
# Iterate over the test data
with torch.no_grad(): # No gradients needed for testing
hidden = model.init_hidden(batch_size).to(device) # Initialize hidden state for batches
for batch_inputs, batch_targets in tqdm(test_loader, desc="Testing"):
batch_inputs, batch_targets = batch_inputs.to(device), batch_targets.to(device)
# Forward pass
output, hidden = model(batch_inputs, hidden)
# Reshape output and targets for loss calculation
output = output.reshape(-1, output_size)
batch_targets = batch_targets.reshape(-1)
# Calculate loss
loss = criterion(output, batch_targets)
total_test_loss += loss.item()
# Calculate predictions
predicted_indices = torch.argmax(output, dim=1)
correct_predictions += (predicted_indices == batch_targets).sum().item() # Count correct predictions
num_samples += batch_targets.size(0)
# Average loss
average_test_loss = total_test_loss / len(test_loader)
accuracy = correct_predictions / num_samples * 100 # Convert to percentage
print(f"Test Loss: {average_test_loss:.4f}, Test Accuracy: {accuracy:.2f}%")
Testing Your Code
Once you've integrated the above suggestions and ensured that all components (like the dataset class) are correctly implemented, run your model and monitor both the training and testing outputs. Continually fine-tuning hyperparameters and observing patterns in loss and accuracy will lead to a better-performing model. Good luck with your training!