2022-03-09 Pytorch:tensor数据类型与创建、初始化tensor

文章目录

      • 1.1 数据类型
      • 1.2 标量
      • 1.3 向量(张量)
        • 1.3.1 一维和二维张量
        • 1.3.2 三维张量 [c, h, w]
        • 1.3.3 四维张量 [b, c, h, w]
        • 1.4 初始化

1.1 数据类型

torch.IntTensor (32位)
torch.LongTensor (64位)
torch.ShortTensor (16位)
torch.FloatTensor (32位)
torch.DoubleTensor (64位)
torch.ByteTensor (8位)
以上是CPU的类型,GPU则直接在torch后面加cuda(如torch.cuda.IntTensor)torch.cuda.IntTensor

import torch

a = torch.randn(2,3)#建立一个2行3列的tensor
print('a.type:',a.type())#type函数返回数据类型
print('type(a):',type(a)) #type方法返回基本信息
print("合法化检验:", isinstance(a,torch.FloatTensor))

print("合法化检验:", isinstance(a,torch.cuda.FloatTensor))
a = a.cuda()
print("变为gpu类型后,检验:", isinstance(a,torch.cuda.FloatTensor))

结果:

a.type: torch.FloatTensor
type(a): <class 'torch.Tensor'>
合法化检验: True
合法化检验: False
合法化检验: True

1.2 标量

b = torch.tensor(1.1) #定义维度为0的tensor
print('b.shape:',b.shape) #查看shape,其实看不出来啥,需要加个len()
print('len(b.shape):',len(b.shape))#返回维度0

结果:

b.shape: torch.Size([]) 
len(b.shape): 0

1.3 向量(张量)

1.3.1 一维和二维张量

创建:

c = torch.tensor([1.1]) #定义一维张量
d = torch.tensor([1.1,1.2])  #定义二维张量
c = torch.FloatTensor(1) #创建随机一维浮点型张量
print('torch.FloatTensor(1) :', c)
d = torch.FloatTensor(2) #创建随机二维浮点型张量
print('torch.FloatTensor(2) :', d)
#通过numpy创建张量
data  = np.ones(2)
print('numpy的array:',data)
torch.from_numpy(data)#torch.from_numpy()
print('torch.from_numpy():',data)

结果:

torch.FloatTensor(1) : tensor([1.4013e-45])
torch.FloatTensor(2) : tensor([-5.0074e-32,  0.0000e+00])
numpy的array: [1. 1.]
torch.from_numpy(): [1. 1.]

查看shape和维度:
torch.randn(2,3) 随机正态分布
torch.rand(2,3) 随机均匀分布

a = torch.randn(2,3)#建立一个2行3列的tensor
print(a)
print('a.shape:',a.shape)
print('a.size(0):',a.size(0))
print('a.size(1):',a.size(1))
print('a.shape[1]:',a.shape[1])#a.shape类似一个列表,是可以索引的
print('通过shape得到tensor的维度:', len(a.shape))
print('直接得到tensor的维度:',len(a))

结果:

tensor([[ 1.4009, -0.2866,  1.3271],
        [-1.5811,  0.9274, -0.5796]])
a.shape: torch.Size([2, 3])
a.size(0): 2
a.size(1): 3
a.shape[1]: 3
通过shape得到tensor的维度: 2
直接得到tensor的维度: 2

1.3.2 三维张量 [c, h, w]

torch.rand(1,3,3),顺序依次是channel, 行,列

a_3 = torch.rand(1,3,3)#创建一个三维张量
print(a_3)
print('a_3.shape:',a_3.shape)
print('a_3[0],取a_3的第1个维度的第0个元素:\n',a_3[0])
shape_l = list(a_3.shape)#为了更好地与numpy交互,将shape转为真正的list
print('转为list的shape',shape_l)

结果:
2022-03-09 Pytorch:tensor数据类型与创建、初始化tensor_第1张图片

1.3.3 四维张量 [b, c, h, w]

