YouTip LogoYouTip

Pytorch Torch Dot

## PyTorch torch.dot The `torch.dot` function in PyTorch is used to compute the dot product (inner product) of two 1D tensors (vectors). Unlike NumPy's `np.dot`, which can handle multi-dimensional arrays, PyTorch's `torch.dot` is strictly designed for 1D tensors of the same size. --- ### Function Signature ```python torch.dot(input, other, *, out=None) β†’ Tensor ``` ### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | `input` | Tensor | The first 1D tensor. | | `other` | Tensor | The second 1D tensor. Must have the same number of elements and the same data type as `input`. | | `out` | Tensor (Optional) | The output tensor where the result will be stored. | ### Return Value * Returns a 0-dimensional tensor (scalar) containing the dot product of `input` and `other`. --- ## Code Examples ### Basic Usage The following example demonstrates how to calculate the dot product of two 1D integer tensors. ```python import torch # Define two 1D tensors (vectors) a = torch.tensor([1, 2, 3]) b = torch.tensor([4, 5, 6]) # Calculate dot product: (1 * 4) + (2 * 5) + (3 * 6) = 4 + 10 + 18 = 32 result = torch.dot(a, b) print("Tensor a:", a) print("Tensor b:", b) print("Dot Product:", result) ``` **Output:** ```text Tensor a: tensor([1, 2, 3]) Tensor b: tensor([4, 5, 6]) Dot Product: tensor(32) ``` ### Working with Floating-Point Tensors `torch.dot` works seamlessly with floating-point numbers as well. ```python import torch x = torch.tensor([1.5, 2.5]) y = torch.tensor([2.0, 4.0]) # Calculate dot product: (1.5 * 2.0) + (2.5 * 4.0) = 3.0 + 10.0 = 13.0 result = torch.dot(x, y) print(result) ``` **Output:** ```text tensor(13.) ``` --- ## Important Considerations ### 1. 1D Tensor Constraint `torch.dot` **only** accepts 1D tensors. If you pass a tensor with 2 or more dimensions, PyTorch will raise a `RuntimeError`. ```python import torch # This will raise an error because the tensors are 2D (matrices) matrix_a = torch.tensor([[1, 2], [3, 4]]) matrix_b = torch.tensor([[5, 6], [7, 8]]) # RuntimeError: 1D tensors expected, but got 2D and 2D tensors result = torch.dot(matrix_a, matrix_b) ``` * **Solution for Multi-Dimensional Tensors:** * For matrix multiplication (2D tensors), use `torch.mm` or `torch.matmul`. * For element-wise multiplication followed by a sum, use `torch.sum(a * b)`. ### 2. Matching Dimensions and Types Both input tensors must have the exact same number of elements and share the same data type (e.g., both `torch.float32` or both `torch.int64`). ```python import torch a = torch.tensor([1, 2], dtype=torch.float32) b = torch.tensor([3, 4], dtype=torch.int32) # This will raise a RuntimeError due to mismatched data types result = torch.dot(a, b) ```
← Pytorch Torch DstackPytorch Torch Div β†’