MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

PyTorch Lab – 2 – Pytorch Tensors

This lab covers the core PyTorch tensor operations: creating tensors, choosing data types, in-place and out-of-place operations, indexing and slicing, splitting and joining, views and reshaping, and sorting. The notebook above was recorded on PyTorch 1.0.1. The sections below explain what each part does and point out where current PyTorch 2.x behaves differently. They also include an updated version of the code and fixes for the errors the notebook shows on purpose.


Setting up the lab environment

The notebook ran on PyTorch 1.0.1 under Anaconda with Python 3.7. Both versions are long out of support. Use a recent Python 3 and the current PyTorch release in a virtual environment. The CPU build is enough for every cell in this lab.

python3 -m venv torch-lab
source torch-lab/bin/activate
pip install torch jupyter
python -c "import torch; print(torch.__version__, torch.cuda.is_available())"
jupyter notebookCode language: JavaScript (javascript)

Note: For a GPU build, take the exact install command from the selector on the official PyTorch website. The right wheel depends on your CUDA version. A plain pip install torch on Linux may install a different build than the one you need.

Legacy calls in the notebook and their modern equivalents

Several calls in the example above still run, but they use the old type-specific constructors (torch.Tensor, torch.ShortTensor, torch.FloatTensor, .type(torch.IntTensor)). Current PyTorch code sets the type with the dtype argument and builds tensors with factory functions. These are clearer, and they also accept device.

Notebook codeRecommended todayWhy
torch.Tensor([[1,2,3],[4,5,6]])torch.tensor([[1,2,3],[4,5,6]], dtype=torch.float32)torch.tensor infers or accepts an explicit dtype. torch.Tensor always uses the default float type.
torch.Tensor(2, 2)torch.empty(2, 2)Makes it explicit that the memory is uninitialised.
torch.tensor([5, 3]).type(torch.IntTensor)torch.tensor([5, 3], dtype=torch.int32)Creates the tensor once instead of creating it and then casting.
torch.ShortTensor([1.0, 2.0, 3.0])torch.tensor([1, 2, 3], dtype=torch.int16)Legacy typed constructors are discouraged.
.type(torch.half).to(torch.float16) or .half().to() handles both dtype and device.
torch.FloatTensor([...])torch.tensor([...], dtype=torch.float32)Same reason as above.
torch.full((2, 6), fill_value=10)torch.full((2, 6), 10.0) or pass dtype=Current versions infer the dtype from the fill value, so an integer 10 gives an int64 tensor, not the float output shown above.
sparse_tensor.datasparse_tensor or sparse_tensor.to_dense().data bypasses autograd tracking and should not be used for inspection.

Updated lab code for current PyTorch

This version of the creation cells runs cleanly on current PyTorch. It fixes the seed so random values are repeatable. It also leaves the default dtype at float32, which is what most models and GPUs expect.

import torch

print(torch.__version__)
torch.manual_seed(0)                      # repeatable random values
print(torch.get_default_dtype())          # torch.float32

t = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.float32)
print(t.shape, t.dtype, t.numel())        # torch.Size([2, 3]) torch.float32 6

empty  = torch.empty(2, 2)                # garbage values, never read before writing
rand   = torch.rand(2, 2)                 # uniform [0, 1)
t_int  = torch.tensor([5, 3], dtype=torch.int32)
t_i16  = torch.tensor([1, 2, 3], dtype=torch.int16)
t_half = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)

full_f = torch.full((2, 6), 10.0)         # float32
full_i = torch.full((2, 6), 10)           # int64 on current versions

ones  = torch.ones(2, 4, dtype=torch.int32)
zeros = torch.zeros_like(ones)            # same shape, dtype and device as ones
eye   = torch.eye(5)

print(torch.nonzero(eye))                 # shape (5, 2): one [row, col] per non-zero
rows, cols = torch.nonzero(eye, as_tuple=True)  # tuple form, usable for indexing

