|
| 1 | +--- |
| 2 | +Title: '.cos()' |
| 3 | +Description: 'Computes the cosine of each element in the input tensor.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Machine Learning' |
| 7 | +Tags: |
| 8 | + - 'Deep Learning' |
| 9 | + - 'PyTorch' |
| 10 | + - 'Tensors' |
| 11 | +CatalogContent: |
| 12 | + - 'learn-python-3' |
| 13 | + - 'paths/machine-learning' |
| 14 | +--- |
| 15 | + |
| 16 | +The **`.cos()`** function computes the cosine of each element in the input [tensor](https://www.codecademy.com/resources/docs/pytorch/tensors), 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. |
| 17 | + |
| 18 | +## Syntax |
| 19 | + |
| 20 | +```py |
| 21 | +torch.cos(input, *, out=None) → Tensor |
| 22 | +``` |
| 23 | + |
| 24 | +**Parameters:** |
| 25 | + |
| 26 | +- `input` (Tensor): Input tensor with elements in radians. |
| 27 | +- `out` (Tensor, optional): Optional tensor to store the output. |
| 28 | + |
| 29 | +**Return value:** |
| 30 | + |
| 31 | +A tensor with the cosine of each element in the input, having the same shape. |
| 32 | + |
| 33 | +## Example 1: Using `.cos()` with a 1D tensor |
| 34 | + |
| 35 | +In this example, `.cos()` computes the cosine of a 1D tensor containing angles in radians: |
| 36 | + |
| 37 | +```py |
| 38 | +import torch |
| 39 | + |
| 40 | +# Create a tensor with values in radians |
| 41 | +x = torch.tensor([0, torch.pi / 2, torch.pi]) |
| 42 | + |
| 43 | +# Compute the cosine |
| 44 | +y = torch.cos(x) |
| 45 | + |
| 46 | +print(y) |
| 47 | +``` |
| 48 | + |
| 49 | +The output of this code is: |
| 50 | + |
| 51 | +```shell |
| 52 | +tensor([ 1.0000e+00, -4.3711e-08, -1.0000e+00]) |
| 53 | +``` |
| 54 | + |
| 55 | +## Example 2: Applying `.cos()` with a 2D tensor |
| 56 | + |
| 57 | +In this example, `.cos()` is applied to a 2D tensor of angles in radians: |
| 58 | + |
| 59 | +```py |
| 60 | +import torch |
| 61 | + |
| 62 | +# Create a 2x2 tensor |
| 63 | +matrix = torch.tensor([[0, torch.pi / 3], [torch.pi / 2, torch.pi]]) |
| 64 | + |
| 65 | +# Compute the cosine |
| 66 | +result = torch.cos(matrix) |
| 67 | + |
| 68 | +print(result) |
| 69 | +``` |
| 70 | + |
| 71 | +The output of this code is: |
| 72 | + |
| 73 | +```shell |
| 74 | +tensor([[ 1.0000e+00, 5.0000e-01], |
| 75 | + [-4.3711e-08, -1.0000e+00]]) |
| 76 | +``` |
0 commit comments