torch.Tensor.view¶
- Tensor.view(*shape) Tensor ¶
返回一个新张量,其数据与
self
张量相同,但具有不同的形状
。返回的张量共享相同的数据,并且必须具有相同的元素数量,但可以具有不同的大小。对于可被 view 的张量,新的 view 大小必须与其原始大小和跨度兼容,即每个新的 view 维度必须要么是原始维度的一个子空间,要么仅跨越满足以下类似连续性条件的原始维度 :即对于 ,
否则,无法在不复制(例如,通过调用
contiguous()
)的情况下将self
张量 view 为shape
。当不确定是否可以执行view()
时,建议使用reshape()
,如果形状兼容,它会返回一个 view,否则会进行复制(相当于调用contiguous()
)。- 参数
shape (torch.Size 或 int...) – 期望的尺寸
示例
>>> x = torch.randn(4, 4) >>> x.size() torch.Size([4, 4]) >>> y = x.view(16) >>> y.size() torch.Size([16]) >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions >>> z.size() torch.Size([2, 8]) >>> a = torch.randn(1, 2, 3, 4) >>> a.size() torch.Size([1, 2, 3, 4]) >>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension >>> b.size() torch.Size([1, 3, 2, 4]) >>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory >>> c.size() torch.Size([1, 3, 2, 4]) >>> torch.equal(b, c) False
- view(dtype) Tensor
返回一个新张量,其数据与
self
张量相同,但具有不同的dtype
。如果
dtype
的元素大小与self.dtype
不同,则输出的最后一个维度的尺寸将按比例缩放。例如,如果dtype
的元素大小是self.dtype
的两倍,则self
最后一个维度中的每对元素将被组合,输出的最后一个维度的尺寸将是self
的一半。如果dtype
的元素大小是self.dtype
的一半,则self
最后一个维度中的每个元素将被分成两部分,输出的最后一个维度的尺寸将是self
的两倍。为了实现这一点,必须满足以下条件:self.dim()
必须大于 0。self.stride(-1)
必须为 1。
此外,如果
dtype
的元素大小大于self.dtype
的元素大小,还必须满足以下条件:self.size(-1)
必须能被 dtypes 元素大小之比整除。self.storage_offset()
必须能被 dtypes 元素大小之比整除。除了最后一个维度外,所有维度的跨度必须能被 dtypes 元素大小之比整除。
如果上述任一条件未满足,则会抛出错误。
警告
此重载不受 TorchScript 支持,在 TorchScript 程序中使用它将导致未定义行为。
- 参数
dtype (
torch.dtype
) – 期望的数据类型
示例
>>> x = torch.randn(4, 4) >>> x tensor([[ 0.9482, -0.0310, 1.4999, -0.5316], [-0.1520, 0.7472, 0.5617, -0.8649], [-2.4724, -0.0334, -0.2976, -0.8499], [-0.2109, 1.9913, -0.9607, -0.6123]]) >>> x.dtype torch.float32 >>> y = x.view(torch.int32) >>> y tensor([[ 1064483442, -1124191867, 1069546515, -1089989247], [-1105482831, 1061112040, 1057999968, -1084397505], [-1071760287, -1123489973, -1097310419, -1084649136], [-1101533110, 1073668768, -1082790149, -1088634448]], dtype=torch.int32) >>> y[0, 0] = 1000000000 >>> x tensor([[ 0.0047, -0.0310, 1.4999, -0.5316], [-0.1520, 0.7472, 0.5617, -0.8649], [-2.4724, -0.0334, -0.2976, -0.8499], [-0.2109, 1.9913, -0.9607, -0.6123]]) >>> x.view(torch.cfloat) tensor([[ 0.0047-0.0310j, 1.4999-0.5316j], [-0.1520+0.7472j, 0.5617-0.8649j], [-2.4724-0.0334j, -0.2976-0.8499j], [-0.2109+1.9913j, -0.9607-0.6123j]]) >>> x.view(torch.cfloat).size() torch.Size([4, 2]) >>> x.view(torch.uint8) tensor([[ 0, 202, 154, 59, 182, 243, 253, 188, 185, 252, 191, 63, 240, 22, 8, 191], [227, 165, 27, 190, 128, 72, 63, 63, 146, 203, 15, 63, 22, 106, 93, 191], [205, 59, 30, 192, 112, 206, 8, 189, 7, 95, 152, 190, 12, 147, 89, 191], [ 43, 246, 87, 190, 235, 226, 254, 63, 111, 240, 117, 191, 177, 191, 28, 191]], dtype=torch.uint8) >>> x.view(torch.uint8).size() torch.Size([4, 16])