i = torch.tensor([[0, 1, 1],              # row indices
                  [2, 2, 0]])             # column indices
v = torch.tensor([3.0, 4.0, 5.0])
sparse = torch.sparse_coo_tensor(i, v, (2, 5))
print(sparse.to_dense())Code language: PHP (php)

The dense form of the sparse tensor makes the coordinate format easy to check. Each column of i is one (row, col) position, and the matching entry in v is the value stored there:

tensor([[0., 0., 3., 0., 0.],
        [5., 0., 4., 0., 0.]])Code language: CSS (css)

What the default dtype controls

torch.set_default_dtype() changes the type used when PyTorch has to pick a floating-point type itself, for example in torch.rand, torch.eye, torch.Tensor(...) and torch.tensor([1.0, 2.0]). Integer tensors are not affected. That is why the notebook's torch.set_default_dtype(torch.int) raises a TypeError: the default can only be a floating-point type.

Note: The notebook sets the default to float64 near the top and never sets it back, so every later float tensor in that session is double precision. float64 doubles memory use and is much slower on most GPUs. Run torch.set_default_dtype(torch.float32) after the experiment, or pass dtype=torch.float64 only where you need it.

In-place operations, views and shared memory

Methods that end in an underscore (add_, sqrt_, fill_) modify the tensor they are called on. The version without the underscore returns a new tensor. Some in-place operations have no underscore: x += 1, index assignment such as x[0] = 5, and functions called with an out= argument. The notebook says fill_ has no out-of-place equivalent. There is no Tensor.fill method, which is the AttributeError shown above, but torch.full_like(x, 10) does the same job out of place.

view(), transpose(), slicing and unsqueeze() return views. A view shares memory with the original tensor, so changing one changes the other. That is why resized_tensor showed 100. after random_tensor[2, 2] was changed. Use clone() when you need an independent copy.

a = torch.tensor([[10., 8., 30.], [40., 5., 6.], [12., 2., 21.]])

flat = a.view(9)
print(flat.data_ptr() == a.data_ptr())   # True: same storage
print(a.view(-1, 3).shape)               # torch.Size([3, 3]); -1 is inferred

at = a.T                                 # transpose is a view, not contiguous
print(at.is_contiguous())                # False
# at.view(9)  -> RuntimeError: view size is not compatible with input tensor's size and stride
print(at.reshape(9))                     # works; copies when it has to
print(at.contiguous().view(9))           # equivalent explicit form

safe = a.clone()                         # independent copy
safe[0, 0] = -1
print(a[0, 0])                           # tensor(10.) - original unchanged

# torch.tensor() copies NumPy data; torch.from_numpy() shares it
import numpy as np
n = np.ones(3)
shared = torch.from_numpy(n)
n[0] = 99
print(shared)                            # tensor([99., 1., 1.], dtype=torch.float64)Code language: PHP (php)

Note: In-place operations can break autograd. Calling w.add_(1) on a leaf tensor created with requires_grad=True raises a RuntimeError. Wrap the update in with torch.no_grad():, which is what optimizers do internally.

Splitting, joining and sorting: what the arguments mean

FunctionSecond argument meansExample from the lab
torch.chunk(x, n, dim)Number of chunks15 elements, 3 chunks: three tensors of 5
torch.split(x, size, dim)Size of each piece (or a list of sizes)3 rows split by 2: a 2-row tensor and a 1-row tensor
torch.cat(seq, dim)Existing dimension to join alongShapes must match in every other dimension
torch.stack(seq, dim)New dimension to createAll tensors must have exactly the same shape
torch.sort(x, dim=-1, descending=False)Dimension to sort alongReturns (values, indices) and sorts each row by default

When the size does not divide evenly, chunk may return fewer pieces than requested, while split always returns pieces of the requested size plus a smaller last piece. Use split when every piece must have a fixed size, for example mini-batches. To sort columns instead of rows, call torch.sort(a, dim=0). For only the largest or smallest k values, torch.topk is faster than a full sort.

