1.reshape
使用方法:张量名.reshape(n1,n2,...,n3,n4)
n的意义为该维度下元素的个数。括号内从左至右是1维,2维,至更高维度。
作用:改变张量形状,张量大小不变。即抽出所有元素进行重新排版输出。
自动将 任意维度 转换成 指定维度 ,按照 指定维度下的元素个数 输出,如下:
x=torch.tensor([[[[2,3],[4,5]],[[6,7],[8,9]]],[[[2,3],[4,5]],[[6,7],[8,9]]]])
print(x.reshape(4,-1))
print(x.reshape(2,2,-1))
结果输出为:
tensor([[2, 3, 4, 5],
[6, 7, 8, 9],
[2, 3, 4, 5],
[6, 7, 8, 9]])
tensor([[[2, 3, 4, 5],
[6, 7, 8, 9]],
[[2, 3, 4, 5],
[6, 7, 8, 9]]])
且当元素个数不够分配时会报错,如下:
x=torch.tensor([[[[2,3],[4,5]],[[6,7],[8,9]]],[[[2,3],[4,5]],[[6,7],[8,9]]]])
print(x.reshape(3,-1))
print(x.reshape(3,-1))
^^^^^^^^^^^^^^^
RuntimeError: shape '[3, -1]' is invalid for input of size 16
2.torch.arange()
torch.arange(x) 生成一个行向量,这个行向量包含从0开始的前x个整数,如下:
x=torch.arange(10)
print(x)
输出结果:
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
3..numel()
张量名.numel() 输出张量内元素个数
4.torch ones和zeros
ones创建的张量所有元素为1,zeros创建的张量所有元素为0。其余用法相同
torch.ones(定义张量的形状和大小) , 如下:
x=torch.ones(2,3,4)
print(x)
输出为:
tensor([[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]],
[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]]])