提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
新手村篇章:第一二章
提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录- 组队打Boss之pytorch
- 前言
- 一、pytorch怎么安装
- 二、安装步骤
- 1.安装anaconda
- 2.安装pytorch
- 最后一步
- 三、语法关卡来啦!!(精英怪)
- 第一部分的一些函数
- 自动求导
- 总结
前言
提示:这里可以添加本文要记录的大概内容:
例如:之所以报pytorch就是想逼自己一下,更加了解下python,学习一些数学知识
提示:以下是本篇文章正文内容,下面案例可供参考
一、pytorch怎么安装本人使用的是Windows系统所以下面的笔记主要是关于Windows系统的
二、安装步骤 1.安装anaconda就baga式安装
2.安装pytorch这里关于CUDA有讲究,需要到dos操作系统去使用 nvidia-smi指令去查
具体是小于你的CUDA版本就ok了,当然保守点也可以选择尽量小的
先打开下图中的Powershell prompt
再把上一步的安装命令在其窗口
输入后会车就ok,接下来就只是等了
看我一命通关!!
Tensor张量
第零阶张量 (r = 0) 为标量 (Scalar),第一阶张量 (r = 1) 为向量 (Vector), 第二阶张量 (r = 2) 则成为矩阵 (Matrix)。
import torch # 创建tensor,用dtype指定类型。注意类型要匹配 a = torch.tensor(1.0, dtype=torch.float) # 使用指定类型函数随机初始化指定大小的tensor d = torch.FloatTensor(2,3) e = torch.IntTensor(2) f = torch.IntTensor([1,2,3,4]) #对于python已经定义好的数据结构可以直接转换 print(d, 'n', e, 'n', f) #打印出的结果 #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) # tensor和numpy array之间的相互转换 import numpy as np#这里是因为到时候复习时看的清楚才把import放这里 g = np.array([[1,2,3],[4,5,6]]) h = torch.tensor(g) print(h) i = torch.from_numpy(g) print(i) j = h.numpy() print(j) #tensor([[1, 2, 3], # [4, 5, 6]]) #tensor([[1, 2, 3], # [4, 5, 6]]) #[[1 2 3] # [4 5 6]] #注意:torch.tensor创建得到的张量和原数据是不共享内存的,张量对应的变量是独立变量。 #而torch.from_numpy()和torch.as_tensor()从numpy array创建得到的张量和原数据是共享内存的,张量对应的变量不是独立变量,修改numpy array会导致对应tensor的改变。 g[0,0] = 100 print(i) # 常见的构造Tensor的函数 k = torch.rand(2, 3) l = torch.ones(2, 3) m = torch.zeros(2, 3) n = torch.arange(0, 10, 2) print(k, 'n', l, 'n', m, 'n', n) #tensor([[0.2652, 0.0650, 0.5593], # [0.7864, 0.0015, 0.4458]]) # tensor([[1., 1., 1.], # [1., 1., 1.]]) # tensor([[0., 0., 0.], # [0., 0., 0.]]) # tensor([0, 2, 4, 6, 8])就是间隔2,左闭右开 # 查看tensor的维度信息(两种方式) print(k.shape) print(k.size()) #torch.Size([2, 3]) #torch.Size([2, 3]) # tensor的运算 o = torch.add(k,l) print(o) #tensor([[1.2652, 1.0650, 1.5593], # [1.7864, 1.0015, 1.4458]]) # tensor的索引方式与numpy类似 print(o[:,1]) print(o[0,:]) #tensor([1.0650, 1.0015])第1列 #tensor([1.2652, 1.0650, 1.5593])第0行 # 改变tensor形状的神器:view print(o.view((3,2))) print(o.view(-1,2)) #tensor([[1.2652, 1.0650], # [1.5593, 1.7864], # [1.0015, 1.4458]]) #tensor([[1.2652, 1.0650], # [1.5593, 1.7864], # [1.0015, 1.4458]]) #科普下-1就是他根据这个来帮你算出对应的值 # tensor的广播机制(使用时要注意这个特性) p = torch.arange(1, 3).view(1, 2) print(p) q = torch.arange(1, 4).view(3, 1) print(q) print(p + q)#这里体现了广播,就是会再复制一列或一行再相加 #view第一个参数指的是行,第二个指列 #tensor([[1, 2]]) #tensor([[1], # [2], # [3]]) #tensor([[2, 3], # [3, 4], # [4, 5]]) # 扩展&压缩tensor的维度:squeeze print(o) r = o.unsqueeze(1) print(r) print(r.shape) #貌似在图片输入的情况会有用 #tensor([[1.2652, 1.0650, 1.5593], # [1.7864, 1.0015, 1.4458]]) #tensor([[[1.2652, 1.0650, 1.5593]], # # [[1.7864, 1.0015, 1.4458]]]) #torch.Size([2, 1, 3]) s = r.squeeze(0) print(s) print(s.shape) #tensor([[[1.2652, 1.0650, 1.5593]], # # [[1.7864, 1.0015, 1.4458]]]) torch.Size([2, 1, 3]) t = r.squeeze(1) print(t) print(t.shape) #tensor([[1.2652, 1.0650, 1.5593], # [1.7864, 1.0015, 1.4458]]) #torch.Size([2, 3])自动求导
import torch x1 = torch.tensor(1.0, requires_grad=True) x2 = torch.tensor(2.0, requires_grad=True) y = x1 + 2*x2 print(y) #tensor(5., grad_fn=) # 首先查看每个变量是否需要求导 print(x1.requires_grad) print(x2.requires_grad) print(y.requires_grad) #True #True #True # 查看每个变量导数大小。此时因为还没有反向传播,因此导数都不存在 print(x1.grad.data) print(x2.grad.data) print(y.grad.data) #--------------------------------------------------------------------------- #AttributeError Traceback (most recent call last) #/tmp/ipykernel_11770/1707027577.py in# 1 # 查看每个变量导数大小。此时因为还没有反向传播,因此导数都不存在 #----> 2 print(x1.grad.data) # 3 print(x2.grad.data) # 4 print(y.grad.data) # #AttributeError: 'NoneType' object has no attribute 'data' x1 #tensor(1., requires_grad=True) ## 反向传播后看导数大小 y = x1 + 2*x2 y.backward() print(x1.grad.data) print(x2.grad.data) #tensor(1.) #tensor(2.) # 导数是会累积的,重复运行相同命令,grad会增加 y = x1 + 2*x2 y.backward() print(x1.grad.data) print(x2.grad.data) #tensor(5.) #tensor(10.) # 所以每次计算前需要清除当前导数值避免累积,这一功能可以通过pytorch的optimizer实现。后续会讲到 # 尝试,如果不允许求导,会出现什么情况? x1 = torch.tensor(1.0, requires_grad=False) x2 = torch.tensor(2.0, requires_grad=False) y = x1 + 2*x2 y.backward() #--------------------------------------------------------------------------- #RuntimeError Traceback (most recent call last) #/tmp/ipykernel_11770/4087792071.py in # 3 x2 = torch.tensor(2.0, requires_grad=False) # 4 y = x1 + 2*x2 #----> 5 y.backward() #/data1/ljq/anaconda3/envs/smp/lib/python3.8/site-packages/torch/_tensor.py in #backward(self, gradient, retain_graph, create_graph, inputs) # 253 create_graph=create_graph, # 254 inputs=inputs) #--> 255 torch.autograd.backward(self, gradient, retain_graph, create_graph, #inputs=inputs) # 256 # 257 def register_hook(self, hook): #/data1/ljq/anaconda3/envs/smp/lib/python3.8/site-packages/torch/autograd/__init__.py #in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables, #inputs) # 145 retain_graph = create_graph # 146 #--> 147 Variable._execution_engine.run_backward( # 148 tensors, grad_tensors_, retain_graph, create_graph, inputs, # 149 allow_unreachable=True, accumulate_grad=True) # allow_unreachable #flag #RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
比较大篇幅的可能是报错内容哦,酌情看哦
具体要反向传播
以上就是新手村的主要内容,你已经通关了,但保守起见,建议多刷几遍刷经验



