EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials PyTorch Tutorial PyTorch Random
Secondary Sidebar
PyTorch Tutorial
  • PyTorch
    • PyTorch Image Classification
    • PyTorch Random
    • PyTorch Variable
    • PyTorch Activation Function
    • Python Formatted String
    • PyTorch GPU
    • PyTorch CUDA
    • PyTorch DataLoader
    • PyTorch LSTM
    • PyTorch Pad
    • PyTorch OpenCL
    • PyTorch Lightning
    • PyTorch SoftMax
    • PyTorch Flatten
    • PyTorch gan
    • PyTorch max
    • PyTorch pip
    • PyTorch Parameter
    • PyTorch Load Model
    • PyTorch Distributed
    • PyTorch BERT
    • PyTorch interpolate
    • PyTorch JIT
    • PyTorch expand
    • PyTorch AMD
    • PyTorch GRU
    • PyTorch rnn
    • PyTorch permute
    • PyTorch argmax
    • PyTorch SGD
    • PyTorch nn
    • PyTorch One Hot Encoding
    • PyTorch Tensors
    • What is PyTorch?
    • PyTorch MSELoss()
    • PyTorch NLLLOSS
    • PyTorch MaxPool2d
    • PyTorch Pretrained Models
    • PyTorch Squeeze
    • PyTorch Reinforcement Learning
    • PyTorch zero_grad
    • PyTorch norm
    • PyTorch VAE
    • PyTorch Early Stopping
    • PyTorch requires_grad
    • PyTorch MNIST
    • PyTorch Conv2d
    • Dataset Pytorch
    • PyTorch tanh
    • PyTorch bmm
    • PyTorch profiler
    • PyTorch unsqueeze
    • PyTorch adam
    • PyTorch backward
    • PyTorch concatenate
    • PyTorch Embedding
    • PyTorch Tensor to NumPy
    • PyTorch Normalize
    • PyTorch ReLU
    • PyTorch Autograd
    • PyTorch Transpose
    • PyTorch Object Detection
    • PyTorch Autoencoder
    • PyTorch Loss
    • PyTorch repeat
    • PyTorch gather
    • PyTorch sequential
    • PyTorch U-NET
    • PyTorch Sigmoid
    • PyTorch Neural Network
    • PyTorch Quantization
    • PyTorch Ignite
    • PyTorch Versions
    • PyTorch TensorBoard
    • PyTorch Dropout
    • PyTorch Model
    • PyTorch optimizer
    • PyTorch ResNet
    • PyTorch CNN
    • PyTorch Detach
    • Single Layer Perceptron
    • PyTorch vs Keras
    • torch.nn Module

PyTorch Random

PyTorch Random

Introduction to PyTorch Random

PyTorch random is the functionality available in PyTorch that enables us to get a tensor with random values that belong to the range of 0 to 1. The values are filled using a uniform distribution. In this article, we will try to dive deep into the topic of PyTorch random and understand What PyTorch random is, how to create PyTorch random, alternative PyTorch, PyTorch random examples, and finally provide our conclusion on the same.

What is PyTorch random?

PyTorch random functionality provides a tensor object containing the random values between the specified interval or, by default, between 0 to 1, [0,1] interval. The functional definition with its fully qualified name looks as shown below –

Torch.rand (* size, *, out = None, stype = None, layout = torch. strided, device = None, requires_grad = False

Output -The return value of the above function is a tensor object containing random values. Here, the argument named size helps specify the tensor size we want as an output.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Let’s understand various arguments or parameters that we need to pass to the rand function to get a tensor of random values –

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,328 ratings)
  • Size – This is the integer value that helps specify the shape of the tensor that we get as a resultant and is a sequence of integers. It can be a tuple, list, or any variable number of parameters.
  • Out – We get the optional parameter and a tensor value as the output.
  • Device – It is an optional argument and is of the type torch. device. It helps in the specification of the required devices of the output tensor. When not specified, the default value of this argument corresponds to None, which means that the same current device is used for that type of tensor. For example, in the case of CUDA tensor types, the device of CUDA that is currently used is the preferred device, while in the case of CPU tensor types, its corresponding CPU device is referred to by the device.
  • Generator – It is an optional argument of type torch. Generator and us a pseudo-random number created or generated just for the sampling.
  • Dtype – It is also an optional argument of type torch. dtype is used to specify the data type we want for the return output tensor. The default value corresponds to None and is a global value when not specified. For more information about this, you can read about the torch. set_default_tensor_type().
  • Requires_grad – It is an optional argument of Boolean type and has its default value set to false. It specifies whether the auto grad should record all the operations carried on returned tensor.
  • Layout – It is an optional argument of the torch. Layout type that has its default value set to torch. strode. It helps get the choice of device we want for the output tensor.

How to Create PyTorch random?

We can create the PyTorch random tensor containing random values in the range of 0 to 1 simply by importing the torch library in your program and then use the rand function to create your tensor by passing the required size of the output tensor in the parameter. Other optional arguments can also be passed as per your requirement and convenience.

Suppose you want to create a tensor containing random values of size 4, then you can write the statement in your program as a torch.rand(4) after you import the torch at the top. This will create a tensor object having uniformly distributed random values between the range of 0 to 1 of size 4, which means four columns in 1 row.

Alternative PyTorch random

None of the equivalent alternatives are present for implementing np.random.choice(). You can use the indexing with random integer values or shuffled indexing.

When you want to carry out this without doing any replacement, then you can follow the below steps –

  • You can go for the generation of n indices that are created randomly.
  • Further, you can use these indices to index the source tensor object, which is your original tensor.
  • For example, when you have a tensor named images, you can use the following statement – images [torch.randint(len(images))]

When you want to perform the same task without the involvement of any replacement, then you can follow the below steps –

  • The index should be shuffled.
  • Retrieve the first n elements from the tensor.
  • For example, we will refer to the same scenario above and use the following code.

sampleIndexes = torch.randperm(len(images))[:10] images[smapleIndexes]

Suppose you want more information about the torch.randint and torch.randperm, refer to this article.

PyTorch random examples

Let us now consider some examples that will help us understand the implementation of PyTorch random, the rand function.

Example #1

We are creating one tensor containing random values and having the shape (2,3)

sampleEducbaTensor1 = torch.rand(2, 3)
print(sampleEducbaTensor1)

The output of executing the above code snippet is as shown in the below image –

PyTorch Random output 1

Example #2

We will take one example where we are passing the tuple to define the shape

sampleEducbaTensor2 = torch.rand((2, 3))
print(sampleEducbaTensor2)

The output of executing the above code snippet is as shown in the below image –

PyTorch Random output 2

Example #3

let’s create a tensor having four size

sampleEducbaTensor3 = torch.rand(4)
print(sampleEducbaTensor3)

The output of executing the above code snippet is as shown in the below image –

PyTorch Random output 3

Example #4

creating a tensor with the shape of (2,3)

sampleEducbaTensor4 =  torch.rand(2, 3)
print(sampleEducbaTensor4)

The output of executing the above code snippet is as shown in the below image –

output 4

Conclusion

PyTorch random functionality generates a tensor with a random value in nature and between intervals of [0,1]. For this, we will have to use the torch.rand() function and we can specify the desired size and shape of the output tensor we want as a resultant.

Recommended Articles

This is a guide to PyTorch Random. Here we discuss What PyTorch is random, how to create PyTorch random, alternative PyTorch, and PyTorch random examples. You may also look at the following articles to learn more –

  1. PyTorch Detach
  2. PyTorch GPU
  3. PyTorch TensorBoard
  4. Dataset Pytorch
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more