Instructions
- This exam contains 5 sections and 47 questions for a total of 120 points.
- Section 1 — True/False (10 questions, 1 pt each) · Section 2 — Multiple Choice (15 questions, 2 pts each; exactly one correct answer).
- Section 3 — Explain the Code (6 questions, 6 pts each) · Section 4 — Open Questions (6 questions, 5 pts each) · Section 5 — Fill in the Blank (14 blanks, 1 pt each).
- Your answers are stored automatically in this browser. You may close the file and reopen it later; use Save Progress / Load Progress if automatic saving is unavailable (some browsers restrict storage for local files).
- When you finish, click Export Answers (JSON) and keep the downloaded file — it is required for grading.
- No grade is shown here. Grading is done separately after you submit your exported answers.
- Answer every question. Do not move to another question without answering; partial answers are still saved.
Section 1 — True / False
Select True or False for each statement. Some statements are deliberately tricky but fair.
Calling np.empty((3, 4)) creates a 3×4 array whose elements are all set to zero.
In plt.subplot(a, b, c), the index c moves from left to right and then from top to bottom.
loss.backward() both computes the gradients of the parameters and updates their values.
A tensor created with torch.from_numpy(np_array) shares memory with the NumPy array, so modifying the array is also reflected in the tensor.
In the CIFAR-10 lab, the network's forward() method applies a Softmax at the end, so the values passed to torch.max(outputs, 1) are probabilities.
transforms.ToTensor() converts a PIL image to a tensor and scales pixel values from the [0, 255] range to the [0, 1] range.
np.linspace(10, 50, 5) includes the endpoint 50 in its result, while np.arange(10, 50, 10) does not include the endpoint 50.
A data augmentation is only useful if it preserves the meaning of the sample: the label must remain the same after the transformation.
When defining a network by subclassing nn.Module, you must implement both a forward() method and a backward() method; the backward pass is not automatic.
When visualizing augmented samples, the DataLoader should be created with shuffle=True so that a different set of images appears each time the cell is run.
Section 2 — Multiple Choice
Choose exactly one answer for each question.
Which command selects the bottom-right panel of a 2×2 grid of subplots?
A plot of y = x² produced from only three points (x = 0, 1, 2) looks jagged instead of smooth. What is the main reason given in the lab?
Which NumPy function lets you specify the number of evenly spaced samples in an interval, with the endpoint included?
Given a = np.array([[7, 2], [3, 4], [5, 6]]), what does np.amin(a, axis=1) return?
x = np.array([2, 3]) y = np.array([[4, 1], [9, 10], [12, 13]]) result = x * y
What is the shape of result?
A tensor x has shape (2, 3). What is the shape of torch.cat([x, x], dim=1)?
Which statement about memory sharing between NumPy and PyTorch is correct?
Immediately after calling loss.backward(), which statement is correct?
w is created with requires_grad=False (frozen) while b has requires_grad=True. After loss.backward() followed by optimizer.step(), what happens?
Which expression defines the ReLU activation function?
An input tensor of shape 3×32×32 passes through nn.Conv2d(3, 6, 5) (stride 1, padding 0). What is the spatial size of each output feature map?
After iterating a FashionMNIST DataLoader with batch_size=64, the code prints train_features.size() → torch.Size([64, 1, 28, 28]). What does this mean?
With transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) applied after ToTensor(), what is the value range of the resulting pixels?
outputs has shape [4, 10] and the code runs t, predicted = torch.max(outputs, 1). What does predicted contain?
To which family of data augmentation does transforms.RandomCrop belong?
Section 3 — Explain the Code
Write your answers in the boxes. Explain what the code does, what it produces, and why — in your own words.
import numpy as np x = np.array([2, 3]) y = np.array([[4, 1], [9, 10], [12, 13]]) result = x * y print(result.shape)
(a) What is printed? (b) What are the values of result? (c) Which NumPy mechanism makes this operation possible, and how does it work? (d) Is this matrix multiplication?
import torch x = torch.ones(5) y = torch.zeros(3) w = torch.randn(5, 3, requires_grad=True) b = torch.randn(3, requires_grad=True) z = torch.matmul(x, w) + b loss = torch.nn.functional.binary_cross_entropy_with_logits(z, y) loss.backward() print(w.grad.shape) optimizer = torch.optim.SGD([w, b], lr=0.001) optimizer.step()
(a) Why does z have a grad_fn while x does not? (b) What does loss.backward() do, and what does the printed shape show? (c) Has the value of w changed immediately after loss.backward()? Explain. (d) What does optimizer.step() do?
The following training loop contains one important omission:
for i, data in enumerate(trainloader, 0):
inputs, labels = data
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
(a) Which line is missing, and where should it be placed? (b) What goes wrong if it is missing? (c) State the correct order of the four steps of the training loop.
Consider the CIFAR-10 network defined below, used with an input batch of shape [16, 3, 32, 32]:
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
Give the tensor shape after each of these stages: (a) after conv1, (b) after the first pool, (c) after conv2, (d) after the second pool, (e) after view, (f) after fc3. Why must fc1 have 400 input features?
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
training_data = datasets.FashionMNIST(
root="data", train=True, download=True, transform=transform)
(a) What does ToTensor() do to the pixel values? (b) What does Normalize compute, and what is the resulting value range? (c) Why must ToTensor() be applied before Normalize? (d) What does train=True select?
import torch import numpy as np t = torch.ones(5) n = t.numpy() t.add_(2) print(t) print(n) n2 = np.ones(5) t2 = torch.from_numpy(n2) np.add(n2, 1, out=n2) print(t2)
(a) What are printed for t and n after t.add_(2)? (b) Why does n change? (c) What does print(t2) show, and why? (d) What does the trailing underscore in add_ mean?
Section 4 — Open Questions
Write clear, complete answers. Your answers are graded on correctness, completeness and understanding.
Explain why a plot of y = x² made from only the three points x = 0, 1, 2 does not look like the smooth parabola we expect, and describe exactly how Lab 2 fixed this problem (include the code idea used).
Explain the difference between loss.backward() and optimizer.step(). What does each one accomplish, where are gradients stored, and what would happen if you performed only one of them?
When do we use model.train(), model.eval() and torch.no_grad() during a training project, and why? What are the practical consequences of forgetting them?
What is data augmentation? Why is it needed when training a classifier, and what makes an augmentation "good" rather than harmful? Give one example of a harmful augmentation mentioned in the lab.
Describe the complete procedure used in Lab 9 to train and evaluate the CIFAR-10 classifier. Your answer should cover: data loading and normalization, the network definition, the loss function and optimizer, the per-batch training steps, how the model is saved and reloaded, and how the test accuracy is computed.
Explain how you determine the number of input features (in_features) of the first Linear layer that follows convolutional and pooling layers. Use the Lab 9 network with a 32×32 RGB input to justify why nn.Linear(16 * 5 * 5, 120) is correct, and give the formula used to compute the convolution output size.
Section 5 — Fill in the Blank
Fill each blank with the missing word, concept, function or parameter. Minor differences in capitalization or prefixes are accepted when grading.
In Jupyter Notebook, pressing evaluates the current cell and selects the cell below it.
After plotting with plt.plot(X, Y, color='r', label='quadratic'), calling plt.() makes those labels appear on the chart.
In NumPy, the attribute used to obtain the dimensions of an array is a. (not len(a)).
is PyTorch's engine for automatic differentiation; it computes gradients automatically for any computational graph.
One is one complete pass of the entire training dataset through the model.
transforms.Normalize computes, for each channel:
output[channel] = ( input[channel] - ______________ ) / ______________
Blank 1: Blank 2:
criterion = nn.__________________________() optimizer = optim.SGD(net.parameters(), lr=______________, momentum=0.9)
Blank 1: Blank 2:
transform_Gray = transforms.Compose([
transforms.____________________________(num_output_channels=1),
transforms.ToTensor(),
])
The missing transform (it converts the RGB image to a single-channel image) is:
# train_features[0] has shape (1, 28, 28) img = train_features[0].________________() # img now has shape (28, 28), ready for plt.imshow
The missing method (it removes the size-1 channel dimension) is:
optimizer.__________________() outputs = net(inputs) loss = criterion(outputs, labels) loss.__________________() optimizer.__________________()
Blank 1: Blank 2: Blank 3:
Before you leave
- Click Save Progress, then Export Answers (JSON) and keep the file.
- Your exam will be graded only after you submit the exported file (or paste its contents) when you ask for grading.
- This page does not show your score.