pytorch基本语法
pytorch安装
bing官网
找对应版本下载
记住一点:-c pytorch不要加上,否则下载速度巨慢
pytorch的基本语法
tensor张量
基本概念
标量:0维张量
矢量:一维张量
矩阵:二维张量
矩阵数组:三维张量
tensor()是一个函数
代码演示:
tensor = torch.arange(2,14,2):不用手打,创建一维张量,取不到14
a=torch.tensor(1,dtype=int)
a = torch.tensor([1,2,3],dtype=int)
a=torch.tensor([[1,2,3],[4,5,6]],dtype=int)
形状
a.dtype:看类型
a.shape:看形状
a.size():看形状
a.ndim:看维度
a.view(6):变形
a.reshape(6):变形
a.view(-1,1):-1是自动匹配
a.fatten():变一维,推平
生成矩阵
手动输入
tensor()是一个函数
a=torch.tensor(1,dtype=int)
a = torch.tensor([1,2,3],dtype=int)
a=torch.tensor([[1,2,3],[4,5,6]],dtype=int)
自动生成
tensor = torch.arange(2,14,2):创建一维张量,取不到14
torch.ones(2,3)
torch.zeros(2,3):0
torch.empty(2,3):无限接近0
torch.rand(2,3,(2,3))
torch.randint(0,2,(2,3))
加参数
dtype=torch.int64
requires_grad=True等等
类型转换
tensor转正常
一个:item
c=torch.randint(2,6,(2,3))
c[1].item()有返回值
多个的:np
import numpy as np
np.array(c)
转基本数据类型
int()
float()
long():不会直接修改
基本运算操作
+:a+b,a.add_(b),torch.add(a,b)
-:a-b
*:a*b,torch.matmul(a,tensor):必须都是int64既long类型
/:除
//:取整
%:取余
转置:A.T #一维张量不能转置
基本运算函数
torch.sum(sample)=sample.sum()
相加:sample.sum() #参数dim=0列相加,dim=1行相加
找最大:sample.max()
找最小:sample.min()
找最大下标:sample.argmax()
找最小下标:sample.argmin()
平均值:sample.mean()
开方:sample.median()
幂指数:sample**sum
数据的索引
一维张量的索引
tensor = torch.arange(2,14)
tensor[2]
tensor[2,5]
tensor[2:]
tensor[2,-1]
tensor[-5:]=tensor[-5:-1]
指定索引多个
index=[1,3,5,7]
tensor[index]
循环
for t in tensor:
print(t)
二维张量:
a[1][1]=a[1,1] #列表不可以,只能写成a[1][1]
a[:,1]=[a[0,1]+a[1,1]+a[2,1]+……]
自动求导
x=torch.randint(1,10,(2,3),dtype=float,requires_grad=True), #表示可导
y = x + 2
z = y * y * 3
out = z.mean() #y,z,out对x有继承
out.backward() #求导之前必须要做的
print(x.grad) #out对x的导数
排序
b=a.sort()或者torch.sort()
排序之后会生成两个列表
一个是b.values,一个是 indices 值,下标
clip函数
sample.clip(2,7)#小于2就变成2,大于7就变为7