pytorch不同类型进行转换

本文详细介绍了PyTorch中张量的数据类型、维度、尺寸转换以及与numpy数组之间的相互转换。通过示例展示了如何查看和改变张量的尺寸,并强调了张量与numpy数组共享内存的特点。
摘要由CSDN通过智能技术生成

不同类型进行转换

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],

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值