0
0
PyTorchml~10 mins

Flatten layer 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 Flatten layer in PyTorch.

PyTorch
import torch.nn as nn

flatten = nn.[1]()
Drag options to blanks, or click blank then click option'
AConv2d
BLinear
CFlatten
DReLU
Attempts:
3 left
💡 Hint
Common Mistakes
Using Linear instead of Flatten
Using Conv2d or ReLU which are not flattening layers
2fill in blank
medium

Complete the code to flatten the input tensor except the batch dimension.

PyTorch
import torch

x = torch.randn(10, 3, 28, 28)  # batch of 10 images
x_flat = x.[1](start_dim=1)
Drag options to blanks, or click blank then click option'
Aflatten
Bview
Creshape
Dsqueeze
Attempts:
3 left
💡 Hint
Common Mistakes
Using view or reshape without specifying correct shape
Using squeeze which removes dimensions of size 1
3fill in blank
hard

Fix the error in the code to correctly flatten the input tensor.

PyTorch
import torch
import torch.nn as nn

class Model(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()

    def forward(self, x):
        x = self.flatten(x)
        x = x.[1](1)
        return x
Drag options to blanks, or click blank then click option'
Aview
Bunsqueeze
Creshape
Dflatten
Attempts:
3 left
💡 Hint
Common Mistakes
Using view or reshape without shape argument
Using unsqueeze which adds dimensions instead of flattening
4fill in blank
hard

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

PyTorch
words = ['apple', 'cat', 'banana', 'dog']
lengths = {word: [1] for word in words if [2]
Drag options to blanks, or click blank then click option'
Alen(word)
Bword
Clen(word) > 3
Dword > 3
Attempts:
3 left
💡 Hint
Common Mistakes
Using word instead of len(word) as value
Using word > 3 which compares string to int
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps uppercase words to their lengths if length is less than 6.

PyTorch
words = ['apple', 'cat', 'banana', 'dog']
result = { [1]: [2] for word in words if [3] }
Drag options to blanks, or click blank then click option'
Aword.upper()
Blen(word)
Clen(word) < 6
Dword.lower()
Attempts:
3 left
💡 Hint
Common Mistakes
Using word.lower() instead of word.upper()
Using wrong condition like len(word) > 6