Tensor
Tensor-张量,是一种数据类型,基本上来说是多维array的别名,这里的“多维”可以是任何维数,也就是说1d-tensor → vector。
Tensor的通用属性 Rank,Axes and shape
Tensor的三个基本属性:Rank,Axes and shape。
**Rank:**维数,其大小恰好说明了需要多少个Index来取得Tensor里的一个数。
Axes: axis复数形式,shape=[batch,height,weight,channel],对应axes=[0,1,2,3]
shape: 等于size,张量的尺寸。reveals Rank and Axes.
t = torch.tensor([
[1,2,3],
[4,5,6],
[7,8,9]])
t.shape
out: torch.Size([3, 3])
Rank = len(t.shape)
Tensor在Pytorch中特有的属性 dtype, device, layout
t = torch.tensor
t.dtype:Tensor的内容的数据类型。Tensor的运算必须保证相同的dtype。
t.device:t所在的设备,关于t的运算将在此设备上进行。Tensor间进行运算时,运算中涉及的所有Tensor必须在同一个设备上。
t.layout:Tensor在内存中的存储方式。
reshape的简单介绍
reshape改变tensor的shape,语法类似numpy,注意元素数量要对应。
t.reshape(1,9)
out:tensor([[1,2,3,4,5,6,7,8,9]])
创建Tensor
1.从数据创建(将数据转为Tensor)
torch.Tensor(data)
,本质上是在调用Tensor类constructor,输入int数据会返回float类型,其原因是dtype的默认值是float32
torch.get_default_dtype() -> torch.float32
torch.tensor(data)
,本质上是在调用一个factory function函数,这个函数返回object,通常factoryfunction相比constructor有更好的文档支持和参数,输出dtype与输入dtype一致(type infer)。factoryfunction也可以指定dtype:torch.tensor(data, dtype2)
torch.as_tensor(data)
torch.from_numpy(data)
那三个factory function之间有什么差别呢?
share data:数据指针相同,即共享存储器中某处的数据。使用这种方法相对需要使用者有数据内存共享的相关知识储备,以防bug。
copy data:复制数据。
这么多选择,到底用哪个呢?
这取决于具体需求,但是通常情况下,用torch.tensor()
就好。调参时,用torch.as_tensor
2.无数据创建
- torch.eye(2) 2x2单位矩阵
- torch.zeros(2,2) 2x2,元素为0
- torch.ones(2,2) 2x2,元素为1
- torch.rand(2,2) 2x2,元素rand
卷积神经网络中的典型Tensor Shape
举个栗子:[31,1,28,28]
分别对应:[B,C,H,W]-[batch, channel, height, width]-[batch的样本数,图像通道数,图像高度,图像宽度]