PyTorch .cos()
Anonymous contributor
Published Aug 1, 2025
Contribute to Docs
The .cos() function computes the cosine of each element in the input tensor, applied element-wise, and returns a tensor of the same shape. It’s part of PyTorch’s math operations used in scientific computing and deep learning.
Syntax
torch.cos(input, *, out=None) → Tensor
Parameters:
input(Tensor): Input tensor with elements in radians.out(Tensor, optional): Optional tensor to store the output.
Return value:
A tensor with the cosine of each element in the input, having the same shape.
Example 1: Using .cos() with a 1D tensor
In this example, .cos() computes the cosine of a 1D tensor containing angles in radians:
import torch# Create a tensor with values in radiansx = torch.tensor([0, torch.pi / 2, torch.pi])# Compute the cosiney = torch.cos(x)print(y)
The output of this code is:
tensor([ 1.0000e+00, -4.3711e-08, -1.0000e+00])
Example 2: Applying .cos() with a 2D tensor
In this example, .cos() is applied to a 2D tensor of angles in radians:
import torch# Create a 2x2 tensormatrix = torch.tensor([[0, torch.pi / 3], [torch.pi / 2, torch.pi]])# Compute the cosineresult = torch.cos(matrix)print(result)
The output of this code is:
tensor([[ 1.0000e+00, 5.0000e-01],[-4.3711e-08, -1.0000e+00]])
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PyTorch on Codecademy
- Learn to build machine learning models with Python.
- Includes 10 Courses
- With Certificate
- Beginner Friendly.23 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours