How To Initialize A PyTorch Random Number?

This beginner-friendly Pytorch code shows you how to initialize a PyTorch random number with the help of a simple example.

Objective: How To Initialize A PyTorch Random Number?

This PyTorch code example will teach you to initialize a random PyTorch number using the ‘torch.rand()’ function.

What is a PyTorch Random Number?

A PyTorch random number is a random number generated by the PyTorch library. PyTorch provides several different functions for generating random numbers, including torch.rand(), torch.randn(), and torch.randint().

  • torch.rand() generates a tensor filled with random numbers from a uniform distribution on the interval [0, 1).

  • torch.randn() generates a tensor filled with random numbers from a normal distribution with mean 0 and standard deviation 1.

  • torch.randint() generates a tensor filled with random integers from a uniform distribution within a specified range.

Get Access To 70+ Enterprise-Grade Solved End-to-End ML Projects And Become A Data Science Pro

Steps Showing How To Initialize A PyTorch Random Number

The following steps will show you how to initialize PyTorch random numbers with the help of a simple example. For initializing random numbers in PyTorch, you will use torch.rand() function in which the output will be a tensor with random numbers from a uniform distribution on the interval, and the tensor shape is defined by the variable argument.

Step 1 - Import Library

First, you must import the required libraries.

import torch

Step 2 - Initialize PyTorch Random Number

Now, you must initialize the PyTorch random number.

random_torch = torch.rand(10)

print("This is the output for random numbers:", random_torch)

The output of the above code is-

This is the output for random numbers: tensor([0.8356, 0.0017, 0.9482, 0.0250, 0.9233, 0.8312, 0.2956, 0.5680, 0.4770, 0.7483])

How To Initialize A PyTorch Random Number Of A Specific Size?

To initialize a random tensor of a specific size, you can pass the desired size as a tuple to the torch.rand() or torch.randn() function. For example, you can initialize a random tensor of size (3, 4) using the following code-

import torch

random_tensor = torch.rand((3, 4))

How To Initialize A PyTorch Random Number With A Specific Seed?

You can use the torch.manual_seed() function to initialize a random tensor with a specific seed to set the seed before calling the torch.rand() or torch.randn() function. For example, you can initialize a random tensor with the seed 42 using the following code-

import torch

torch.manual_seed(42)

random_tensor = torch.rand((3, 4))

Master PyTorch Random Number with ProjectPro

This PyTorch code example delved into PyTorch random numbers, showing how to initialize random numbers of different types and sizes and with specific seeds. Random numbers play a crucial role in training machine learning models, and mastering their usage is crucial for data scientists and machine learning practitioners. If you aspire to become proficient in PyTorch and leverage it to build real-world data science and machine learning solutions, check out ProjectPro. The hands-on PyTorch projects and expert guidance offered by ProjectPro enable you to gain practical experience and proficiency in employing PyTorch for complex data science challenges.

What Users are saying..

profile image

Abhinav Agarwal

Graduate Student at Northwestern University
linkedin profile url

I come from Northwestern University, which is ranked 9th in the US. Although the high-quality academics at school taught me all the basics I needed, obtaining practical experience was a challenge.... Read More

Relevant Projects

Build OCR from Scratch Python using YOLO and Tesseract
In this deep learning project, you will learn how to build your custom OCR (optical character recognition) from scratch by using Google Tesseract and YOLO to read the text from any images.

Recommender System Machine Learning Project for Beginners-1
Recommender System Machine Learning Project for Beginners - Learn how to design, implement and train a rule-based recommender system in Python

Text Classification with Transformers-RoBERTa and XLNet Model
In this machine learning project, you will learn how to load, fine tune and evaluate various transformer models for text classification tasks.

FEAST Feature Store Example for Scaling Machine Learning
FEAST Feature Store Example- Learn to use FEAST Feature Store to manage, store, and discover features for customer churn prediction machine learning project.

Stock Price Prediction Project using LSTM and RNN
Learn how to predict stock prices using RNN and LSTM models. Understand deep learning concepts and apply them to real-world financial data for accurate forecasting.

Llama2 Project for MetaData Generation using FAISS and RAGs
In this LLM Llama2 Project, you will automate metadata generation using Llama2, RAGs, and AWS to reduce manual efforts.

Deep Learning Project for Beginners with Source Code Part 1
Learn to implement deep neural networks in Python .

Learn Hyperparameter Tuning for Neural Networks with PyTorch
In this Deep Learning Project, you will learn how to optimally tune the hyperparameters (learning rate, epochs, dropout, early stopping) of a neural network model in PyTorch to improve model performance.

Learn How to Build PyTorch Neural Networks from Scratch
In this deep learning project, you will learn how to build PyTorch neural networks from scratch.

Natural language processing Chatbot application using NLTK for text classification
In this NLP AI application, we build the core conversational engine for a chatbot. We use the popular NLTK text classification library to achieve this.