torch.rand(2,3,,28,28),顺序依次是 个数,channel, 行,列
有2张图片,每个图片是3个通道(RGB),每个通道是28×28的大小

a_4 = torch.rand(1,3,2,2)
print('a_4.shape:', a_4.shape)
print('a_4.numel():', a_4.numel())#number of elements占内存的大小
print("a_4.dim():", a_4.dim())#维度,or len(a_4.shape)

结果:

a_4.shape: torch.Size([1, 3, 2, 2])
a_4.numel(): 12
a_4.dim(): 4

1.3 创建张量

#直接由array转
a = np.array([1,2,3])
a = torch.from_numpy(a)
print('a:\n', a)

#生成1构成的array,再转
a = np.ones([2,3])
a = torch.from_numpy(a)
print('ones:\n', a)

#由list导入,数据少,不需要numpy作为载体
a = torch.tensor([1,2.2,3])#小写的tensor只接收现成数据
print('小写tensor:\n', a)
a = torch.Tensor(2,3)#大写的可以接收数据和shape,但是最好只用shape
print('大写Tensor:\n', a)
a = torch.FloatTensor(2,3)
print('大写FloatTensor,与Tensor一样:\n', a)

结果:

a:
 tensor([1, 2, 3], dtype=torch.int32)
ones:
 tensor([[1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)
小写tensor:
 tensor([1.0000, 2.2000, 3.0000])
大写Tensor:
 tensor([[0., 0., 0.],
        [0., 0., 0.]])
大写FloatTensor,与Tensor一样:
 tensor([[0., 0., 0.],
        [0., 0., 0.]])

1.4 初始化

a = torch.rand(3,3):采样在[0,1]之间
b = torch.rand_like(a):

##采样在[0,1]之间的3*3的tensor
a = torch.rand(3,3)
b = torch.rand_like(a)  #将a的shape读出来喂给torch.rand()
c = torch.randint(1,10,[3,3])#限制value的数值
print('randint(1,10,[3,3]):\n', c)

###均值为0,方差为1
d = torch.randn(3,3)
print('均值为0,方差为1:',d)
#自定义分布,采用normal函数

###全部赋值为一个元素
e = torch.full([2,3],8)
print('全部赋值为8\n',e)
e = torch.full([],8)
print('0维全部赋值为8\n',e)

###设置范围arange
f = torch.arange(0,10)#不建议使用range(),记得用arange()
print('0到10:\n',f)
f = torch.arange(0,10,2)#第三个参数是间隔
print('0到10,以2为间隔:\n',f)

###等分
f = torch.linspace(0,10,steps = 4)#第三个参数是等分的数量
print('0到10,等分为4个数:\n',f)
f = torch.logspace(0, -1, steps=10)#10的多少次方
print('10的x次方,x为0到10等分:\n',f)

###全0
f = torch.ones(2,3)
###全1
f = torch.zeros(2,3)
###单位矩阵.可以不是对角矩阵
f = torch.eye(2,3)

shuffle:

###随机打散
#假如a,b里存的是2个人的各科成绩
a = torch.rand(2,3)
b = torch.rand(2,2)
print('未改变顺序的a:\n',a)
idx = torch.randperm(2)#shuffle一维索引
print('shuffle第1次:',idx)
idx = torch.randperm(2)
print('shuffle第2次:',idx)
#a和b的索引得一致,才能让人不变
print('将idx给a作索引:\n',a[idx])
print('将idx给b作索引:\n',b[idx])

结果:

未改变顺序的a:
 tensor([[0.9132, 0.7129, 0.6979],
        [0.3145, 0.7523, 0.4238]])
shuffle第1次: tensor([0, 1])
shuffle第2次: tensor([1, 0])
将idx给a作索引:
 tensor([[0.3145, 0.7523, 0.4238],
        [0.9132, 0.7129, 0.6979]])
将idx给b作索引:
 tensor([[0.9509, 0.1228],
        [0.2892, 0.0747]])

你可能感兴趣的:(深度学习笔记,pytorch,深度学习,python)