Common tensor operations
1. the tensor. View method can be used to adjust the tensor shape, but the total number of elements before and after the adjustment must be consistent. View does not modify its own data, and returns a new tensor shared memory with the original tensor, that is, change one of them, and the other will change accordingly. 2. In practice, you often need to add or remove a dimension. The squeeze and unsqueeze functions are available. Import torch as Ta = T. arange (0, 6) B =. view (2, 3) # adjust the tensor shape without modifying its own data c =. view (-1, 3) #-1 automatically calculates the size of ''' A = tensor ([0, 1, 2, 3, 4, 5]) B = tensor ([0, 1, 2], [3, 4, 5]) C = tensor ([0, 1, 2], [3, 4, 5]) ''' B = B. unsqueeze (1) # Add "1" '''tensor ([[0, 1, 2], [[3, 4, 5]) '''c = C. unsqueeze (-2) ''' tensor ([[0, 1, 2], [3, 4, 5]) ''' d = B. view (, 3) ''' tensor ([[[0, 1, 2], [3, 4, 5]) ''' D = D. squeeze (0) # compress the 0th-dimension "1" ''' tensor ([[0, 1, 2], [3, 4, 5]) '''d = D. squeeze () # compress '''tensor ([0, 1, 2], [3, 4, 5]) where all dimensions are "1". '''3. Resize is another method that can be used to adjust the size. However, unlike view, it can modify the tensor size. If the new size exceeds the original size, a new memory space is automatically allocated. If the new size is smaller than the original size, the previous data is still saved. B. resize _ () # resize _ adjust the size. If the new size is smaller than the original size, '''tensor ([[0, 1, 2]) ''' is retained. resize _ (3, 3) # resize _ adjust the size. If the new size is greater than the original size, a new memory space '''tensor ([0, 1, 2], [3, 4, 5], [7526747973031060338,730 6812055932138085, 8389969046800051066]) '''
17:59:12
Common tensor operations