0
0
PyTorchml~5 mins

First PyTorch computation

Choose your learning style9 modes available
Introduction

PyTorch helps us do math with numbers easily on computers. It is useful for building smart programs that learn from data.

When you want to add or multiply numbers using a computer program.
When you want to create a simple math example to understand how PyTorch works.
When you want to prepare for building machine learning models.
When you want to try out basic operations on data like addition or multiplication.
When you want to see how PyTorch handles numbers and calculations.
Syntax
PyTorch
import torch

a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
c = a + b
print(c)

Use torch.tensor() to create a tensor, which is like a list of numbers.

You can do math operations like + directly on tensors.

Examples
This example subtracts two tensors element-wise.
PyTorch
import torch

x = torch.tensor([10, 20])
y = torch.tensor([1, 2])
z = x - y
print(z)
This example multiplies two tensors element-wise.
PyTorch
import torch

p = torch.tensor([2, 3])
q = torch.tensor([4, 5])
r = p * q
print(r)
This example divides two tensors element-wise with decimal numbers.
PyTorch
import torch

s = torch.tensor([1.5, 2.5])
t = torch.tensor([2.0, 3.0])
u = s / t
print(u)
Sample Model

This program creates two lists of numbers called tensors. It adds and multiplies them element by element and prints the results.

PyTorch
import torch

# Create two tensors
x = torch.tensor([3, 6, 9])
y = torch.tensor([1, 2, 3])

# Add the tensors
total = x + y

# Multiply the tensors
product = x * y

# Print results
print('Sum:', total)
print('Product:', product)
OutputSuccess
Important Notes

Tensors are like lists but can do math faster and on special hardware like GPUs.

PyTorch uses tensor objects to hold numbers for calculations.

You can do math operations directly on tensors without loops.

Summary

PyTorch tensors hold numbers for math operations.

You can add, subtract, multiply, and divide tensors easily.

Basic PyTorch computations help you start building machine learning models.