YouTip LogoYouTip

Pytorch Torch Cosh

## PyTorch torch.cosh The `torch.cosh` function in PyTorch is used to compute the element-wise hyperbolic cosine ($\cosh$) of a given input tensor. --- ## Mathematical Definition For any real or complex number $x$, the hyperbolic cosine is defined mathematically as: $$\cosh(x) = \frac{e^x + e^{-x}}{2}$$ --- ## Syntax and Parameters ### Syntax ```python torch.cosh(input, *, out=None) -> Tensor ``` ### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | `input` | `Tensor` | The input tensor containing the values (in radians) for which to compute the hyperbolic cosine. | | `out` | `Tensor` (Optional) | The output tensor. If provided, the result will be written into this tensor. | ### Return Value * Returns a new tensor containing the element-wise hyperbolic cosine of the `input` tensor. * The returned tensor has the same shape and data type as the `input` tensor. --- ## Code Examples ### Example 1: Basic Usage with a 1D Tensor This example demonstrates how to compute the hyperbolic cosine for a simple 1D tensor of floating-point numbers. ```python import torch # Create a 1D tensor x = torch.tensor([0, 1, 2, 3], dtype=torch.float32) # Compute the hyperbolic cosine result = torch.cosh(x) print("Input Tensor:") print(x) print("\nResult Tensor (cosh):") print(result) # Output: tensor([ 1.0000, 1.5431, 3.7622, 10.0677]) ``` ### Example 2: Using the `out` Parameter You can write the result directly to an existing tensor using the `out` parameter to optimize memory usage. ```python import torch x = torch.tensor([-1.0, 0.0, 1.0]) output_tensor = torch.empty_like(x) # Compute cosh and store the result in output_tensor torch.cosh(x, out=output_tensor) print("Output Tensor:") print(output_tensor) # Output: tensor([1.5431, 1.0000, 1.5431]) ``` ### Example 3: In-place Operation PyTorch also provides an in-place version of the function, `torch.cosh_` (with a trailing underscore), which modifies the input tensor directly. ```python import torch x = torch.tensor([0.5, 1.5], dtype=torch.float32) # Perform in-place cosh calculation x.cosh_() print("Modified Input Tensor:") print(x) # Output: tensor([1.1276, 2.3524]) ``` --- ## Considerations and Behavior 1. **Minimum Value**: Since $\cosh(0) = 1$ and $\cosh(x) \ge 1$ for all real $x$, the output values for real-valued inputs will always be greater than or equal to $1.0$. 2. **Symmetry**: The hyperbolic cosine is an even function, meaning $\cosh(x) = \cosh(-x)$. 3. **Data Types**: `torch.cosh` supports floating-point and complex tensor types. If you pass integer tensors, PyTorch will automatically promote them to floating-point types (typically `torch.float32` or `torch.float64`) to perform the calculation.
← Pytorch Torch Cuda Empty_CachePytorch Torch Corrcoef β†’