Complete the code to reshape a tensor of shape (4, 3) into (2, 6) using PyTorch.
import torch x = torch.randn(4, 3) y = x.[1](2, 6) print(y.shape)
The view method reshapes the tensor without copying data if possible. Here, view(2, 6) changes the shape from (4, 3) to (2, 6).
Complete the code to add a new dimension at position 1 to a tensor of shape (3, 4).
import torch x = torch.randn(3, 4) y = x.[1](1) print(y.shape)
The unsqueeze method adds a dimension of size 1 at the specified position. Here, unsqueeze(1) changes shape from (3, 4) to (3, 1, 4).
Fix the error in the code to remove all dimensions of size 1 from the tensor.
import torch x = torch.randn(1, 3, 1, 5) y = x.[1]() print(y.shape)
The squeeze method removes all dimensions of size 1. Here, it changes shape from (1, 3, 1, 5) to (3, 5).
Fill both blanks to reshape a tensor and then add a new dimension at the end.
import torch x = torch.randn(6, 4) y = x.[1](3, 8).[2](-1) print(y.shape)
First, reshape(3, 8) changes the shape from (6, 4) to (3, 8). Then, unsqueeze(-1) adds a new dimension at the end, resulting in shape (3, 8, 1).
Fill all three blanks to create a dictionary with keys as the tensor's dimension sizes and values as the dimension indices, but only for dimensions larger than 1.
import torch x = torch.randn(1, 5, 1, 7) result = {x.shape[[1]]: [2] for [3] in range(len(x.shape)) if x.shape[[1]] > 1} print(result)
We use i as the loop variable and index to access each dimension size. The dictionary comprehension maps dimension sizes greater than 1 to their indices.