Tensor
python | PyTorch |
Int | IntTensor of size() |
float | FloatTensor of size() |
Int array | IntTensor of size [d1, d2 ,…] |
Float array | FloatTensor of size [d1, d2, …] |
string | --- |
pytorch中字符串数据类型是用编码来代替的
pytorch内键的数据类型
检查变量a的类型
a.type() 返回Tensor数据类型,如torch.FloatTensor
type(a) 返回基本数据类型,如torch.Tensor
isinstance(a, torch.FloatTensor) 返回True or False
x与x.cuda的数据类型不同,后者属于GPU Tensor的类型
1.标量Dimension为0的数据类型,常用来计算loss
a = torch.tensor(1.3)
a.shape => torch.Size([ ])
len(a.shape) => 0
a.size => torch.Size([ ])
2.Dimension为1的张量带一个"[ ]",常用于bias和神经网络线性层的输入
torch.tensor([1.1]) => tensor([1.1000])
torch.tensor([1.1,2.2]) => tensor([1.1000,2.2000])
输出一个dimens为1,size长度为1的张量torch.FloatTensor(1) => tensor([3.2239e-25])
输出一个dimens为1,size长度为2的张量torch.FloatTensor(2) => tensor([3.2239e-25,4.5915-41])
从numpy引入:
data.shape() => torch.size([2])
dimension是size的长度,size/shape指张量的形状,tensor指一个具体的张量
3.Dimension为2的张量带2个"[ ]",常用于带有batch的线性输入
随机生成一个2行3列的2维张量 a=torch.randn(2,3) =>
tensor([[-0.4423,0.5983,1.2390],
[-2.3440,0.2344,1.9372]])
a.shape => torch.Size([2,3])
a.size(0) => 2
a.size(1) => 3
a.shape[1] => 3
4.Dimension为3的张量带3个"[ ]",常用于RNN网络结构输入batch(处理文字)
随机均匀生成一个[0,1]的3维张量 a=torch.rand(1,2,3) =>
tensor([[[0.0763,0.2570,0.9831],
[0.6832,0.1549,0.7923]]])
a.shape => torch.Size([1,2,3])
取a第0个元素返回[2,3]
tensor([[0.0763,0.2570,0.9831],
[0.6832,0.1549,0.7923]])
5.Dimension为4的张量带4个"[ ]",常用于卷积神经网络CNN[b,c,h,w](处理图片)
b:batch表示照片数量;c:channel为图片通道,=1时是灰度图片,=3时时彩色图片;h:height为图片的长;w:width为图片的宽
a.shape => torch.Size([2,3,28,28])
a.numel() => 4704 计算张量所占内存大小2*3*28*28=4704
a.dim() => 4