#debug功能:调错功能 #torch=tensor=矩阵 #安装pytorch #anaconda prompt->pip install(百度pytorch官网) #安装CUDA(官网下载)安装GPU版本 #pytorch基本操作 x=torch.empty(5,3)//创建一个没有初始化的矩阵 x=torch.rand(5,3)//随机的 x=torch.zeros(5,3,dtype=torch.long)//全0 x=torch.tensor([5.5,3])//直接传入数据 x=x.new_ones(5,3,dtype=torch.double) x=torch.randn_like(x,dtype=torch.float)//创建一个矩阵,随机初始化 x.size//展示矩阵大小 #基本计算方法 y=torch.rand(5,3) x+y torch.add(x,y) #索引 x[:,1]//:表示取所有 x=torch.randn(4,4) y=x.view(16) z=x.view(-1,8)//view操作可以改变矩阵维度 #与numpy协同操作 a=torch.ones(5) b=a.numpy()//tensor格式转换成array import numpy as np a=np.ones(5) b=torch.from_numpy(a)//将array转换成tensor #自动求导机制 import torch #方法1 x=torch.randn(3,4,requires_grad=true)//可以对x进行求导 #方法2 x=torch.randn(3,4) x.requires_grad=true b=torch.randn(3,4,requires_grad=true) t=x+b//t自动可以求导 y=t.sum() y.backward()//反向传播 b.grad//b的导数 #计算流程 x=torch.rand(1) b=torch.rand(1,requires_grad=true) w=torch.rand(1,requires_grad=true) y=w*x z=y+b y.requires_grad//结果为ture x.is_leaf,w.is_leaf,b.is_leaf,y.is_leaf,z.is_leaf//最终结果不是叶子结点 #反向传播计算 z.bachward(retain_graph=true)//如果不清空,梯度会累加起来 w.grad b.grad
pytorch学习笔记1
最新推荐文章于 2024-10-02 08:41:51 发布