Pytorch学习笔记1

Pytorch学习笔记1

导入pytorch模块,若没有安装pytorch,可到 pytorch安装选择相应系统版本进行安装

import torch
import numpy as np
tensor的基本属性与生成
#生成2*3的随机张量 
a = torch.FloatTensor(2,3)
#生成默认类型的2*3的张量通过dtype查看类型
b = torch.Tensor(2,3)
print(a)
print(b.dtype)
a = torch.tensor([4])
print(a)

#生成元素为[4,3]的张量
torch.tensor([4,3])
#错误写法:
#torch.tensor(4,3)
#生成符合正态分布的张量,dim1:个数;dim2:通道个数channel;dim3:行长;dim4:列长
#生成的张量:若一个维度,一般表示偏置bias;若两个维度,一般表示图片输入[3,28*28];若三个维度,一般表示文字处理;若四个维度,一般表示图片
r = torch.randn(2,3,28,28) 
print(r.shape)

输出结果为:
tensor([[0., 0., 0.],
[0., 0., 0.]])
torch.float32
tensor([4])
torch.Size([2, 3, 28, 28])

创建Tensor
#从numpy数组中倒入 from_numpy 或者torch.as_tensor()。tensor.numpy()变为numpy数组
a = torch.from_numpy(np.array([1,2]))
print(a)
print(a.numpy())

#从python的list数据结构中倒入
b = torch.tensor([1,2,3])
print(b)
#指定类型名创建
c = torch.FloatTensor([1,2,3,4])
print(c)
d = torch.FloatTensor(2,3)
print(d)

输出:
tensor([1, 2])
[1 2]
tensor([1, 2, 3])
tensor([1., 2., 3., 4.])
tensor([[2.7418e-06, 1.0140e-11, 1.1210e-44],
[0.0000e+00, 1.7136e-07, 1.2779e+22]])
tensor([0.0000e+00, 2.5244e-29, 0.0000e+00, 2.5244e-29])

总结
1.若用tensor创建。
torch.tensor((2,4)) #创建包含2,4的tensor
torch.tensor([2,4]) #创建包含2,4的tensor
torch.tensor(4) #创建元素为4的张量 size=[] torch.tensor([4]) #创建包含元素为4的张来给你 size=[1]
2.指定类型创建
torch.FloatTensor((2,4)) #创建包含2,4的float型tensor
torch.FloatTensor([2,4]) #创建包含2,4的float型tensor
torch.FloatTensor(4) #创建dim1 = 4的float型tensor。即:4个元素一行
torch.FloatTensor(4,3) #创建dim1 = 4, dim2 = 3的float型tensor
初始化tensor
#0-1之间均匀的初始化,生成3*3的tensor
a = torch.rand(3,3)
print(a)

#正态的初始化,生成3*3的tensor
b = torch.randn(3,3)
print(b)

#初始化3*3的tensor,值都为7
c = torch.full([3,3],7)
print(c)

#生成a到b,不包含b的tensor
d = torch.arange(0,10)
print(d)

#eye:值为1的4*4的对角阵;ones:全为1;zeros:全为0
e = torch.eye(4)
print(e)

