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 can I use Yolov5 with PyTorch?
- How can I use Python and PyTorch to parse XML files?
- How do I save a PyTorch tensor to a file using Python?
- How do I use PyTorch with Python version 3.11?
- How do I install the PyTorch nightly version for Python?
- How do I determine the version of Python and PyTorch I'm using?
- How can I use Python Torch to create a Tensor?
- How can I use Python and PyTorch to query data?
- How can I use PyTorch with Python 3.11?
- How can I use Python and PyTorch to create a U-Net architecture?
See more codes...