Common tensor operations

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.