Deep Learning with PyTorch / Tensors

Create and inspect tensors

Lesson 4 of 41. Open to read. No account needed.

The Problem: Every Number Lives in a Tensor

In the training script from the previous lesson, the inputs, the targets, the predictions, the loss and every weight in the model were tensors. A tensor is PyTorch's container for numbers: a block of values arranged along one or more dimensions, all of one type, stored in one place. Most errors in deep learning code are tensor mistakes: the wrong shape, the wrong type of number, or two tensors that cannot be combined. This lesson teaches you to create tensors and to read the three properties that cause those mistakes: shape, dtype and device.

A Bridge from NumPy

If you have used NumPy arrays, tensors will feel familiar. Check yourself before continuing. For the array below, predict the three shapes, then read the answers underneath.

import numpy as np
a = np.arange(12).reshape(3, 4)   # 3 rows, 4 columns
a.shape        # ?
a[0].shape     # ?
a[:, 1:3].shape   # ?

(3, 4), then (4,) because one row of four values remains, then (3, 2) because every row is kept and columns 1 and 2 are selected. If those came easily, you are ready. If not, practise NumPy indexing first: the next three lessons build on it.

Shape, dtype and Device

A three-by-four grid of the numbers 0 to 11, with dimension 0 of size 3 running down the rows and dimension 1 of size 4 across the columns, labelled shape (3, 4), dtype torch.int64 and device cpu. Below, a NumPy array and a from_numpy tensor both point to one block of data, while a dashed clone points to its own copy.

What a tensor carries. The top half shows the three properties; the bottom half shows which tensors share memory with a NumPy array.

Shape lists the size of each dimension. The grid above has shape (3, 4): dimension 0 has 3 entries (the rows) and dimension 1 has 4 (the columns). A single number has shape (), a list of five numbers (5,), and a batch of 64 greyscale images of 28 by 28 pixels (64, 1, 28, 28). t.shape reports it, t.ndim gives the number of dimensions and t.numel() the number of values.

dtype is the type of every value in the tensor (S27). Three matter most in this course:

dtypeHoldsUsed for
torch.float32Decimal numbers, 32 bits eachInputs, weights, predictions, losses: PyTorch's default for decimals
torch.float64Decimal numbers, 64 bits eachWhat NumPy creates by default; occasionally for precise checks
torch.int64Whole numbersClass labels and counts

Simple arithmetic between different dtypes is allowed: PyTorch promotes both to a common type, so int64 + float32 gives float32. Matrix multiplication, which every layer performs, is stricter and needs matching dtypes. A model's weights are float32, so its inputs must be too.

device is where the values are stored: cpu means the computer's main memory. Tensors on a GPU would show a different device, and tensors on different devices cannot be combined. Everything in the core course stays on cpu.

Ways to Create a Tensor

You haveUseResult
Python numbers or nested liststorch.tensor([[0, 1], [2, 3]])A new tensor; whole numbers become int64, decimals float32
A size and a filltorch.zeros(2, 3), torch.ones(4), torch.full((2, 2), 7.0)A tensor of that shape
A rangetorch.arange(12)0, 1, …, 11 as int64
Random valuestorch.rand(5) (between 0 and 1), torch.randn(5) (centred on 0)float32
A NumPy arraytorch.from_numpy(array) or torch.as_tensor(array, dtype=...)See below

.reshape(3, 4) rearranges the same values into a new shape; the next lesson explains it fully (S26).

NumPy arrays need care. torch.from_numpy(array) does not copy the data: the tensor and the array share the same memory, so changing one changes the other (S31). It also keeps NumPy's dtype, and NumPy's default for decimals is float64. Going the other way, t.numpy() on a CPU tensor also shares memory (S32). Two ways to break the link:

  • .clone() makes an independent copy with the same dtype.
  • torch.as_tensor(array, dtype=torch.float32) converts to float32, which requires a new block of memory.

Exercise: Predict, Then Inspect

