查看大小
Tensor.shape
Tensor.size()
AttributeError: ‘list’ object has no attribute ‘shape’
len(list)
或
np.array(a).shape
或
print(list[0].shape)
view
if __name__ == '__main__':
x = torch.tensor([[1, 2,3,4],
[5, 6,7,8],
[9, 10,11,12],
[13, 14,15,16],]).unsqueeze(dim=0).unsqueeze(dim=0)
x = x.view(x.shape[0], x.shape[1]*4, int(x.shape[2]/2), int(x.shape[3]/2))
tensor([[[[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]]]])
tensor([[[[ 1, 2],
[ 3, 4]],
[[ 5, 6],
[ 7, 8]],
[[ 9, 10],
[11, 12]],
[[13, 14],
[15, 16]]]])
报错原因
tensor.view()方法可以调整tensor的形状,但必须保证调整前后元素总数一致
tensor.view()方法可以调整tensor的形状,
\\ \color{red}但必须保证调整前后元素总数一致
tensor.view()方法可以调整tensor的形状,但必须保证调整前后元素总数一致
view不会修改自身的数据,返回的新tensor与原tensor共享内存,即更改一个,另一个也随之改变。view不会修改自身的数据,返回的新tensor与原tensor共享内存,即更改一个,另一个也随之改变。view不会修改自身的数据,返回的新tensor与原tensor共享内存,即更改一个,另一个也随之改变。
X.view(X.shape[2:])# 在y的前两个维度不是1的情况下,是会报错的
其他错误
RuntimeError: view size is not compatible with input tensor’s size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(…) instead.
tensor不是contiguous 引起的错误。查看targets.is_contiguous()为False。
两种解决办法:1)按照提示使用reshape代替;2)将变量先转为contiguous ,再进行view:
x.contiguous().view(b,-1)
view VS permute

import torch
x = torch.randn(2, 3)
y = torch.permute(x, (1, 0))
print(x)
print(y)
tensor([[ 1.0945, -0.0853, -0.3914],
[-1.1281, -0.0633, -1.0864]])
tensor([[ 1.0945, -1.1281],
[-0.0853, -0.0633],
[-0.3914, -1.0864]])
torch.Size([3, 5, 2])
tensor([[[ 0.2059, -0.7165],
[-1.1305, 0.5886],
[-0.1247, -0.4969],
[-0.5788, 0.0159],
[ 1.4304, 0.6014]],
[[ 2.4882, -0.3910],
[-0.5558, 0.6903],
[-0.4219, -0.5498],
[-0.5346, -0.0703],
[ 1.1497, -0.3252]],
[[-0.5075, 0.5752],
[ 1.3738, -0.3321],
[-0.3317, -0.9209],
[-1.6677, -1.1471],
[-0.9269, -0.6493]]])
torch.Size([2, 3, 5])
tensor([[[ 0.2059, -1.1305, -0.1247, -0.5788, 1.4304],
[ 2.4882, -0.5558, -0.4219, -0.5346, 1.1497],
[-0.5075, 1.3738, -0.3317, -1.6677, -0.9269]],
[[-0.7165, 0.5886, -0.4969, 0.0159, 0.6014],
[-0.3910, 0.6903, -0.5498, -0.0703, -0.3252],
[ 0.5752, -0.3321, -0.9209, -1.1471, -0.6493]]])
[官方链接](https://pytorch.org/docs/stable/generated/torch.permute.html)
[添加链接描述](https://www.geeksforgeeks.org/python-pytorch-permute-method/#:~:text=PyTorch%20torch.permute%20%28%29%20rearranges%20the%20original%20tensor%20according,as%20that%20of%20the%20original.%20Syntax:%20torch.permute%20%28*dims%29)
更多:
[python:pytorch维度变换,爱因斯坦求和约定enisum,einops](https://blog.youkuaiyun.com/ResumeProject/article/details/121354010)
本文介绍了PyTorch中张量的view和permute方法。view用于调整张量形状,须确保元素总数不变,否则会引发错误。permute则重新排列张量的维度顺序。当张量不是contiguous时,使用view前需先转为contiguous。示例展示了这两个方法的用法及错误处理。
820

被折叠的 条评论
为什么被折叠?



