0
0
PyTorchml~5 mins

Why tensors are PyTorch's core data structure

Choose your learning style9 modes available
Introduction

Tensors are like smart boxes that hold numbers. They help PyTorch do math fast and easily for machine learning.

When you want to store and work with data like images or sounds in a way a computer understands.
When you need to do math on many numbers at once, like adding or multiplying big lists of numbers.
When building machine learning models that learn from data by adjusting many numbers.
When you want to use a GPU to speed up calculations for training AI models.
When you need a flexible way to handle data with different shapes and sizes.
Syntax
PyTorch
import torch

t = torch.tensor([[1, 2], [3, 4]])

Tensors can have any number of dimensions, like 1D (list), 2D (table), or more.

They work like arrays but are designed for fast math and can use GPUs.

Examples
This is a simple list of numbers stored as a tensor.
PyTorch
import torch

# Create a 1D tensor (vector)
t1 = torch.tensor([1, 2, 3])
This is like a table with rows and columns.
PyTorch
import torch

# Create a 2D tensor (matrix)
t2 = torch.tensor([[1, 2], [3, 4]])
This makes a 3 by 3 grid filled with zeros.
PyTorch
import torch

# Create a tensor of zeros with shape 3x3
t3 = torch.zeros(3, 3)
This shows how tensors can be moved to a GPU for faster math.
PyTorch
import torch

# Move tensor to GPU if available
if torch.cuda.is_available():
    t_gpu = t2.to('cuda')
Sample Model

This program shows how tensors hold data and how PyTorch does math with them. It also checks if a GPU is available to speed up work.

PyTorch
import torch

# Create two tensors
x = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
y = torch.tensor([[5, 6], [7, 8]], dtype=torch.float32)

# Add tensors
y_sum = x + y

# Multiply tensors element-wise
product = x * y

# Print results
print('Sum of tensors:\n', y_sum)
print('Element-wise product:\n', product)

# Check if GPU is available and move tensor
if torch.cuda.is_available():
    x_gpu = x.to('cuda')
    print('Tensor moved to GPU:', x_gpu.device)
else:
    print('GPU not available, running on CPU')
OutputSuccess
Important Notes

Tensors are the foundation for all PyTorch operations and models.

They support automatic differentiation, which helps models learn.

Using tensors on a GPU can make training much faster.

Summary

Tensors store numbers in a way computers can easily use for math.

They work on CPUs and GPUs to speed up machine learning tasks.

Understanding tensors is key to using PyTorch effectively.