How to use function torch in Python? - with practical example
Step 1: In this example, we will use the torch function in Python to create a tensor of ones with a specific shape.
Explanation: We will import the torch library, then use the torch.ones() function to create a tensor of ones with a shape of (2, 3). This means the tensor will have 2 rows and 3 columns.
Step 2: Now, let's use the torch function in Python to perform element-wise addition on two tensors. Explanation: We will create two tensors with the same shape, then use the torch.add() function to add them together element-wise.
import torch # Create a tensor of ones with shape (2, 3) ones_tensor = torch.ones(2, 3) print(ones_tensor)
Step 2: Now, let's use the torch function in Python to perform element-wise addition on two tensors. Explanation: We will create two tensors with the same shape, then use the torch.add() function to add them together element-wise.
import torch # Create two tensors with the same shape tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]]) tensor2 = torch.tensor([[7, 8, 9], [10, 11, 12]]) # Perform element-wise addition result_tensor = torch.add(tensor1, tensor2) print(result_tensor)
Comments
Post a Comment