Common errors in this lab and how to fix them

ErrorCauseFix
TypeError: only floating-point types are supported as the default typePassing an integer dtype to set_default_dtypePass dtype=torch.int32 to the tensor instead
AttributeError: 'Tensor' object has no attribute 'fill'No out-of-place fill method existsUse x.fill_(v) or torch.full_like(x, v)
RuntimeError: shape '[-1, 6]' is invalid for input of size 9The new shape must have exactly the same number of elements; 9 is not divisible by 6Use a compatible shape such as view(-1, 3) or view(9)
view size is not compatible with input tensor's size and strideCalling view on a non-contiguous tensor, such as a transposeUse reshape() or call .contiguous() first
Sizes of tensors must match except in dimension 0Mismatched shapes passed to torch.catCheck .shape of every input; reshape or pad first
expected scalar type Float but found DoubleMixing float64 data (often from NumPy or the default dtype) with float32 modelsConvert with .float() or .to(torch.float32)

Note: In the notebook, resized_tensor.size() still returns torch.Size([9]) after the failed view(-1, 6). The assignment never happened, so the variable still holds the earlier flattened view. The new shape was not partly applied.

Frequently asked questions

What is the difference between torch.Tensor and torch.tensor?

torch.tensor() is a factory function that infers the dtype from the data, or takes an explicit dtype, and always copies the data. torch.Tensor is the class constructor. It always produces the default floating-point type, and with integer arguments it allocates uninitialised memory of that shape. Use torch.tensor for data and torch.empty, torch.zeros or torch.ones for a given shape.

What is the difference between view() and reshape() in PyTorch?

view() always returns a tensor that shares memory with the original and fails if the tensor is not contiguous. reshape() returns a view when it can and makes a copy when it must, so it works on any tensor.

How do I make an independent copy of a PyTorch tensor?

Use x.clone(). Add .detach() if the copy should not be tracked by autograd. Assignment (y = x), slicing and view() all share memory with the original.

Why does torch.full return an integer tensor?

Current PyTorch versions infer the dtype from fill_value, so torch.full((2, 3), 10) returns int64. Pass 10.0 or dtype=torch.float32 to get a float tensor.

When should I avoid in-place operations?

Avoid them on tensors that autograd needs for the backward pass, especially leaf tensors with requires_grad=True. These raise errors or produce wrong gradients. They are safe for preprocessing data or inside a torch.no_grad() block.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

PyTorch Lab – 9 – Pytorch CUDA Semantics

This lab covers how PyTorch builds a computation graph on the fly as tensor operations run, and how that graph behaves when tensors and models are on…

Read More

PyTorch Lab – 8 – Pytorch Install And Setup Tensorflow Hidden Layer

This lab sets up HiddenLayer, a small Python library that draws neural network graphs and plots training metrics, along with the Graphviz bindings it uses to render…

Read More

PyTorch Lab – 7 – Pytorch CUDA Semantics

This page covers a PyTorch lab notebook that fits a linear regression model with autograd and manual gradient descent. The title mentions CUDA, but the notebook above…

Read More

PyTorch Lab – 6 – Pytorch Autograd With Variables

This lab uses PyTorch autograd to calculate gradients through a single multiplication, result = var * w1, using the older torch.autograd.Variable wrapper. Below you'll find what each…

Read More

PyTorch Lab – 5 – Pytorch AutogradIntro

This lab shows how PyTorch autograd records operations on tensors and computes gradients. It covers requires_grad, grad_fn, .grad, backward(), torch.no_grad() and detach(). The sections below the notebook…

Read More

PyTorch Lab – 3 – Pytorch Conversions Between PyTorch And NumPy

This lab shows how to convert data between PyTorch tensors and NumPy arrays using tensor.numpy(), torch.from_numpy(), torch.as_tensor() and torch.tensor(). The main point is memory: the first three…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x