Pytorch笔记汇总-Tensor的基本操作

目录

目录

1.GPU使用时要初始化:

2.torch.matmul()矩阵乘法

3.自动求导

4.learning_rate通常用0.001, minst手写数字集用0.01

5.MINST手写数字集(0-9)

6.写程序的时候的快捷键

7.Tensor常用函数

8.Tensor创建

9.Tensor索引

10.Tensor维度转换

11.广播机制

12.Tensor的数学运算

13.Tensor的统计属性




1.GPU使用时要初始化:

import torch as t 

device = t.device("cuda") #可为'cpu'
a = a.to(device)
b = b.to(device)
print(a.device) #查看变量在cpu还是在gpu上

2.torch.matmul()矩阵乘法

3.自动求导

import torch as t 
from torch import autograd

x = t.tensor(1.) #tensor只能是浮点数
a = t.tensor(1., requires_grad=True)
b = t.tensor(2., requires_grad=True)
c = t.tensor(3., requires_grad=True)

y = a**2 *x +b*x +c
print('before',a.grad,b.grad,c.grad)#none
grads = autograd.grad(y, [a,b,c])#结果存在数组内
print('after', grads[0],grads[1],grads[2])

4.learning_rate通常用0.001, minst手写数字集用0.01

5.MINST手写数字集(0-9)

(1)28 * 28

(2)每个数字有7000张图片

(3)采用one-hot编码 (N位寄存器对应N个状态)

6.写程序的时候的快捷键

shift+tab 往前缩进

ctrl+1 集体注释/去注释

7.Tensor常用函数

import torch as t

a = t.randn(2, 3)

a.type() #输出一个字符串
type(a) #输出一个类

isinstance(a, torch.FloatTensor) ->True
isinstance(a,torch.cuda.FloatTensor) ->False

a.shape#torch.Size([2, 3])
a.shape[0] #2
a.shape[1] #3

a.size()#torch.Size([2, 3])
a.size(0)
a.size(1)

a.dim() 维度

a.numel() # number of element返回占内存大小

​

8.Tensor创建

import torch as t
'''
tensor 每一个维度都要有意义,比如
torch.rand(2,3,28,28)分别表示2张图片,3个通道,图高与图宽。
'''
shape = [2,3]
a = t.tensor([[1.,2.,3.],[4.,5.,6.]]) #一定要用浮点数
b = t.empty(shape)
t.rand(shape) #均匀分布
t.rand_like(a)
t.randint(start, end,  shape) #左闭右开区间
t.randint_like(start, end,  a)
t.randn(shape) #正态分布
t.full(shape, num)
t.arange(start,end step) #左闭右开区间
t.linspace(start,end,step)#闭区间,step指等分个数
t.ones(shape)
t.zeros(shape)
t.eye(shape) #eye不能接受dim>=3的Tensor
t.randperm(num) #[0, num)  shuffle的功能
idx = t.randperm(2)
a[idx] #可以调换a的行顺序
#事实上,a[tensor([1,0])]将第一行与第二行交换了位置

9.Tensor索引

import torch as t
a = t.randn(4,3,28,28)
a[0].shape #[3,28,28]
a[0,0].shape #[28,28]
#','表示维度,‘:’冒号表示从哪到哪,和python一致,左开右闭区间。
a[:2].shape #[2,3,28,28]
a[:2, :1,:,:].shape #[2,1,28,28]

a.index_select(0, torch.tensor([0,1])).shape #意味着第0维上的第0,1张图片,[2,3,28,28]
#其中第二个参数为tensor
#tips:Tensor和list一样是共享地址的

a[0,...].shape #[3,28,28]
a[:,1,...].shape #[4,28,28]
#...表示一种省略,自动匹配,一般只放在开头或者结尾

mask=a.ge(0.5)
b = torch.masked_select(a,mask) #取出a中大于0.5的元素,b是被打平了的

torch.take(a, torch.tensor([0,2,5])) #先打平,再取

10.Tensor维度转换

