oneflow.Tensor.view¶
-
Tensor.
view
()¶ Returns a new tensor with the same data as the
self
tensor but of a differentshape
.The returned tensor shares the same data and must have the same number of elements, but may have a different size. For a tensor to be viewed, the new view size must be compatible with its original size and stride, i.e., each new view dimension must either be a subspace of an original dimension, or only span across original dimensions \(d, d+1, \dots, d+k\) that satisfy the following contiguity-like condition that \(\forall i = d, \dots, d+k-1\),
\[\text{stride}[i] = \text{stride}[i+1] \times \text{size}[i+1]\]Otherwise, it will not be possible to view
self
tensor asshape
without copying it (e.g., viacontiguous()
). When it is unclear whether aview()
can be performed, it is advisable to usereshape()
, which returns a view if the shapes are compatible, and copies (equivalent to callingcontiguous()
) otherwise.The interface is consistent with PyTorch. The documentation is referenced from: https://pytorch.org/docs/1.10/generated/torch.Tensor.view.html.
- Parameters
input – A Tensor.
*shape – flow.Size or int…
- Returns
A Tensor has the same type as input.
For example:
>>> import numpy as np >>> import oneflow as flow >>> x = np.array( ... [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] ... ).astype(np.float32) >>> input = flow.Tensor(x) >>> y = input.view(2, 2, 2, -1).numpy().shape >>> y (2, 2, 2, 2)