0
0
PyTorchml~10 mins

Tensor shapes and dimensions in PyTorch - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a tensor of shape (3, 4).

PyTorch
import torch
x = torch.zeros([1])
print(x.shape)
Drag options to blanks, or click blank then click option'
A(4, 3)
B[3, 4, 5]
C(3, 4)
D[4, 3]
Attempts:
3 left
💡 Hint
Common Mistakes
Using square brackets instead of parentheses for shape.
Swapping the dimensions (4, 3) instead of (3, 4).
2fill in blank
medium

Complete the code to get the number of dimensions of tensor x.

PyTorch
import torch
x = torch.randn(2, 5, 7)
dimensions = x.[1]()
print(dimensions)
Drag options to blanks, or click blank then click option'
Ashape
Bndim
Csize
Ddim
Attempts:
3 left
💡 Hint
Common Mistakes
Using shape which returns the size tuple, not the number of dimensions.
Using ndim which is not a PyTorch method.
3fill in blank
hard

Fix the error in the code to reshape tensor x to shape (6, 10).

PyTorch
import torch
x = torch.randn(3, 20)
x = x.[1]((6, 10))
print(x.shape)
Drag options to blanks, or click blank then click option'
Aview
Bresize
Creshape
Dresize_
Attempts:
3 left
💡 Hint
Common Mistakes
Using reshape() which can sometimes cause errors if tensor is not contiguous.
Using resize() which changes the tensor size in-place and can cause unexpected behavior.
4fill in blank
hard

Fill both blanks to create a tensor of shape (2, 3) and then flatten it to 1D.

PyTorch
import torch
x = torch.randn([1])
x_flat = x.[2]()
print(x_flat.shape)
Drag options to blanks, or click blank then click option'
A(2, 3)
B(3, 2)
Cflatten
Dview
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the shape dimensions.
Using view() without specifying the new shape.
5fill in blank
hard

Fill all three blanks to create a tensor, get its shape, and access the size of the second dimension.

PyTorch
import torch
x = torch.randn([1])
shape = x.[2]
second_dim = shape[[3]]
print(second_dim)
Drag options to blanks, or click blank then click option'
A(4, 5, 6)
Bshape
C1
Dsize
Attempts:
3 left
💡 Hint
Common Mistakes
Using size() method instead of shape attribute.
Accessing index 0 or 2 instead of 1 for the second dimension.