![]() |
VOOZH | about |
PyTorch provides several components for building and training neural networks, and torch.nn.Parameter is one of the most important among them. It is a special tensor used to store trainable parameters in a model. When assigned as a module attribute, it is automatically registered and updated during training, making it useful for creating custom layers and neural network architectures.
requires_grad argument to control gradient computation. torch.nn.Parameter are treated as learnable model parameters and are updated during gradient-based training. torch.nn.Module, it is automatically registered as part of the module's parameters. torch.nn.Parameter to make it learnable during training. torch.nn.Module, it is automatically added to the model's parameter list. Let's consider a simple neural network that uses torch.nn.Parameter to create a trainable parameter and update it during training.
Importing the required PyTorch modules for neural network construction and optimization.
Creating a custom neural network class SimpleNet using nn.Module. Define a trainable parameter self.weight using torch.nn.Parameter.
Creating an instance of SimpleNet. Print the initial model parameters to verify that the weight has been initialized.
Define the loss function and optimizer for training. Here, we use the Mean Squared Error (MSE) loss and Stochastic Gradient Descent (SGD) optimizer.
Defining the input and target tensors. These tensors represent the data that the model will learn from during training.
Execute the training loop. This loop involves forwarding pass, loss calculation, backpropagation, and parameter updates. Monitor the training progress by printing the loss and current weight every 10 epochs.
After training, print the final learned parameters to see how well the model has learned to approximate the target from the input.
Output:
Initial Model Parameters: [Parameter containing:
tensor([0.5888], requires_grad=True)]
Epoch 0, Loss: 7.966062068939209, Weight: 0.7016862034797668
Epoch 10, Loss: 1.5031428337097168, Weight: 1.4360274076461792
Epoch 20, Loss: 0.28363296389579773, Weight: 1.7550169229507446
Epoch 30, Loss: 0.0535195991396904, Weight: 1.8935822248458862
Epoch 40, Loss: 0.01009878609329462, Weight: 1.9537733793258667
Epoch 50, Loss: 0.0019055854063481092, Weight: 1.979919672012329
Epoch 60, Loss: 0.00035956292413175106, Weight: 1.9912774562835693
Epoch 70, Loss: 6.785020377719775e-05, Weight: 1.9962109327316284
Epoch 80, Loss: 1.2803415302187204e-05, Weight: 1.9983540773391724
Epoch 90, Loss: 2.415695234958548e-06, Weight: 1.999285101890564
Final Model Parameters: [Parameter containing:
tensor([1.9997], requires_grad=True)]
torch.nn.Module.