In PyTorch, a tensor is a multi-dimensional array that can be used for efficient computation on CPUs and GPUs. A two-dimensional tensor in PyTorch represents a matrix, where each element is identified by two indices: row and column.
To create a two-dimensional tensor in PyTorch, you can use the torch.tensor()
function and provide a nested list or a NumPy array as the input. Here’s an example:
import torch # Create a two-dimensional tensor using a nested list tensor_list = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Create a two-dimensional tensor using a NumPy array import numpy as np numpy_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) tensor_numpy = torch.tensor(numpy_array)
You can also create an empty two-dimensional tensor and initialize it later. For that, you can use the torch.empty()
function and specify the desired shape:
empty_tensor = torch.empty(3, 3) # Creates a 3x3 tensor with uninitialized values
Once you have created a two-dimensional tensor, you can perform various operations on it, such as element-wise operations, matrix multiplication, transposition, and more. PyTorch provides a wide range of functions and methods to manipulate tensors efficiently.
Here’s an example that demonstrates some common operations with two-dimensional tensors:
import torch # Create a two-dimensional tensor tensor = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Accessing individual elements print(tensor[0, 0]) # Output: 1 print(tensor[1, 2]) # Output: 6 # Slicing a tensor print(tensor[:, 1]) # Output: tensor([2, 5, 8]) print(tensor[1:, :2]) # Output: tensor([[4, 5], [7, 8]]) # Matrix multiplication other_tensor = torch.tensor([[2, 2, 2], [2, 2, 2], [2, 2, 2]]) result = tensor.matmul(other_tensor) print(result) # Output: # tensor([[12, 12, 12], # [30, 30, 30], # [48, 48, 48]]) # Transposition transposed_tensor = tensor.transpose(0, 1) print(transposed_tensor) # Output: # tensor([[1, 4, 7], # [2, 5, 8], # [3, 6, 9]])
These are just a few examples of what you can do with two-dimensional tensors in PyTorch. The library provides a rich set of operations and functions for working with tensors efficiently and effectively in deep learning applications.