#生成0-10之间随机的矩阵,并打散
f = torch.randperm(10

输出:
tensor([0.4313, 0.5069, 0.9568])
tensor([[ 0.1360, 1.8631, 0.9356],
[-0.9338, -1.2699, -0.2736],
[ 0.1092, -0.5033, 1.8757]])
tensor([[7, 7, 7],
[7, 7, 7],
[7, 7, 7]])
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
tensor([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
tensor([9, 3, 6, 7, 0, 1, 2, 5, 4, 8])

维度变化
#tensor.reshape()
a = torch.arange(12.0)
a = a.reshape(3,4)
print(a)

#tensor.view()
b = torch.rand(4,1,28,28)
print(b.view(28,4,28).shape)

#压缩:squeeeze();展开:unsqueeze()
print(a.unsqueeze(0))   #unsqueeze(i),在i后面添加一个维度
print(b.squeeze().shape)#squeeze(),移除所有dim=1的维度

print(b.shape)
print(b.expand(4,14,28,28).shape)  #1->14可行。只有1可以变化
print(b.repeat(4,1,14,14).shape)   #各个维度变化倍数

#转置transpose(a,b).交换a,b的维度
print(b.shape)
print(b.transpose(0,1).shape)

#permute(0,2,3,1):dim0不变;dim2->dim1;dim3->dim2;dim1->dim4
print(b.shape)
print(b.permute(0,2,3,1).shape)

输出:
tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
torch.Size([28, 4, 28])
tensor([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]]])
torch.Size([4, 28, 28])
torch.Size([4, 1, 28, 28])
torch.Size([4, 14, 28, 28])
torch.Size([16, 1, 392, 392])
torch.Size([4, 1, 28, 28])
torch.Size([1, 4, 28, 28])
torch.Size([4, 1, 28, 28])
torch.Size([4, 28, 28, 1])

Pytorch 广播
a = torch.rand((4,32,8))
b = torch.FloatTensor([5])
print((a+b).shape)

c = torch.FloatTensor(1,32,1)
print((a+c).shape)

a = torch.rand((4,32,14,14))
b = torch.rand((14,14))
print((a+b).shape)

输出:
orch.Size([4, 32, 8])
torch.Size([4, 32, 8])
torch.Size([4, 32, 14, 14])

合并与切割
#使用cat进行拼接。注意:按dim = d进行拼接时,其他dim的维度必须相同
a = torch.rand(4,32,8)
b= torch.rand(5,32,8)
print(torch.cat([a,b],dim = 0).shape)

#使用stack进行拼接,不会将指定维度拼在一起,而是在指定维度之前添加一个维度。0表示原来的a,1表示原来的b。
#注意:torch.stack([a,b],dim = d)。 拼接的维度d必须相同。如下都为5
a= torch.rand(5,32,8)
b= torch.rand(5,32,8)
print(torch.stack([a,b],dim = 0).shape)

#使用split进行拆分,按长度进行拆分[num1,num2]。拆分为num1和num2的tensor,num1+num2 = 原来的值
c = torch.stack([a,b,a,b], dim = 0)
print(c.shape)
aa1, bb1 = c.split([2,2], dim = 0)
aa1.shape,bb1.shape
aa2,bb2,cc2 = c.split([2,1,1],dim = 0)
aa2.shape,bb2.shape,cc2.shape
aa3,bb3 = c.split(3,dim = 0)#拆分为2个,3表示第一个的,第二个的自动推导出
print(aa3.shape,bb3.shape)
aa4,bb4 = c.chunk(2,dim = 3)#拆分为2个
print(aa4.shape,bb4.shape)

输出:
torch.Size([9, 32, 8])
torch.Size([2, 5, 32, 8])
torch.Size([4, 5, 32, 8])
torch.Size([3, 5, 32, 8]) torch.Size([1, 5, 32, 8])
torch.Size([4, 5, 32, 4]) torch.Size([4, 5, 32, 4])

Tensor的基本运算
a = torch.rand(4,3)
b = torch.rand(3)

print('-------加法测试--------')
print(a.add(b))
print(a+b)
print()
print('-------减法测试--------')
print(a.sub(b))
print(a-b)
print()
print('-------乘法法测试--------')
print(a.mul(b))
print(a*b)
print()
print('-------除法测试--------')
print(a.div(b))
print(a/b)

#矩阵乘法
print('-------矩阵乘法----------')
a = torch.tensor([[3,3],[3,3]])
b = torch.ones(2,2).long()
#元素乘法,对应位置相乘
print('a*b = ',a*b)
#矩阵相乘。1:torch.mm();2:torch.matmul(),相比于mm。此方法可以对高维张量相乘。3:@
print(torch.mm(a,b))
print(torch.matmul(a,b))
print(a@b)
#.t()转置
a = torch.rand(4,3,28,64)
b = torch.rand(4,3,64,32)
#print(a.mm(b))#会报错
print(torch.matmul(a,b).shape)
print((a@b).shape)

#平方:a.pow(2) 或者 ** 开方:a.sqrt() 或者 **0.5
#torch.exp(a)

a = torch.tensor(3.14)
print(torch.round(a))#四舍五入
print(torch.ceil(a))#上取整
print(torch.floor(a))#下取整
print(torch.trunc(a))#取整数部分
print(torch.frac(a))#取小数部分

grad = torch.rand(2,3)*15
print(grad)
print('最大值:',grad.max())
print('最小值:',grad.min())
print('均值:',grad.mean())
print('方差:',grad.var())
print('对行求和:',grad.sum(dim = 1))#0对列求和;1对行求和
print('中位数:',grad.median())
print('将小于10的都变为10:', grad.clamp(10))
print('将值限定在0-10之内:',grad.clamp(8,10))#小于8取8,大于10取10,其他不变
print('求最大值的索引位置:',grad.argmax(),';和0维的最小值的索引位置:',grad.argmin(dim = 0))

输出:
-------加法测试--------
tensor([[0.4575, 1.0354, 1.0420],
[0.4469, 1.1079, 1.1655],
[0.8844, 1.1245, 1.6397],
[0.2280, 1.2742, 1.6576]])
tensor([[0.4575, 1.0354, 1.0420],
[0.4469, 1.1079, 1.1655],
[0.8844, 1.1245, 1.6397],
[0.2280, 1.2742, 1.6576]])

-------减法测试--------
tensor([[ 0.2788, -0.2627, -0.3344],
[ 0.2681, -0.1903, -0.2109],
[ 0.7057, -0.1737, 0.2633],
[ 0.0493, -0.0239, 0.2812]])
tensor([[ 0.2788, -0.2627, -0.3344],
[ 0.2681, -0.1903, -0.2109],
[ 0.7057, -0.1737, 0.2633],
[ 0.0493, -0.0239, 0.2812]])

-------乘法法测试--------
tensor([[0.0329, 0.2508, 0.2435],
[0.0319, 0.2978, 0.3285],
[0.0710, 0.3086, 0.6548],
[0.0124, 0.4058, 0.6671]])
tensor([[0.0329, 0.2508, 0.2435],
[0.0319, 0.2978, 0.3285],
[0.0710, 0.3086, 0.6548],
[0.0124, 0.4058, 0.6671]])

-------除法测试--------
tensor([[4.1202, 0.5952, 0.5141],
[4.0007, 0.7069, 0.6935],
[8.8970, 0.7324, 1.3825],
[1.5519, 0.9632, 1.4085]])
tensor([[4.1202, 0.5952, 0.5141],
[4.0007, 0.7069, 0.6935],
[8.8970, 0.7324, 1.3825],
[1.5519, 0.9632, 1.4085]])
-------矩阵乘法----------
a*b = tensor([[3, 3],
[3, 3]])
tensor([[6, 6],
[6, 6]])
tensor([[6, 6],
[6, 6]])
tensor([[6, 6],
[6, 6]])
torch.Size([4, 3, 28, 32])
torch.Size([4, 3, 28, 32])
tensor(3.)
tensor(4.)
tensor(3.)
tensor(3.)
tensor(0.1400)
tensor([[11.5540, 12.3727, 0.4324],
[10.1802, 5.8624, 7.2057]])
最大值: tensor(12.3727)
最小值: tensor(0.4324)
均值: tensor(7.9346)
方差: tensor(19.7894)
对行求和: tensor([24.3591, 23.2484])
中位数: tensor(7.2057)
将小于10的都变为10: tensor([[11.5540, 12.3727, 10.0000],
[10.1802, 10.0000, 10.0000]])
将值限定在0-10之内: tensor([[10., 10., 8.],
[10., 8., 8.]])
求最大值的索引位置: tensor(1) ;和0维的最小值的索引位置: tensor([1, 1, 0])

数据统计
a = torch.full([8],1).float()
b = a.view(2,4)
c = a.view(2,2,2)
#norm(p) p范数
print(a.norm(1))
print(a.norm(2))
print(c.norm(2,dim = 1))#在1维度求范数

a = torch.rand(4,5)
print(a)
print('max: ',a.max(dim=1))
print('argmax: ',a.argmax(dim = 1))
print('max,keppdim :',a.max(dim = 1,keepdim = True))
print(a.topk(3,dim=1,largest=True))#返回第1维上最大的3个值,最小设置为False
print(a.kthvalue(3,dim = 1,))#返回第1维上第3大的值

输出:
tensor(8.)
tensor(2.8284)
tensor([[1.4142, 1.4142],
[1.4142, 1.4142]])
tensor([[0.0182, 0.4398, 0.5263, 0.3716, 0.9303],
[0.1398, 0.3868, 0.0902, 0.4231, 0.9096],
[0.9719, 0.9478, 0.2886, 0.5268, 0.3841],
[0.7851, 0.3434, 0.2289, 0.3156, 0.0474]])
max: torch.return_types.max(
values=tensor([0.9303, 0.9096, 0.9719, 0.7851]),
indices=tensor([4, 4, 0, 0]))
argmax: tensor([4, 4, 0, 0])
max,keppdim : torch.return_types.max(
values=tensor([[0.9303],
[0.9096],
[0.9719],
[0.7851]]),
indices=tensor([[4],
[4],
[0],
[0]]))
torch.return_types.topk(
values=tensor([[0.9303, 0.5263, 0.4398],
[0.9096, 0.4231, 0.3868],
[0.9719, 0.9478, 0.5268],
[0.7851, 0.3434, 0.3156]]),
indices=tensor([[4, 2, 1],
[4, 3, 1],
[0, 1, 3],
[0, 1, 3]]))
torch.return_types.kthvalue(
values=tensor([0.4398, 0.3868, 0.5268, 0.3156]),
indices=tensor([1, 1, 3, 3]))

高阶操作
#torch.where(condition,A,B)。
a = torch.tensor([[1,2],[3,4]])
b = torch.tensor([[1,3],[2,4]])
print(torch.where(a>2,a,b))
应用
  1. 通过backward()求梯度。torch.nn模块和torch.nn模块中的functional中已经编写了常用激活函数,可以直接使用
from torch.nn import functional as F
x = torch.tensor([[1.0,2.0],[3.0,4.0]],requires_grad = True)
y = torch.sum(x**2+2*x+1)
y.backward()
print(x.grad)

a = torch.linspace(-100,100,10)
F.tanh(a)
torch.tanh(a)

2.求损失函数

from torch.nn import functional as F
a = torch.linspace(1,10,10)
print(torch.norm(a,2))#torch.norm(a,p)。求p范数

x = torch.ones(1)
w = torch.full([1],2.0)
print('w不需要梯度:',w)#w不能求范数
w.requires_grad_()#更新w需要梯度
print('w更新需要梯度后:',w)

#求损失函数方式一:F.mes_loss(predict,label):均方误差函数。
mse = F.mse_loss(torch.ones(1),x*w)#mse_loss = norm(2)**2
print('均方误差:',mse)

#求损失函数方式二:torch.norm(predict-label)**2
print('通过2-范数的平方求误差',torch.norm(torch.ones(1)-x*w,2)**2)

print('test:',(torch.ones(1)-x*2).norm(2))

#torch.autograd.grad(y,[w,x]):y关于w和x求梯度
#print('mes关于w求梯度:',torch.autograd.grad(mse,[w]))

#通过loss.backward()求梯度
mse.backward()
print(w.grad)
#通常我们在调试的时候,不会直接看每个变量各个维度的梯度,而是打印改变量的梯度的范数
print(w.grad.norm())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值