PyTorch Rad2deg examples

This PyTorch article will look at converting radians to degrees using the rad2deg() method. PyTorch is an open-source framework that uses Python as its programming language.

A tensor is a multidimensional array used to store data. Consequently, we must first load the torch module to use a tensor. Further, tensor is the method used to build a tensor().

<div class="wp-block-codemirror-blocks-code-block code-block">

In this case, the data is a multidimensional array.


Rad2deg() in PyTorch translates tensor radians to degrees. It only requires one parameter. The syntax is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">


tensor_object refers to a tensor

Return Value

The return value gives you a new array tensor with degrees.

What is a torch.Tensor?

A torch.Tensor is a multidimensional matrix with only one data type’s elements. Additionally, torch. Tensor is a shorthand for the default tensor type (torch.FloatTensor).

Ten types of tensors

Torch defines ten tensor types, each with its CPU and GPU variant:

Type 1:data type: 32-bit floating point

  • The dtype is torch.float32 or torch.float
  • The CPU tensor is torch.FloatTensor
  • The GPU tensor is torch.cuda.FloatTensor

Type 2: data type: 64-bit floating point

  • The dtype is torch.float64 or torch.double
  • The CPU tensor is torch.DoubleTensor
  • The GPU tensor is torch.cuda.DoubleTensor

Type 3: data type: 16-bit floating point 1

  • The dtype is torch.float16 or torch.half
  • The CPU tensor is the torch.HalfTensor
  • The GPU tensor is torch.cuda.HalfTensor

Type 4: data type: 16-bit floating point 2

  • The dtype is the torch.bfloat16
  • The CPU tensor is torch.BFloat16Tensor
  • The GPU tensor is torch.cuda.BFloat16Tensor

Type 5: data type: 32-bit complex

  • The dtype is the torch.complex32

Type 6: data type: 64-bit complex

  • The dtype is the torch.complex64

Type 7: data type: 128-bit complex

  • The dtype is torch.complex128 or torch.cdouble

Type 8: data type: 8-bit integer (unsigned)

  • The dtype is the torch.uint8
  • The CPU tensor is torch.ByteTensor
  • The GPU tensor is torch.cuda.ByteTensor

Type 9: data type: 16-bit integer (signed)

  • The dtype is torch.int16 or torch.short
  • The CPU tensor is torch.ShortTensor
  • The GPU tensor is torch.cuda.ShortTensor

Type 10: data type: 32-bit integer (signed)

  • The dtype is torch.int32 or
  • The CPU tensor is torch.IntTensor
  • The GPU tensor is torch.cuda.IntTensor

11. data type: 64-bit integer (signed)

  • The dtype is torch.int64 or torch.long
  • The CPU tensor is torch.LongTensor
  • The GPU tensor is torch.cuda.LongTensor

12. data type: Boolean

  • The dtype is the torch.bool
  • The CPU tensor is torch.BoolTensor
  • The GPU tensor is torch.cuda.BoolTensor

The torch.Tensor() constructor can be used to create a tensor from a Python list or sequence:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>torch.tensor([[1., -1.], [1., -1.]])
tensor([[ 1., -1.], [ 1., -1.]])
torch.tensor(np.array([[4, 5, 6], [10, 8, 9]]))
tensor([[4, 5, 6], [7, 8, 9]])</pre>

The function torch.tensor() always copies data. To prevent a copy, use requires_grad_() or detach() if you only want to update the requires_grad_flag of a Tensor data. Use torch.as_tensor() if you have a numpy array and wish to avoid a copy.

By giving a torch.dtype alongside or without a torch.device to a tensor creation op or constructor, a tensor of a certain data type can be created:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>torch.zeros([2, 4], dtype=torch.int32)
tensor([[ 0,  0,  0,  0],
        [ 0,  0,  0,  0]], dtype=torch.int32)
cuda0 = torch.device('cuda:0')
torch.ones([5, 7], dtype=torch.float64, device=cuda0)
tensor([[ 1.0000,  1.0000,  1.0000,  1.0000],
        [ 1.0000,  1.0000,  1.0000,  1.0000]], dtype=torch.float64, device='cuda:0')</pre>

Python’s indexing and slicing notation can be used to access and modify the contents of a tensor:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>var_x = torch.tensor([[1, 2, 3], [4, 5, 6]])
x[0][1] = 8
tensor([[ 1,  8,  3],
        [ 4,  5,  6]])</pre>

Use torch.Tensor.item() in the retrieval of a Python number from a tensor with a single value:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>var_x = torch.tensor([[1]])


var_x = torch.tensor(2.5)

With requires_grad=True, a tensor can be built such that torch.autograd records operations on it for automatic differentiation.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>var_x = torch.tensor([[1., -1.], [1., 1.]], requires_grad=True)
out = var_x.pow(2).sum()
tensor([[ 2., -2.],
        [ 2.,  2.]])</pre>

