0
0
PyTorchml~10 mins

Broadcasting 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 add a tensor and a scalar using broadcasting.

PyTorch
import torch

a = torch.tensor([1, 2, 3])
b = 5
result = a [1] b
print(result)
Drag options to blanks, or click blank then click option'
A/
B-
C*
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Trying to add without an operator.
2fill in blank
medium

Complete the code to multiply a 2D tensor by a 1D tensor using broadcasting.

PyTorch
import torch

a = torch.tensor([[1, 2, 3], [4, 5, 6]])
b = torch.tensor([1, 0, 1])
result = a [1] b
print(result)
Drag options to blanks, or click blank then click option'
A*
B+
C-
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of multiplication.
Trying to multiply tensors with incompatible shapes without broadcasting.
3fill in blank
hard

Fix the error in the code by completing the broadcasting operation correctly.

PyTorch
import torch

a = torch.tensor([[1, 2, 3], [4, 5, 6]])
b = torch.tensor([1, 2])
result = a [1] b
print(result)
Drag options to blanks, or click blank then click option'
A+
B*
C-
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication which causes shape mismatch.
Trying to add tensors with incompatible shapes without broadcasting.
4fill in blank
hard

Fill both blanks to create a tensor of shape (3, 4) by broadcasting a (3, 1) tensor with a (1, 4) tensor.

PyTorch
import torch

a = torch.tensor([[1], [2], [3]])  # shape (3, 1)
b = torch.tensor([[4, 5, 6, 7]])  # shape (1, 4)
result = a [1] b
print(result.shape)  # should print torch.Size([2])
Drag options to blanks, or click blank then click option'
A*
B+
C(3, 4)
D(4, 3)
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of multiplication.
Confusing the output shape dimensions.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps each word to its length if the length is greater than 3.

PyTorch
words = ['apple', 'bat', 'carrot', 'dog']
lengths = { [1]: [2] for word in words if len(word) [3] 3 }
print(lengths)
Drag options to blanks, or click blank then click option'
Aword
Blen(word)
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong comparison operator.
Swapping key and value in the dictionary comprehension.