栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pytorch学习笔记(1)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pytorch学习笔记(1)

首先安装好后pytorch

使用import pytorch如果程序不报错,那么就是安装好了。

一、torch数据结构——tensor(张量)
  • torch.float()
  • torch.int()
  • torch.bool()
torch创建tensor时要用dtype指定类型

torch也可以使用指定类型函数快速创建 

d = torch.FloatTensor(2,3)
e = torch.IntTensor(2)
f = torch.IntTensor([1,2,3,4])
print(d, e, f)

out:

tensor([[ 7.2398e-07,  4.5710e-41, -2.0912e+23],
        [ 3.0812e-41,  6.7262e-43,  0.0000e+00]]) 

tensor([64,  0], dtype=torch.int32) 

tensor([1, 2, 3, 4], dtype=torch.int32)
其他torch函数

torch.rand(2, 3)  # 两行三列的随机数 

torch.ones(2, 3)  # 两行三列的全1,默认dtype=float32,也可指定dtype改变

torch.zeros(2, 3)  # 两行三列的全0,dtype=float32

torch.arange(0, 10, 2)  # 0到10,间隔为2, --> tensor([0, 2, 4, 6, 8])

二、torch和numpy互换

numpy的array和torch的tensor可以相互转换

# 定义numpy数组

# array --> tensor
arr1 = np.array([[1,2,3],[4,5,6]])
ten1 = torch.tensor(arr1)       # method 1

# tensor --> array 
ten2 = torch.from_numpy(arr1)   # method 2
arr2 = ten.numpy()

out:
ten1:     tensor([[1, 2, 3],
                  [4, 5, 6]])

tens:     tensor([[1, 2, 3],
                  [4, 5, 6]])
arr2:     [[1 2 3]
          [4 5 6]]

三、tensro的属性

a = torch.tensor([1,2,3])

a.shape  # -->torch.Size([3])   和调用a.size()   得到的结果相同

a.dtype   # -->cpu

a.device  # -->torch.int64

四、torch的运算 基础:  + - * /
############哈达玛积(element wise,对应元素相乘)
a*b     +-*/
torch.mul(a,b)   # add sub div
a.mul(b)
a.mul_(b)   # -->  加下划线之后,乘完之后改变a的值

#######矩阵运算

###低维情况
a = torch.tensor([[1,2],[3,4]])
b = torch.tensor([[1,0],[1,0]])
print(a, "n",b)

print(torch.mm(a,b))     # 矩阵乘积形式1
print(torch.matmul(a,b)) # 矩阵乘积形式2
print(a @ b)             # 矩阵乘积形式3
print(a.matmul(b))       # 矩阵乘积形式4
print(a.mm(b))           # 矩阵乘积形式5

###高维情况
# 前两个必须相同,后面两位相乘

a = torch.ones(1,2,3,4)
b = torch.ones(1,2,4,3)
# 3*4 @ 4*3 = 3*3
print(a.matmul(b))
print(torch.matmul(a, b))
 幂指对运算 pow、 exp、 log
###########幂运算

##### a^2
torch.pow(a,2) 
a.pow(2)
a**2
a.pow_(2)

##### e^x
torch.exp(a))
b = a.exp_()

##### 根号
a.sqrt()
a.sqrt_()

###########对数运算
torch.log2(a)  # 每个数都分别取对数
torch.log10(a)
torch.log(a)   #  底数为e
相同返回True
################### tensor 比较运算

torch.eq(input,other,out=None)# 对每个元素进行等式操作,返回boolean tensor,全部相同返回True
torch.equal(tensor1,tensor2)# 如果tensor1,tensor2 有相同的size和elements,则为一个True或False
torch.ge(input,other,out=None)  # input >=other
torch.gt(input,other,out=None)  # input >other
torch.le(input,other,out=None)  # input <=other
torch.lt(input,other,out=None)  # input  
torch其他函数 
################### torch统计学函数

torch.mean()      #返回均值 
torch.sum()       #返回总和 
torch.prod()      #返回 所哟普元素的积
torch.max()       #返回最大值 
torch.min()       #返回最小值
torch.argmax()    #返回最大值排序的索引值
torch.argmin()    #返回最小值排序的索引值
torch.std()       #返回标准差 
torch.var()       #返回方差
torch.median()    #返回中间值 
torch.mode()      #返回众数值
torch.histc()     #返回input的直方图
torch.bincount()  #返回每个值的频数,只支持一维的tensor

################### tensor函数

torch.abs()  # L1_loss   
torch.sigmoid()  # 激活函数
torch.sign()  # 符号函数  -1,x<0   0,x=0     1,x>0
torch.cumprod()
torch.cumsum()

五、torch操作

if tensor.cuda.is_available():

        tensor = tensor.to("cuda")

索引切片

a[ : ,  1 ]  -->第一列

a[ 0 ,  : ]  -->第一行

改变形状

改变tensor形状view()    类似于numpy的reshae

a.view(3,2)

a.view(-1,3)  # -1是由自动推导

合并tensor

t1 = torch.cat([tensor1, tensor2, tensor3], dim=1)

a=torch.rand(4,32,8)  # 4层32行8列
b=torch.rand(5,32,8)  # 5层32行8列
torch.cat([a,b], dim=0).shape #  --> torch.Size([9, 32, 8])  如果使用dim=1报错,因为4和5不相同

a=torch.rand(4,32,8)
b=torch.rand(4,32,8)
torch.cat([a,b], dim=1).shape  # torch.Size([4, 64, 8]) 因为4,,8相同

t2 = torch.stack([tensor1, tensor2],dim=1)

a=torch.rand(4,32,8)
b=torch.rand(4,32,8)torch.stack([a,b], dim=1).shape  # torch.Size([4, 2, 32, 8]) 因为4,,8相同

torch.Size([4, 2, 32, 8])

六、自动求导

x1 = torch.tensor(1, requires_grad = True)  # requires_grad表示这个变量可求导

x2 = torch.tensor(2, requires_grad = True) 

y = x1 + x2 * 2

使用x1.requires_grad   会返回True 或者 False,表示是否可以求导

out:        y = tensor(5.0, grad_fn=

此时如果输入:

x1.grad.data    程序报错,因为此时只进行了前向传播,未进行反向传播

所以,用反向传播

y = x1 + x2 * 2

y.backward()

print(x1.grad.data)  -->  tensor(1.)

print(x2.grad.data)  -->  tensor(2.)

注意:

# 1、 导数是会累计的,重复运行相同命令,grad会增加
# 2、 所以每次计算前都要清除当前导数值避免累计,这一功能可以通过pytorch的optimizer实现

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1012215.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号