Deeplizard《Pytorch神经网络高效入门教程》第十集笔记

t = torch.tensor([
    [1,1,1,1],
    [2,2,2,2],
    [3,3,3,3]
], dtype=torch.float32)
我们可以用t.size() 和t.shape来查看张量t的形状
我们可以用len(t.shape)来看张量t的rank(阶,即这个张量拥有的基底向量的数量)
可以根据torch.tensor(t.shape).prod()或t.numel()获取张量的元素数量
改变张量的形状(reshape)
重塑不会改变基础数据,只是改变形状
1.不改变张量的rank的操作

import torch
t = torch.tensor([
    [1,1,1,1],
    [2,2,2,2],
    [3,3,3,3]
], dtype=torch.float32)
t.reshape(1,12)
t.reshape(2,6)
t.reshape(4,3)
t.reshape(6,2)
t.reshape(12,1)

上述操作没有改变张量的rank,形状中的分量值是t.numel()的因数
2.改变rank的操作
(1)改变形状中的分量值的个数

t.reshape(1,3,4)
t.reshape(2,2,3)
t.reshape(1,1,12)
t.reshape(12)

(2)squeeze与unsqueeze(压缩和解压)
squeeze函数一个张量可以移除所有长度为1的轴
unsqueeze函数会增加一个长度为1的维度

print(t.reshape(1,12).squeeze())
print(t.reshape(1,1,12).squeeze())
print(t.reshape(1,12).squeeze().unsqueeze(dim=0))
print(t.reshape(1,12).unsqueeze(dim=0))
print(t.reshape(1,12).unsqueeze(dim=0).shape)

3.通过flatten函数来压缩一个张量(使张量变为一维的张量)(rank=1)

def flatten(t):
	t = t.reshape(1,-1)   
 #在pytorch中,-1告诉reshape函数根据张量中包含的其他值和元素的个数求出值是多少
	t = t.squeeze()
    return t
#flatten函数也可写成:
#def flatten(t):
#	t = t.reshape(-1)或者t = t.reshape(1,-1)[0]或者t.view(t.numel())或t.flatten()

猜你喜欢

转载自blog.csdn.net/weixin_43227262/article/details/120420819
今日推荐