import torch as t
a=torch.randn(4,1,28,28)
a.view(4,28*28).shape #[4,784] 前后numel不变

a.squeeze(idx).shape #去除所有维度为1的维度,不给idx就删所有维度
a.unsqueeze(idx) #增加维度

a.expend(4,31,28,28).shape #[4,31,28,28],填-1是让python自己算
a.repeat(4,1,1,1).shape #[16,1,28,28] expand和repeat的维度须与原tensor一致

a.t() #只能转置二维矩阵
a.transpose(dimA, dimB)#互换AB维度的数值
#使用transpose后tensor在内存中存储不是连续的,不可以使用.view(),用.contiguous()转为连续
a.permute(1,3,0,2).shape #[1,28,4,28]大规模换维度,
#用permute后tensor在内存中存储不是连续的,不可以使用.view(),用.contiguous()转为连续

t.eq(tensor1, tensor2) #两个tensor的维度需要一致,结果是对应索引True or False
t.all(t.eq(tensor1, tensor2)) #a与b每一个元素等才返回True

import torch as t

a = t.randn(3,12,13)
b = t.randn(4,12,13)
t.cat(a,b dim=0).shape #[7,12,13] #dim需一致,除了要cat的维度,其他维度应一致。


a = t.randn(3,12,13)
b = t.randn(3,12,13)
t.stack(a,b, dim=0).shape #[2,3,12,13] stack的dim必须一致,赋予一个新的维度

a = t.randn(3,32,8)
aa,bb = a.split([2,1],dim=0)
aa.shape #[2,32,8]
bb.shape #[1,32,8]
a.split(1,dim=0) #把3分成每份为1,所以分成三份
#a.split(1,dim=0) == a.chunk(3,dim=0) chunk是分为3份

11.广播机制

从低纬度开始匹配,在大维度上插入维度为1,并对该维度(维度为1的维度进行扩展),只能为数值为1的维度进行扩展。

12.Tensor的数学运算

import torch as t

a-b == t.sub(a,b)
a+b == t.add(a,b)
a*b == t.mul(a,b) #是点乘,要求ab的维度完全一致。element-wise
a/b == t.div(a,b)
a @ b == t.matmul(a,b)#对于高维 [4,3,28,64] @ [4,3,64,32] 只计算最后两个维度的矩阵乘

a = torch.exp(torch.ones(2,2))
torch.log(a) #默认e为底

a = t.tensor(3.14)
a.floor() #去整数下界 3 
a.ceil() #取整数上界 4 
a.trunc() #取整数 3
a.frac() #取分数 0.1400
a.round() #四舍五入 3

a = t.tensor([[1,2,3],[4,5,6]])
a.max() #6
a.min() #1
a.medium() #3
a.clamp(2,4) # [[2,2,3],[4,4,4]] clamp(min,max)小于min的都变为min,大于max的都变为max
#若只有一个参数,是min

13.Tensor的统计属性

import torch as t

a = t.tensor([[1.,1.,1.],[1.,1.,1.]])
a.norm(1)#1范数
a.norm(1,dim=1)
Out[19]: tensor([3., 3.])

a.norm(1,dim=0)
Out[20]: tensor([2., 2., 2.])


a = t.tensor([[1.,1.,1.],[1.,1.,1.]])
a.norm(1)#1范数
a.norm(1.dim=1)

a.mean() #平均值
a.prod() #累乘
a.sum() #求和
a.argmax(), a.argmin() #先打平,再返回索引,可以给一个参数dim
a.max(dim=1, keepdim=True) #使返回的结果保留与a相同的维度

a.topk(num,dim,largest=True) #largest=True 求维度上的前num大
#largest=False 求维度上的前num小
a.kthvalue(num,dim)#求第K小

a>0
torch.gt(a,0)
a!=0
torch.eq(a,a) #数值比较
torch.equal(a,a) #整体比较

t.where(condition,x,y)
t.where(x>0,x,y) #条件满足的位置选x的值,不满足的位置选y的值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值