PyTorch Tensors: Basics & Creation Guide
PyTorch Tensors: Basics & Creation Guide
Agar tumne NumPy use kiya hai toh good news — PyTorch ka tensor similar hota hai NumPy
array jaisa.
PyTorch extra features deta hai:
GPU acceleration (Fast training)
Automatic differentiation (for backpropagation)
💡 Bonus:
1/40
Linear Algebra ke basics — jaise matrix multiplication, vector addition — agar aate hain toh
aur easy ho jayega.
📦 Use cases:
Data cleaning
Loss function define karna
Neural network banana
Simulations aur research
🧪 Example:
python
import torch
# ek simple tensor
x = [Link]([1.0, 2.0, 3.0])
print(x)
Scalar 0D 5 [Link](5)
2/40
Name Dimensions Example PyTorch Shape
🧠 Real-Life Example:
Grayscale image = 2D tensor (height x width)
RGB image = 3D tensor (height x width x 3)
Video = 4D (frames x height x width x 3)
Batch of videos = 5D
3/40
Step What You'll Learn
🧠 Example:
A 3x3 matrix:
X ∈ ℝ^(3×3)
A 28x28 grayscale image:
I ∈ ℝ^(28×28)
A batch of 64 RGB images (3 channels):
B ∈ ℝ^(64×3×28×28)
4/40
Concept Samajh
import torch
# 1D Vector
v = [Link]([10, 20, 30])
print([Link]) # [Link]([3])
# 2D Matrix
m = [Link]([[1, 2], [3, 4]])
print([Link]) # [Link]([2, 2])
5/40
🔥 Part 2: Tensor Creation in PyTorch
✅ Step 1: Basic Setup
python
import torch
import numpy as np
print(torch.__version__)
🧪 Example:
6/40
python
# Scalar
s = [Link](7)
# Vector
v = [Link]([1, 2, 3])
# Matrix
m = [Link]([[1, 2], [3, 4]])
# 3D Tensor
t = [Link]([[[1,2],[3,4]], [[5,6],[7,8]]])
🧠 Tip:
.shape : Each dimension me kitne elements
.dim() : Kitni dimensions hain
torch.int32 4 Integers
7/40
Data Type Bytes Use for
🧪 Example:
python
print(a.element_size()) # 4 bytes
print(b.element_size()) # 8 bytes
print(c.element_size()) # 4 bytes
print(d.element_size()) # 1 byte
💡 Important Concept:
torch.from_numpy() gives a view, not a copy.
Agar NumPy array change hua, PyTorch tensor bhi change ho jayega.
Use [Link](np_array.copy()) agar independent tensor chahiye.
8/40
Function Description Example
📌 Masking Example:
python
mask = [Link](5)
mask[1:3] = 1
# Like range()
[Link](0, 10) # 0 to 9
[Link](0, 10, 2) # 0, 2, 4, 6, 8
# Log spacing
[Link](1, 4, 5) # [10^1, ..., 10^4]
🧠 Tip:
9/40
linspace includes both start and end
arange excludes end value (like Python range)
# Identity-like (2x4)
[Link](2, 4)
10/40
Task Function
🧠 Real-Life Analogy
💡 zeros, ones, full: Blank notebooks with predefined content
📏 arange, linspace: Number lines (rulers) with equal spacing
🧬 diag, eye: DNA patterns jahan diagonal me values chahiye
🔄 from_numpy: Convert borrowed data into PyTorch-friendly format
🏁 Homework Practice
1. Create a 5×5 tensor filled with 9.
2. Create a 4D tensor with shape (2,3,4,5) with random values.
3. Create identity matrix of size 6×6 and extract diagonal.
4. Convert a numpy array to torch tensor, modify numpy array and observe tensor.
11/40
🧮 PART 1: Random Tensor Generation
📌 Use Cases:
Neural Network ka weight initialization
Data augmentation (noise add karna)
Monte Carlo simulation
Synthetic data banana for testing
Variability / randomness model karna (e.g., dropout)
⚙️ Description:
Ye values 0 to 1 ke beech me random hoti hain.
Float32 by default
Uniform distribution ka matlab: sab value aane ka equal chance
python
print(rand_tensor.shape) # (3, 4)
print(rand_tensor.dtype) # torch.float32
print(rand_tensor.min()) # Min value
print(rand_tensor.max()) # Max value
print(rand_tensor.mean()) # Mean (expected ~0.5)
print(rand_tensor.std()) # Standard deviation (~0.288)
12/40
📸 2. Image-Like Random Tensor
python
⚙️ Explanation:
RGB image: 224x224 pixels, 3 channels
Legacy of ImageNet: most pretrained CNNs expect 224×224 inputs
📐 Memory Check:
python
📌 Real-Life Analogy:
Jese tum ek TV screen ke pixels ko random colors se fill kar rahe ho testing ke liye.
noise = torch.rand_like(img_tensor)
noisy_image = img_tensor + 0.1 * noise # Add little noise
13/40
[Link](0, 10) # 0 to 9
[Link](0, 12, 2) # Step size = 2
📌 2. [Link]
python
📌 3. [Link]
python
🧠 Summary Table
Function Description
a = [Link](2, 3)
b = torch.zeros_like(a)
c = torch.ones_like(a)
Ye functions help karte hain jab shape same chahiye but value alag.
14/40
🔄 PART 4: Data Types and Requires Grad
python
💡 Use Case:
requires_grad=True => for automatic gradient calculation in backprop
x = [Link]([1, 2, 3])
print(x + 10) # Adds 10 to each element => [11, 12, 13]
print(x - 5) # Subtracts 5 => [-4, -3, -2]
print(x * 2) # Multiply => [2, 4, 6]
print(x / 2) # Divide => [0.5, 1.0, 1.5]
🔁 Reassignment
python
x += 10
print(x) # Now x is modified
🧪 Code:
python
# Method 1
C = [Link](A, B)
# Method 3 (manual)
C = [Link](A, B)
print(C)
🤯 Real Meaning:
Dot product = Similarity
High value = similar direction
Neural networks use this in linear layers, attention, gradient calc
16/40
Tensors
├── Random: rand, rand_like
│ ├── Uniform [0,1], float32
│ ├── Use: noise, augmentation, init
├── Sequential: arange, linspace, logspace
│ ├── Use: indexing, counters
├── Arithmetic
│ ├── Add, Sub, Mul, Div
│ ├── Reassignment
├── Matrix Ops
│ ├── Element-wise (*)
│ ├── Matrix Multiplication (@ or matmul)
│ └── Dot Product (dot)
🧪 Homework Practice
1. Create a random tensor of shape (5, 5) and calculate min, max, mean, std.
2. Generate linspace values between 2 and 10 with step 2.
3. Make two 2×3 and 3×2 tensors, multiply them and verify shape.
4. Use dot() on any two vectors and explain result in terms of similarity.
17/40
🧱 1. Reshape a Tensor
python
x = [Link]([1, 2, 3, 4, 5, 6, 7])
x_reshaped = [Link](1, 7)
📌 Points:
.reshape(a, b) : New shape
Doesn't change data, just arrangement
Very useful in matrix multiplication where dimensions must match
👓 2. .view() vs .reshape()
python
z = [Link](1, 7)
🔍 Difference:
reshape() may return a copy (not guaranteed)
python
z[0][0] = 99
print(x) # x[0] is also 99 now
🧱 3. Stacking Tensors
python
x = [Link]([1, 2, 3, 4])
stacked_0 = [Link]([x, x, x, x], dim=0)
stacked_1 = [Link]([x, x, x, x], dim=1)
18/40
💡 dim=0 → stack row-wise
plaintext
dim=0 → 4x4
dim=1 → 4x4 (but columns come from different tensors)
💡 Use:
Remove any dimension with size 1
Useful when shapes are like (1, N) or (N, 1) but you want just (N,)
x = [Link]([1, 2, 3, 4])
x_unsq = [Link](0) # shape becomes (1, 4)
📌 Use:
Add dimension where needed for broadcasting or matrix mult
python
[Link](1).shape # (4, 1)
19/40
img = [Link](224, 224, 3) # HWC
img_p = [Link](2, 0, 1) # CHW
📌 Why:
PyTorch expects input as (Channel, Height, Width)
Image libraries like OpenCV/PIL give (Height, Width, Channel)
🔍 7. Indexing Tensors
python
x = [Link](1, 10).reshape(1, 3, 3)
📐 Shape:
1 matrix of 3x3
Examples:
python
🧠 Real-World Analogy:
Tensor = Excel sheet (multi-dimensional)
: means "select all"
x[0, :, 2] means "get all rows in sheet 0, column 2"
20/40
Operation Function Result Shape
🧪 Homework Practice
1. Create a tensor of shape (1, 3, 3) and try:
21/40
.squeeze()
.unsqueeze(0)
Next:
🎯 GPU Acceleration → , check availability, copy data
.to("cuda")
🎯 Broadcasting → Tensor arithmetic with mismatched shapes
Bhai chahiye toh in sabka revision PDF + worksheet bhi bana deta hoon. Batao.
🔄 NumPy to PyTorch
🧪 Example:
22/40
python
import numpy as np
import torch
print(tensor_from_np)
print(tensor_from_np.shape) # [Link]([7])
print(tensor_from_np.dtype) # torch.float64 / torch.int64 (depends on np_array)
⚠️ Important:
torch.from_numpy() returns a view, not a copy
Matlab agar np_array me change karoge, tensor_from_np bhi change ho jayega
🔁 PyTorch to NumPy
🧪 Example:
python
print(np_from_tensor)
print(np_from_tensor.shape) # (4,)
print(np_from_tensor.dtype) # int64
⚠️ Important:
.numpy() bhi ek view deta hai
Agar tensor change hua, toh np_from_tensor bhi change hoga (and vice versa)
🧠 Real-Life Analogy
Socho NumPy ek Hindi speaker hai aur PyTorch ek English speaker
Tum dono ko ek translator chahiye jo ek hi sentence ko Hindi aur English dono me samjha
23/40
sake — bina dobara likhe.
Yeh translator = view!
print([Link]) # torch.float32
python
🛑 Common Pitfalls
Mistake What Happens?
python
24/40
# NumPy → PyTorch (copy)
tensor = [Link](np_array.copy())
📌 Summary Table
Operation Function
🎯 Use-Cases
Use Case PyTorch or NumPy?
🧪 Homework Practice
25/40
1. Convert NumPy array of shape (3, 3) to PyTorch tensor, modify one value in NumPy, and
observe change in tensor
2. Convert PyTorch tensor to NumPy array, modify tensor, and see if NumPy changes too
3. Create a safe, independent copy while converting and verify they are separate
"Agar kal ya koi dusra banda same code, same data, same settings use kare… to same results
aaye."
python
import torch
A = [Link](2, 2)
26/40
print(A)
To har baar naya output aayega — kyuki yeh random tensor hai.
Lekin agar tum research paper likh rahe ho, ya production model deploy kar rahe ho, ya
debug kar rahe ho —
Random output se kaam nahi chalega.
python
import torch
torch.manual_seed(42)
A = [Link](2, 2)
print(A)
27/40
⚡ For GPU: [Link].manual_seed(seed)
Agar CUDA GPU use kar rahe ho, to alag seed set karna padta hai:
python
if [Link].is_available():
[Link].manual_seed(42)
Full Code:
python
import torch
seed = 42
torch.manual_seed(seed)
if [Link].is_available():
[Link].manual_seed(seed)
# Now generate
print([Link](2, 2)) # CPU
print([Link](2, 2).cuda()) # GPU (if available)
🔐 Ek Important Note:
Reproducibility perfect nahi hoti jab:
Multi-GPU kaam karta hai (parallelism ka randomness hota hai)
CuDNN backend ka non-deterministic operations use ho jaata hai
28/40
Agar 100% determinism chahiye:
python
torch.use_deterministic_algorithms(True)
⚠️ Yeh slow kar sakta hai training ko, but reproducibility milega.
import torch
# CPU reproducibility
torch.manual_seed(42)
# GPU reproducibility
if [Link].is_available():
[Link].manual_seed(42)
# Generate tensor
A = [Link](2, 2)
print(A)
📦 Summary Cheatsheet:
Task Command
29/40
Task Command
for i in range(3):
torch.manual_seed(42)
print([Link](0, 10, (5,)))
⚙️ GPUs are:
Parallel processing machines (can do 1000s of tasks at once)
Super optimized for vectorized and matrix ops
30/40
🖥️ Step 1: Check If GPU is Available
python
import torch
print([Link].is_available())
Output:
✅ → GPU is available
True
❌ → GPU not available (you’re stuck with CPU)
False
python
!nvidia-smi
This gives:
GPU Name (like A100 , T4 , RTX 3080 )
GPU Memory
Driver version
Usage stats
📌 Note: On Colab, drivers and CUDA are already installed. On your own system, you must
install CUDA Toolkit .
31/40
print([Link].memory_allocated(0)) # Used memory
print([Link].memory_reserved(0)) # Reserved memory
total = [Link].get_device_properties(0).total_memory
print(total)
✅ Move to GPU:
python
tensor_gpu = tensor_cpu.to('cuda')
python
tensor_gpu = tensor_cpu.cuda()
32/40
python
tensor_gpu.numpy()
You'll get:
vbnet
RuntimeError: Can't convert CUDA tensor to numpy. Use [Link]() to copy it to host memory first.
🧠 Why?
Because NumPy only works with CPU memory.
tensor_back_to_cpu = tensor_gpu.cpu()
array = tensor_back_to_cpu.numpy()
print(array)
🔁 Summary Table
Task Code
33/40
Task Code
python
👉 Useful when you download pre-trained models or use third-party libraries that need specific
versions.
34/40
Benefit Description
🧠 Real-Life Analogy
Socho GPU ek express train hai jo 1000 passengers (calculations) ek saath le ja sakta hai
CPU ek auto rickshaw hai — reliable but slow.
# Move to GPU
t_gpu = [Link]('cuda')
# Do some operation
t_result = t_gpu * 2
# Convert to NumPy
print(t_cpu.numpy())
35/40
🔴 Part 1: Shape Mismatch Error
💡 Most common error in PyTorch matrix operations.
🔸 Problem:
python
❌ Error:
Because A is shape (3x2) and B is shape (3x2)
Matrix multiplication rule:
A (m x n) @ B (n x p) → Output: (m x p)
But here, inner dims don’t match ( 2 != 3 )
A → (3×2)
B.T → (2×3)
✔️ Now matmul is valid
✔️ Output shape = (3×3)
🔁 Shortcut:
python
36/40
C = [Link](A, B.T)
❌ Error:
Both tensors have different data types:
t1 → float16
t2 → float32
python
t = [Link](torch.float32)
Or shortcut:
python
t = [Link]()
t = [Link]() # Float16
t = t.int8()
37/40
🔴 Part 3: CPU vs GPU Mismatch Error
🔸 Problem:
python
❌ Error:
pgsql
python
t1 = [Link]()
t2 = [Link]()
38/40
❌ Error Type 🧠 Reason ✅ Fix
Data type mismatch Float16 vs Float32 or int8, etc. Use
.type(torch.float32
) or .float()
✅ Monitor memory:
Use [Link].memory_allocated() to avoid OOM (Out Of Memory)
torch.manual_seed(42)
if [Link].is_available():
[Link].manual_seed(42)
39/40
40/40