A view is a tensor that shares underlying storage with another tensor but can present the data with a different shape or indexing layout. Creating a view can be inexpensive because the data does not need to be copied. section 3.9.1 section 4.4.2
A tensor’s size, storage offset, and stride describe how it indexes storage. The offset identifies where indexing starts; each stride says how many storage elements to skip when an index increases by one. Indexing a row can produce a smaller tensor that still uses the original storage. section 3.9.1
# In[28]:
points = torch.tensor([[4.0, 1.0], [5.0, 3.0], [2.0, 1.0]])
second_point = points[1]
second_point[0] = 10.0
points
# Out[28]:
tensor([[ 4., 1.],
[10., 3.],
[ 2., 1.]])
Changing the indexed row also changes the original tensor because they share storage. Use points[1].clone() instead when the new tensor needs its own storage. section 3.9.1
The view method provides a new shape for the same data. One dimension can be specified as -1, letting PyTorch infer its size from the remaining dimensions and the number of elements. section 4.4.2
# In[4]: daily_bikes = bikes.view(-1, 24, bikes.shape[1]) daily_bikes.shape, daily_bikes.stride() # Out[4]: (torch.Size([730, 24, 17]), (408, 17, 1))
Hourly bike data changes from 17,520 rows of 17 columns into 730 days of 24 hours, with 17 columns per hour. The new strides describe the same storage using the three-dimensional shape. section 4.4.2
A view can also prepare features for a network’s linear layer. For example, out.view(-1, 8 * 8 * 8) turns each pooled 8-channel, 8-by-8 output into a 512-element vector while inferring the batch size. section 8.2.4 section 8.3.1
A requested view may not work with a noncontiguous layout. In that case, contiguous() can create a tensor with rearranged storage; if the tensor is already contiguous, the call does nothing. section 3.9.4





