7 PyTorch Tasks (Advanced)
Seven runnable PyTorch tasks on one tensor: keep a column, stack vs cat, keepdim, pairwise distances, clone, reshape vs view, and softmax's dim.
Work through seven small tensor tasks using the same six values. Each answer is a complete CPU Python snippet, so you can run it independently with PyTorch installed.
The main tensor is [[1, 2, 3], [4, 5, 6]], shape (2, 3): two rows, three columns. Axis numbers and indices start at zero. Write down the output shape as well as the values before opening an answer. That habit catches mistakes that a printed list alone can hide.
Keep one feature as a column
Select the middle column while keeping shape (2, 1). An integer column index removes an axis; choose a slice that retains it.
python import torch x = torch.tensor([[1, 2, 3], [4, 5, 6]]) y = x[:, 1:2] print(y.tolist(), tuple(y.shape))
The stop index 2 is excluded. x[:, 1] selects the same values but gives shape (2,), so it does not satisfy the shape requirement.
Rebuild a batch from separate rows
Take each row of the tensor and combine the rows into shape (2, 3) using stack . What would cat do to those two one-dimensional rows?
python import torch x = torch.tensor([[1, 2, 3], [4, 5, 6]]) rows = [x[0], x[1]] print(torch.stack(rows).tolist()) print(tuple(torch.cat(rows).shape))
Stack adds an axis identifying the row. Cat extends the existing length-three axis and loses the explicit two-row arrangement.
Subtract each row's own mean
Use floating-point values. Produce two rows with mean zero without writing a Python loop. Keep the computed means as a (2, 1) column so they align with rows during subtraction.