不同类型进行转换
1.1 张量的数据类型
i = torch.tensor(1);
print(i,i.dtype)
x = i.float();
print(x,x.dtype) #调用 float方法转换成浮点类型
y = i.type(torch.float);
print(y,y.dtype) #使用type函数转换成浮点类型
z = i.type_as(x);
print(z,z.dtype) #使用type_as方法转换成某个Tensor相同类型
tensor(1) torch.int64
tensor(1.) torch.float32
tensor(1.) torch.float32
tensor(1.) torch.float32
1.2 张量的维度
不同类型的数据可以用不同维度(dimension)的张量来表示。
标量为0维张量,向量为1维张量,矩阵为2维张量。
彩色图像有rgb三个通道,可以表示为3维张量。
视频还有时间维,可以表示为4维张量。
可以简单地总结为:有几层中括号,就是多少维的张量。
scalar = torch.tensor(True)
print(scalar)
print(scalar.dim()) # 标量,0维张量
tensor(True)
0
vector = torch.tensor([1.0,2.0,3.0,4.0]) #向量,1维张量
print(vector)
print(vector.dim())
tensor([1., 2., 3., 4.])
1
matrix = torch.tensor([[1.0,2.0],[3.0,4.0]]) #矩阵, 2维张量
print(matrix)
print(matrix.dim())
tensor([[1., 2.],
[3., 4.]])
2
tensor3 = torch.tensor([[[1.0,2.0],[3.0,4.0]],[[5.0,6.0],[7.0,8.0]]]) # 3维张量
print(tensor3)
print(tensor3.dim())
tensor([[[1., 2.],
[3., 4.]],
[[5., 6.],
[7., 8.]]])
3
1.3 张量的尺寸
可以使用 shape属性或者 size()方法查看张量在每一维的长度.
可以使用view方法改变张量的尺寸。
如果view方法改变尺寸失败,可以使用reshape方法.
scalar = torch.tensor(True)
vector = torch.tensor([1.0,2.0,3.0,4.0])
print(vector.size())
print(vector.shape)
torch.Size([])
torch.Size([4])
matrix = torch.tensor([[1.0,2.0],[3.0,4.0]])
print(matrix.size())
torch.Size([2, 2])
# 使用view可以改变张量尺寸
vector = torch.arange(0,12)
print(vector)
print(vector.shape)
matrix34 = vector.view(3,4)
print(matrix34)
print(matrix34.shape)
matrix43 = vector.view(4,-1) #-1表示该位置长度由程序自动推断
print(matrix43)
print(matrix43.shape)
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
torch.Size([12])
tensor([[ 0, 1, 2, 3],