Each tensor is paired with a torch. Storage is where data is kept. The tensor class also defines numeric operations on storage and gives a multidimensional, strided view of it.

Example 1: Creating a one-dimensional tensor

In this example, we’ll make a tensor with one dimension and five elements, then convert it to degrees.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>#initially, begin by importing the module, torch
import torch

 #creation of a tensor with one dimension
var_data = torch.tensor([1.54,5.87,9.10,4.76,7.63])

 # show the initial data before conversion
print("Actual radians contained in the Tensor: ")


print("Conversion of the tensor into degrees")


The Actual radians contained in the Tensor output are represented as follows:

Creating a one-dimensional tensor
Creating a one-dimensional tensor


Example 2: Two-dimensional tensor

In this example, we will generate a two-dimensional tensor with five elements in each row and convert it to radians.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre># start by importing the torch module

import torch

#create a 2D tensor

var_data = torch.tensor([[1.54,5.87,9.10,4.76,7.63],[1,2,3,4,5]])

# show the actual radians before conversion
print("Actual radians contained in the Tensor: ")

print("Show the resultant degrees after cnversion")

How to work with the CPU

To run a rad2deg() function on the CPU, we must first create a tensor with a cpu() function. This will be executed on a CPU computer. This time, when we generate a tensor, we may utilize the cpu() function. The syntax is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">

Example 1: Using the CPU to generate tensors

In this example, we will use the CPU to generate a tensor with one dimension and five elements and convert it to degrees.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>#start by importing the torch module

import torch

 #creation of tensor with one dimension

var_data = torch.tensor([1.54,5.87,9.10,4.76,7.63]).cpu()

# showing the initial tensor before conversion
print(" These are the real radians present in the Tensor: ")

print("Resultant degrees after tensor conversion")

Example 2: Generating a two-Dimensional tensor

In this example, we will generate a two-dimensional tensor with five elements on the CPU in each row and convert it to radians.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>#start by importing the torch module
import torch

#creation of a tensor with two dimensions
var_data = torch.tensor([[1.54,5.87,9.10,4.76,7.63],[1,2,3,4,5]]).cpu()

#shows the actual tensor by its conversion
print("The Tensor containing actual radians: ")

print("The resultant degrees after conversion")

How to use Mars for converting angles from degrees to radians

The syntax is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>mars.tensor.rad2deg(x, out=None, where=None, **kwargs)</pre>

The Parameters are listed below:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>x (array_like) - Radian angle</pre>

out (Tensor, None, or tuple of Tensor and None, optional) – The location where the result will be stored. If one is provided, it must have a shape to which the inputs broadcast. If no tensor is provided or None is specified, a newly allocated tensor is returned. A tuple (only permitted as a keyword parameter) must be the same length as the number of outputs.

where (array_like, optional) – True values indicate that the ufunc should be calculated at that position, while False values suggest that the value in the output should be left alone.

**kwargs –

Returns are:

y – represents the corresponding degree angle.

The return type here is a Tensor

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>rad2deg(x) is 180 * x / pi.

import mars.tensor as mt


Example: Angles in radians transformed to degrees as input

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>var_data = torch.tensor([[4.142, -2.142], [7.283, -5.283], [2.570, -0.570]])

Example: Pass a Floating point number in the rad2deg function

<div class="wp-block-codemirror-blocks-code-block code-block">

For the rad2deg function, the tensor is intended to be a floating point number. Long cannot be cast using the Float type. So, we may declare dtype as a float for the tensor and then do the rad2deg function.

Example: How to Convert Radians to Degrees Using np.arange() and a Function

Because your angle x is in degrees, you’ll want to convert it to radians using several ways, such as np.deg2rad. So the code is:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>var_x = np.arange(0, 360, 0.1) # angles represent as degrees starting at 0 to 360
var_y = np.cos(np.deg2rad(var_x))  # conversion of var_x to degrees before application of cosine</pre>

Example: Integrating Rad2deg with other methods

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>%%matplotlib inline
import matplotlib.pyplot as plt'seaborn-whitegrid')
import numpy as np

var_x = np.arange(0, 360, 0.1)
var_y = np.cos(np.deg2rad(var_x))  
plt.plot(var_x, var_y, 'o', color='blue')
plt.xlabel('Angle (Degrees)')


We explored the rad2deg() function in this PyTorch Rad2deg article. The latter is responsible for converting the provided tensor angles in radians to degrees. We also executed the tensor on the CPU by examining the two examples. Additionally, rad2deg() is one of the less well-known PyTorch tensors to investigate some procedures for mathematical calculations.

Most importantly, when working with datasets containing variables relating to angles, the rad2deg function is beneficial.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *