tensor数据类型,对于dim=0和dim=1是不一样的;
维度为0的数据,一般称为标量,如loss值;
维度为1的数据,一般称为向量,如feature维度;
tensor shape,view和size的区别
tensor.shape和tensor.size()是一样表示tensor形状(不同维度对应数量);
tensor.dim()可显示tensor维度;
random创建,需灵活掌握各种类型random;random_like(a)比较方便;
torch.empty,作为容器,值比较特殊需要及时覆盖;
torch.Tensor和torch.tensor,均能生成tensor,tensor直接输入具体值,Tensor输入shape,避免混淆;
torch.ones,torch.zeros,torch.empty,torch.eye()都能快速组成简单数据;
直接切片,对于张量有:
a = torch.rand(4, 3, 224, 224) a[0].shape = (3, 224, 224) a[0, 0].shape = (224, 224) a[0, 0, 1, 1].shape = 0 索引选择范围 多维度分别选取即可,[start:end] 索引间隔 [start:end:range] 指定索引 a.index_select(0, 2) shape[2, 3, 224, 224] index_select 第一个参数表示某一维度,第二个参数表示索引范围; 特殊符号[...] 进行自动推测;根据已知的维度推测剩余维度选择范围;主要是书写和理解方便,具体情况需推测; 掩码选择 select by mask a.masked_select(value) 对于大于等于给定值,mask变为1,小于则为0; x = torch.randn(3, 4) mask = x.ge(0.5) value = torch.masked_select(x, mask) print(value.shape)维度变化
view/reshape(功能一致) pytorch更高版本常用reshape,和numpy保持一致; a = torch.rand(4, 1, 28, 28) a.view(4, 28*28) [原来的存储方式十分重要,要注意] squeeze/unsqueeze(挤压,扩展) a.unsqueeze(0).shape a.squeeze(1).shape 取值范围[-a.dim()-1, a.dim()+1) a.squeeze() 当不注明维度,表示将数值为1的维度全部消除; transpose/permute a.t() 使用transpose只能使用2D tensor,有局限性;使用contiguous()将打乱的数据变得连续; 注意:使用transpose转置,一定要注意维度转换的问题,出现错误容易导致数据污染,和元数据不一致,后面容易报错; 使用permute可以使用任意维度;要换哪个维度直接换位置序列号[0,1,2,3] -> [0, 3, 2, 1],调换第一维度和第三维度置换,也需要使用contiguous保持内存一致; a.shape [4, 3, 32, 32] expand/repeat expand: broadcasting 广播操作,占用内存少 repeat: memory copied 占用内存较大 a = torch.rand(4, 32, 14, 14) b.shape [1, 32, 1, 1] b.expand(4, 32, 14, 14)扩展为和a一致,维度不变用(-1)代替 repeat其中参数和expand不一致,repeat(4, 32, 1, 1)参数表示拷贝次数而不是重复的维度; 想得到(4, 32, 14, 14)应该用b.repeat(4, 1, 14, 14)



