PyTorch Certified Associate (PTCA) free question 3 / 10 · Domain 1: PyTorch Fundamentals
x = torch.randn(4, 4) and z = x.view(-1, 8). What is z.size(), and how does z relate to x?
- torch.Size([2, 8]), and z shares its data with x
- torch.Size([1, 8]), and z shares its data with x
- It raises an error: -1 is not allowed as a size in view()
- torch.Size([2, 8]), and z is an independent copy of x
Show the answer and explanation
Answer: A
Why this is correct
view() returns a tensor with the same data and the same number of elements, in a different size. The tensor x has 16 elements. With a trailing size of 8, the size -1 is inferred from the other dimensions, giving 2 rows, so z.size() is torch.Size([2, 8]). Because it is a view, z and x share the same data, and the documentation's own example is this call.
Why the other options are wrong
"torch.Size([2, 8]), and z is an independent copy of x" … The size is right, but view() returns a tensor that shares the same data as the original, so it is not an independent copy.
"torch.Size([1, 8]), and z shares its data with x" … The view must have the same number of elements. Sixteen elements in rows of 8 give 2 rows, so the inferred -1 is 2, not 1.
"It raises an error: -1 is not allowed as a size in view()" … The page's example uses z = x.view(-1, 8) and states that the size -1 is inferred from other dimensions.
Key points
At most one dimension can be -1, and the product of the sizes must equal the number of elements.