python-pytorchHow can I set a random seed in Python using PyTorch?
The random seed in Python can be set using PyTorch. To do this, you will need to use the torch.manual_seed()
method. This method takes an integer as an argument, which is used to set the seed for the random number generator.
# Set seed
torch.manual_seed(1234)
# Generate random numbers
x = torch.rand(2, 3)
# Print random numbers
print(x)
# Output
tensor([[0.2645, 0.5346, 0.6404],
[0.8923, 0.5346, 0.8975]])
The code above sets the random seed to 1234 and then generates a 2x3 tensor of random numbers.
Code explanation
torch.manual_seed()
: This method sets the random seed for the random number generator.torch.rand()
: This method generates a tensor of random numbers.
Helpful links
More of Python Pytorch
- How do I check the Python version requirements for PyTorch?
- How can I use Python, PyTorch, and YOLOv5 to build an object detection model?
- What is the most compatible version of Python to use with PyTorch?
- How can I use Python and PyTorch to parse XML files?
- How do I install a Python PyTorch .whl file?
- How do I use Pytorch with Python 3.11 on Windows?
- How do I uninstall Python PyTorch?
- How do I install the PyTorch nightly version for Python?
- How can I use Yolov5 with PyTorch?
- How can I use Python PyTorch with CUDA?
See more codes...