标签:不为 方式 range and erro exp randn Dimension 如何
数据本身不发生改变,数据的访问方式发生了改变
函数:unsqueeze()
# a是一个4维的
a = torch.randn(4, 3, 28, 28)
print(‘a.shape\n‘, a.shape)
print(‘\n维度扩展(变成5维的):‘)
print(‘第0维前加1维‘)
print(a.unsqueeze(0).shape)
print(‘第4维前加1维‘)
print(a.unsqueeze(4).shape)
print(‘在-1维前加1维‘)
print(a.unsqueeze(-1).shape)
print(‘在-4维前加1维‘)
print(a.unsqueeze(-4).shape)
print(‘在-5维前加1维‘)
print(a.unsqueeze(-5).shape)
a.shape
torch.Size([4, 3, 28, 28])
维度扩展(变成5维的):
第0维前加1维
torch.Size([1, 4, 3, 28, 28])
第4维前加1维
torch.Size([4, 3, 28, 28, 1])
在-1维前加1维
torch.Size([4, 3, 28, 28, 1])
在-4维前加1维
torch.Size([4, 1, 3, 28, 28])
在-5维前加1维
torch.Size([1, 4, 3, 28, 28])
注意,第5维前加1维,就会出错
# print(a.unsqueeze(5).shape)
# Errot:Dimension out of range (expected to be in range of -5, 4], but got 5)
函数:unsqueeze()
# b是一个1维的
b = torch.tensor([1.2, 2.3])
print(‘b.shape\n‘, b.shape)
print()
# 0维之前插入1维,变成1,2]
print(b.unsqueeze(0))
print()
# 1维之前插入1维,变成2,1]
print(b.unsqueeze(1))
# 连续扩维,然后再对某个维度进行扩张
print(b.unsqueeze(1).unsqueeze(2).unsqueeze(0).shape)
b.shape
torch.Size([2])
tensor([[1.2000, 2.3000]])
tensor([[1.2000],
[2.3000]])
torch.Size([1, 2, 1, 1])
函数:squeeze()
# 挤压维度,只会挤压shape为1的维度,如果shape不是1的话,当前值就不会变
c = torch.randn(1, 32, 1, 2)
print(c.shape)
print(c.squeeze(0).shape)
print(c.squeeze(1).shape) # shape不是1,不会变
print(c.squeeze(2).shape)
print(c.squeeze(3).shape) # shape不是1,不会变
torch.Size([1, 32, 1, 2])
torch.Size([32, 1, 2])
torch.Size([1, 32, 1, 2])
torch.Size([1, 32, 2])
torch.Size([1, 32, 1, 2])
函数1:expand():扩张到多少,
# shape的扩张
# expand():对shape为1的进行扩展,对shape不为1的只能保持不变,因为不知道如何变换,会报错
d = torch.randn(1, 32, 1, 1)
print(d.shape)
print(d.expand(4, 32, 14, 14).shape)
torch.Size([1, 32, 1, 1])
torch.Size([4, 32, 14, 14])
函数2:repeat()方法,扩张多少倍
d=torch.randn([1,32,4,5])
print(d.shape)
print(d.repeat(4,32,2,3).shape)
torch.Size([1, 32, 4, 5])
torch.Size([4, 1024, 8, 15])
标签:不为 方式 range and erro exp randn Dimension 如何
原文地址:https://www.cnblogs.com/52dxer/p/13771279.html