Starting state: the course environment active.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/pytorch-practice/tensor-basics
    cd ~/pytorch-practice/tensor-basics
    

    Windows PowerShell:

    mkdir $HOME\pytorch-practice\tensor-basics
    cd $HOME\pytorch-practice\tensor-basics
    
  2. Save this as tensor_basics.py:

    """Create tensors in several ways, then inspect shape, dtype, device and memory."""
    import numpy as np
    import torch
    
    grid_a = torch.tensor([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
    grid_b = torch.arange(12).reshape(3, 4)
    array = np.arange(12, dtype=np.float64).reshape(3, 4)
    grid_c = torch.from_numpy(array)
    
    for name, t in [("grid_a", grid_a), ("grid_b", grid_b), ("grid_c", grid_c)]:
        print(f"{name}: shape {tuple(t.shape)}, dtype {t.dtype}, device {t.device}")
    
    print("Python floats:", torch.tensor([1.0, 2.0]).dtype)
    print("zeros(2, 3):", torch.zeros(2, 3).dtype, tuple(torch.zeros(2, 3).shape))
    print("rand(5):", torch.rand(5).dtype)
    print("class labels:", torch.tensor([0, 2, 1]).dtype)
    
    array[0, 0] = 100.0
    print("grid_c[0, 0] after changing the array:", grid_c[0, 0].item())
    independent = torch.from_numpy(array).clone()
    array[0, 0] = 0.0
    print("clone[0, 0] after changing the array again:", independent[0, 0].item())
    converted = torch.as_tensor(array, dtype=torch.float32)
    print("as_tensor with float32:", converted.dtype, "| shares memory:", converted.data_ptr() == grid_c.data_ptr())
    
  3. Before running, write your predictions for each printed value: the three dtypes of the grids, the four dtypes on the next lines, and the two [0, 0] values. Then run it:

    python tensor_basics.py
    

    Output (exact; these values do not vary between computers):

    grid_a: shape (3, 4), dtype torch.int64, device cpu
    grid_b: shape (3, 4), dtype torch.int64, device cpu
    grid_c: shape (3, 4), dtype torch.float64, device cpu
    Python floats: torch.float32
    zeros(2, 3): torch.float32 (2, 3)
    rand(5): torch.float32
    class labels: torch.int64
    grid_c[0, 0] after changing the array: 100.0
    clone[0, 0] after changing the array again: 100.0
    as_tensor with float32: torch.float32 | shares memory: False
    

Success: your predictions match after at most one revision, and you can say why each line printed what it did.

How the Script Works

  • Three grids, two dtypes. grid_a comes from Python whole numbers and grid_b from arange, so both are int64. grid_c comes from a NumPy array made with dtype=np.float64, and from_numpy keeps that type.
  • tuple(t.shape) prints the shape as a plain tuple, (3, 4), rather than PyTorch's torch.Size([3, 4]). They mean the same thing.
  • The four single lines show the defaults: Python decimals become float32, zeros and rand make float32, Python whole numbers become int64.
  • array[0, 0] = 100.0 changes the NumPy array, and grid_c[0, 0] now reads 100.0 too, because from_numpy shared the memory. .item() turns a one-value tensor into a Python number.
  • The clone was taken while the value was 100.0. Setting the array back to 0.0 does not affect it, so it still reads 100.0.
  • as_tensor(..., dtype=torch.float32) converted the values to 32-bit, which needs new memory. data_ptr() returns the memory address where a tensor's data starts; different addresses mean no sharing.

Your Turn: A Type Mismatch

Save this as layer_input.py in the same folder:

"""Feed NumPy data to a linear layer."""
import numpy as np
import torch
from torch import nn

features = np.random.default_rng(0).normal(size=(4, 3))
layer = nn.Linear(3, 2)
print(layer(torch.from_numpy(features)).shape)

nn.Linear(3, 2) is a layer that turns 3 numbers into 2; its weights are float32 (S42). np.random.default_rng(0).normal(size=(4, 3)) makes four rows of three random NumPy numbers. Run python layer_input.py. It fails, and the traceback ends with:

RuntimeError: mat1 and mat2 must have the same dtype, but got Double and Float

Fix it with a one-line change so that it prints torch.Size([4, 2]). Then explain the message: which tensor is Double, and which is Float?

Clean Up

cd ~/pytorch-practice
ls
rm -r tensor-basics
ls

Windows PowerShell:

cd $HOME\pytorch-practice
ls
Remove-Item -Recurse tensor-basics
ls

Check Your Understanding

  1. You load labels for ten classes with torch.tensor([3, 7, 1]). What dtype do you get, and is it suitable for labels?
  2. You create t = torch.from_numpy(a), then normalise a in place with a -= a.mean(). What happens to t?
  3. A batch of 32 colour images of 64 by 64 pixels has three colour channels. Predict its shape in PyTorch's usual layout.

Answer and Reasoning

Your turn

Change the last line to convert the data to float32:

print(layer(torch.from_numpy(features).float()).shape)

torch.as_tensor(features, dtype=torch.float32) works equally well. The message names the two dtypes in PyTorch's older vocabulary: Double is float64, from NumPy's default, and Float is float32, the layer's weights. mat1 and mat2 are the two matrices the layer multiplies: your input and its weights. A model's inputs must match its weights' dtype, and converting the data is the usual fix rather than changing the model.

Understanding check

  1. torch.int64, which is what PyTorch's classification losses expect for class labels.
  2. t changes too, because from_numpy shares memory and -= changes the array in place. If you need the original values, clone() before modifying.
  3. (32, 3, 64, 64): batch, channels, height, width. PyTorch's image layers expect channels before height and width.

References

36 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy