2021-07-16 Pytorch的基本用法

一、新建张量

1、新建常量

#常量
a = torch.tensor(1.)
print(a)
print(a.size())
tensor(1.)
torch.Size([])

2、创建一维,二维,多维的张量

#创建一维张量,即vector
b = torch.FloatTensor(1)
print(b)
print(b.size())
#亦或
data = np.ones(2)
print("numpy:",data)
data1 = torch.from_numpy(data)  #import from numpy
print("torch:",data1)
#亦或
data3 = torch.randn(1)
print("dim1:",data3)

#dim=2
data2 = torch.randn(2,3)
print("dim2:",data2)

#dim3(适用于NLP)
data4 = torch.randn(2,2,2)
print("dim3:",data4)

#dim4(适用于image)
data5 = torch.randn(1,3,28,28)
print("dim4:",data5)
tensor([4500.3516])
torch.Size([1])
numpy: [1. 1.]
torch: tensor([1., 1.], dtype=torch.float64)
dim1: tensor([0.9116])
dim2: tensor([[ 0.0962,  1.1507, -0.0616],
        [ 0.0536,  0.8998, -0.6768]])
dim3: tensor([[[-2.2403e+00,  6.7108e-01],
         [-5.5247e-01,  4.8007e-04]],

        [[ 1.7094e+00, -1.7289e-01],
         [-1.7839e+00,  1.9703e+00]]])

3、对矩阵的初始化

#初始化矩阵
data6 = torch.rand(3,3) #在0到1之间分布
print("0-1初始化:",data6)
data7 = 10*torch.rand(2,2)  #在0到10之间分布
print(data7)
data8 = torch.randint(0,10,[3,3])  #如果需要用int变量初始化需给出最小值和最大值
print(data8)
data9 = torch.full([2,3],7,dtype=float) #利用full函数填充矩阵
print(data9)
#常规矩阵生成
print(torch.zeros(3,3))  #全零矩阵
print(torch.ones(3,3))  #全一矩阵
print(torch.eye(3))  #单位矩阵
0-1初始化: tensor([[0.9706, 0.1778, 0.1911],
        [0.4616, 0.0061, 0.3414],
        [0.4977, 0.6467, 0.5585]])
tensor([[2.0732, 8.4920],
        [9.1237, 3.8154]])
tensor([[9, 2, 4],
        [9, 8, 0],
        [1, 8, 7]])
tensor([[7., 7., 7.],
        [7., 7., 7.]], dtype=torch.float64)
tensor([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])
tensor([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])

4、创建等差数列

x = torch.arange(0,10) #此为整型数据
print(x)
xx = torch.range(0,10)
print(xx)
array0 = torch.arange(0,10,2)
print(array0)
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
tensor([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])
tensor([0, 2, 4, 6, 8])

5、范围内等分

array1 = torch.linspace(0,6,5)
print(array1)
array2 = torch.logspace(0,-2,10)  #此logspace函数:0:10^0;-2:10^-2
print(array2)
tensor([0.0000, 1.5000, 3.0000, 4.5000, 6.0000])
tensor([1.0000, 0.5995, 0.3594, 0.2154, 0.1292, 0.0774, 0.0464, 0.0278, 0.0167,
        0.0100])

6、将数据随机打散

#随机打散函数
m = torch.rand(4,2)
print("打散前:",m)
index = torch.randperm(4)  #打散索引
print("打散索引:",index)
print("打散后:",m[index])
打散前: tensor([[0.2266, 0.8468],
        [0.8041, 0.3267],
        [0.1047, 0.4745],
        [0.8006, 0.9312]])
打散索引: tensor([3, 2, 0, 1])
打散后: tensor([[0.8006, 0.9312],
        [0.1047, 0.4745],
        [0.2266, 0.8468],
        [0.8041, 0.3267]])

二、索引和切片

#全局例子
eg = torch.rand(4,3,28,28)

1、索引的多种语法

#索引
print(eg[0].shape)
print(eg[0,0].shape)
print(eg[0,0,1,2])
#高级索引
print(eg[:2].shape)
print(eg[:,:1,:14,:].shape)
print(eg[:2,...,::2].shape)
#直接选取
print(eg.index_select(0,torch.tensor([0,2])).shape)
print(eg.index_select(3,torch.arange(8)).shape)
torch.Size([3, 28, 28])
torch.Size([28, 28])
tensor(0.3493)
torch.Size([2, 3, 28, 28])
torch.Size([4, 1, 14, 28])
torch.Size([2, 3, 28, 14])
torch.Size([2, 3, 28, 28])
torch.Size([4, 3, 28, 8])

2、矩阵的变换

#1.view||reshape
print("变换:",eg.view(4,3,28*28).shape) #将每幅图打平

#2.squeeze||unsqueeze挤压和展开维度
print("增加:",eg.unsqueeze(0).shape)
eg1 = torch.rand(1,3,28,28)
print("删减:",eg1.squeeze(0).shape)

#3.expand(没有增加数据,只是方便理解,不占内存)/repeat扩展维度
print("扩展维度:",eg1.expand(4,3,28,28).shape)
print(eg1.expand(-1,3,28,28).shape)

#4.矩阵的转置
print("转置后:",eg.transpose(1,3).contiguous().view(4,3*28*28).view(4,28,28,3).transpose(1,3).shape)
print("高级转置方法:",eg.permute(0,2,3,1).shape)
变换: torch.Size([4, 3, 784])
增加: torch.Size([1, 4, 3, 28, 28])
删减: torch.Size([3, 28, 28])
扩展维度: torch.Size([4, 3, 28, 28])
torch.Size([1, 3, 28, 28])
转置后: torch.Size([4, 3, 28, 28])
高级转置方法: torch.Size([4, 28, 28, 3])

三、合并与分割

1、矩阵间如何合并?使用cat,除合并的维度,其余维度必须一样;stack则不同于cat,它会多增加一个维度进行合并

eg2 = torch.rand(5,32,8)
eg3 = torch.rand(3,32,8)
print("拼接:",torch.cat([eg2,eg3],0).shape)  #用cat拼接
eg4 = torch.rand(1,12,12,32)
eg5 = torch.rand(1,12,12,32)
#利用stack进行拼接,但是它不同于cat拼接,不是在原有的维度上拼接,而是在指定维度的前面新增加一个维度进行拼接
print(torch.stack([eg4,eg5],1).shape)
拼接: torch.Size([8, 32, 8])
torch.Size([1, 2, 12, 12, 32])

2、如何进行拆分?有两种方法,一个是基于长度的split,一个基于数量的chunk

#拆分操作
#split by length进行拆分
s1 = torch.rand(2,5,6)
c,v = s1.split([1,1],0)
print(c.shape,v.shape) #拆分后得分别赋值,才能看到各自的维度
#利用chunk拆分,按数量拆分
c1,v1 = s1.chunk(2,dim=2)
print(c1.shape,v1.shape)
torch.Size([1, 5, 6]) torch.Size([1, 5, 6])
torch.Size([2, 5, 3]) torch.Size([2, 5, 3])

四、数学运算

eg11 = 3*torch.ones(2,2)
eg22 = torch.ones(2,2)

#1.加法
print(torch.add(eg11,eg22))

#2.减法
print(torch.sub(eg11,eg22))

#3.乘法
print(eg22@eg11)  #矩阵相乘(大于两维的一般计算后面两维)
print(eg22*eg11)  #矩阵中的元素相乘

#4.除法
print(eg22/eg11)

#5.次方的运算
print(eg11.pow(2))  #矩阵eg11的2次方
aa = eg11**2 #也是eg11的二次方
print(aa.sqrt())  #平方根
print(aa.rsqrt())  #平方根的倒数
print(aa**(1/3))

#6.EXP OR LOG
bb = torch.exp(eg22)  #进行e^1
print(bb)
print(torch.log(bb))  #log默认以e为底
print(bb.clamp(3))
print(bb.clamp(0,2))  #将其限制在0到2之间
tensor([[4., 4.],
        [4., 4.]])
tensor([[2., 2.],
        [2., 2.]])
tensor([[6., 6.],
        [6., 6.]])
tensor([[3., 3.],
        [3., 3.]])
tensor([[0.3333, 0.3333],
        [0.3333, 0.3333]])
tensor([[9., 9.],
        [9., 9.]])
tensor([[3., 3.],
        [3., 3.]])
tensor([[0.3333, 0.3333],
        [0.3333, 0.3333]])
tensor([[2.0801, 2.0801],
        [2.0801, 2.0801]])
tensor([[2.7183, 2.7183],
        [2.7183, 2.7183]])
tensor([[1., 1.],
        [1., 1.]])
tensor([[3., 3.],
        [3., 3.]])
tensor([[2., 2.],
        [2., 2.]])

五、属性统计可用到的方法

1、normal函数(1是进行平方,2是进行平方相加后的开方)

eg33 = torch.rand(8)
aaa = eg33.view(2,4)
bbb = eg33.view(2,2,2)
print(aaa.norm(1,dim=1))  #norm1是将矩阵元素进行平方
print(bbb.norm(2,0))  #norm2==将矩阵的元素平方相加之后再进行开方
print(torch.prod(eg33))  #累乘
print(eg33.mean()) #求均值
tensor([2.2402, 2.2549])
tensor([[1.0225, 1.0571],
        [0.1909, 0.9722]])
tensor(0.0011)
tensor(0.5619)

2、max函数与argmax函数。两者都是找出数据中最大的值的索引,但是max函数还以看见其值是多少。

print(aaa.max(dim=1))  #torch.return_types.max(values=tensor([0.7341, 0.8172]),indices=tensor([1, 0]))  可用来查看神经网络最后结果的置信度
print(aaa.argmax(dim=1))
print(aaa.max(dim=1,keepdim=True))  #keepdim的作用是维持原来的维度不变

torch.return_types.max(
values=tensor([0.8056, 0.8749]),
indices=tensor([3, 1]))
tensor([3, 1])
torch.return_types.max(
values=tensor([[0.8056],
        [0.8749]]),
indices=tensor([[3],
        [1]]))

3、topk函数与kthvalue函数。找出数据中较大的值,前者找得多个,后者找寻一个

#topk API可用来返回数据中较大的数值
print(aaa.topk(3,dim=1))  #若要选取最小的几个,则在后面加上largest=False
#kthvalue API可用来找某一个值
print(aaa.kthvalue(3,dim=1))  #找第三小的值
torch.return_types.topk(
values=tensor([[0.8056, 0.6580, 0.5932],
        [0.8749, 0.7826, 0.5442]]),
indices=tensor([[3, 0, 1],
        [1, 0, 3]]))
torch.return_types.kthvalue(
values=tensor([0.6580, 0.7826]),
indices=tensor([0, 0]))

4、where和gather的用法。(where可用来对某个数据集进行0,1标注;gather可用来进行矩阵间的匹配)

#where的用法
cond = torch.rand(2,2)
print(cond)
aaaa = torch.ones(2,2)
bbbb = torch.zeros(2,2)
print(torch.where(cond>0.5,aaaa,bbbb))
#gather的用法
index = 100+torch.arange(0,4)
print(index)
print(torch.gather(index.expand(2,4),1,aaa.topk(3,dim=1)[1]))
tensor([[1., 0.],
        [1., 1.]])
tensor([100, 101, 102, 103])
tensor([[103, 100, 101],
        [101, 100, 103]])

完结...

你可能感兴趣的:(2021-07-16 Pytorch的基本用法)