目录

一、 初始化张量

1. torch.arange()和range()

2. torch.rand()、torch.randn()、torch.randint()、torch.randperm()、torch.normal()

二、 运算

1.张量比较

2. torch.eq

3. torch.sum

4. torch.mean

5. torch.mm

6. torch.matmul

7. torch.clamp

8. torch.max

9. torch.norm

10. torch.argmax

11. 矩阵运算

三、维度操作

1. torch.cat

2. torch.chunk

3. torch.squeeze和unqueeze

4. A.view(a, b)


一、 初始化张量

1. torch.arange()和range()

torch.arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

    >>> torch.arange(5)  # 默认以 0 为起点tensor([ 0,  1,  2,  3,  4])>>> torch.arange(1, 4)  # 默认间隔为 1tensor([ 1,  2,  3])>>> torch.arange(1, 2.5, 0.5)  # 指定间隔 0.5tensor([ 1.0000,  1.5000,  2.0000])

torch.range(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

>>> y=torch.range(1,6)
>>> y
tensor([1., 2., 3., 4., 5., 6.])

2. torch.rand()、torch.randn()、torch.randint()、torch.randperm()、torch.normal()

 

torch.randint()同rand,生成int(均匀分布)

torch.randperm

torch.randperm(n, generator=None, out=None, dtype=torch.int64, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) → Tensor

torch.normal() 

返回一个张量,包含了从指定均值mean和标准差std的离散正态分布中抽取的一组随机数。

torch.normal(mean, std, generator=None, out=None) → Tensortorch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1))返回:
tensor([  1.0425,   3.5672,   2.7969,   4.2925,   4.7229,   6.2134,8.0505,   8.1408,   9.0563,  10.0566])torch.normal(mean=torch.arange(1., 6.))返回:
tensor([ 1.1552,  2.6148,  2.6535,  5.8318,  4.2361])torch.normal(2, 3, size=(1, 4))返回:
tensor([[-1.3987, -1.9544,  3.6048,  0.7909]])

二、 运算

1.张量比较

对于x=Tensor([0,1,2,3,4]),返回满足的则为1(True),否为0(False)

torch.gt(x, 1)   大于  -> [0,0,1,1,1]torch.ne(x, 1)   不等于  -> [1,0,1,1,1]torch.lt(x, 3)   小于  -> [1,1,1,0,0]torch.eq(x, 3)   等于  -> [0,0,0,1,0]

2. torch.eq

torch.pow(input, exponent, *, out=None) → Tensor

计算两个张量或者一个张量与一个标量的指数计算结果,返回一个张量。
input和exponent都可以是张量或者标量,
1)若input和exponent都为张量,则必须维度一致;
2)若input和exponent其中一个为标量,一个为张量,标量以广播的形式进行计算>>> a = torch.randn(4)
>>> a
tensor([ 0.4331,  1.2475,  0.6834, -0.2791])
>>> torch.pow(a, 2)
tensor([ 0.1875,  1.5561,  0.4670,  0.0779])
>>> exp = torch.arange(1., 5.)>>> a = torch.arange(1., 5.)
>>> a
tensor([ 1.,  2.,  3.,  4.])
>>> exp
tensor([ 1.,  2.,  3.,  4.])
>>> torch.pow(a, exp)
tensor([   1.,    4.,   27.,  256.])>>> torch.pow(2, a)
tensor([ 2.,  4.,  8., 16.])
>>> torch.pow(a, 2)
tensor([ 1.,  4.,  9., 16.])

3. torch.sum

1.torch.sum(input, dtype=None)
2.torch.sum(input, list: dim, bool: keepdim=False, dtype=None) → Tensor

import torcha = torch.ones((2, 3))
a1 =  torch.sum(a)
a2 =  torch.sum(a, dim=0)
a3 =  torch.sum(a, dim=1)print(a)
print(a1)
print(a2)
print(a3)

4. torch.mean

求平均数。

mean()函数的参数:dim=0,按列求平均值,返回的形状是(1,列数);dim=1,按行求平均值,返回的形状是(行数,1),默认不设置dim的时候,返回的是所有元素的平均值。

x=torch.arange(12).view(4,3)
'''
注意:在这里使用的时候转一下类型,否则会报RuntimeError: Can only calculate the mean of floating types. Got Long instead.的错误。
查看了一下x元素类型是torch.int64,根据提示添加一句x=x.float()转为tensor.float32就行
'''
x=x.float()
x_mean=torch.mean(x)
x_mean0=torch.mean(x,dim=0,keepdim=True)
x_mean1=torch.mean(x,dim=1,keepdim=True)
print('x:')
print(x)
print('x_mean0:')
print(x_mean0)
print('x_mean1:')
print(x_mean1)
print('x_mean:')
print(x_mean)
x:
tensor([[ 0.,  1.,  2.],[ 3.,  4.,  5.],[ 6.,  7.,  8.],[ 9., 10., 11.]])
x_mean0:
tensor([[4.5000, 5.5000, 6.5000]])
x_mean1:
tensor([[ 1.],[ 4.],[ 7.],[10.]])
x_mean:
tensor(5.5000)

5. torch.mm

torch.mm(mat1, mat2, *, out=None) → Tensor

注意:mat1和mat1只能是矩阵matrix, 并且无法只用广播机制

6. torch.matmul

该方法支持张量乘法,可以实现广播机制

torch.matmul(input, other, *, out=None) → Tensor

7. torch.clamp

将输入input张量每个元素的夹紧到区间 [min,max]内,并返回结果到一个新张量。

torch.clamp(input, min, max, out=None) → Tensor| min, if input < min
output = | input, if min <= input <= max| max, if input > max
a=torch.randint(low=0,high=10,size=(10,1))
print(a)
a=torch.clamp(a,3,9)
print(a)
tensor([[9.],[3.],[0.],[4.],[4.],[2.],[4.],[1.],[2.],[9.]])tensor([[9.],[3.],[3.],[4.],[4.],[3.],[4.],[3.],[3.],[9.]])

8. torch.max

torch.max(input, dim, max=None, max_indices=None) -> (Tensor, LongTensor)
返回输入张量给定维度上每行的最大值,并同时返回每个最大值的位置索引。
(返回的是最大值和索引!)torch.max(input, other, out=None) → Tensor
返回输入张量给定维度上每行的最大值,并同时返回每个最大值的位置索引。
即,( out_i=max(input_i,other_i) \)

9. torch.norm

torch.norm(input, p, dim, out=None,keepdim=False) → Tensor返回输入张量给定维dim 上每行的p 范数。 参数:input (Tensor) – 输入张量
p (float) – 范数计算中的幂指数值
dim (int) – 缩减的维度
out (Tensor, optional) – 结果张量
keepdim(bool)– 保持输出的维度  (此参数官方文档中未给出,但是很常用)

10. torch.argmax

得到指定维度最大值的索引值。

1. torch.argmax(input, dim=None, keepdim=False)import torch
a=torch.tensor([[1, 5, 5, 2],[9, -6, 2, 8],[-3, 7, -9, 1]])
b=torch.argmax(a,dim=0)
print(b)
print(a.shape)#tensor([1, 2, 0, 1])
#torch.Size([3, 4])2. a.argmax(dim)

11. 矩阵运算

  1. torch.mul()      矩阵点乘,要求shape一样。相当于A * B=A和B矩阵同位置的元素相乘赋值给新矩阵。
  2. torch.dot()       一维向量相乘,返回一个tensor值,与mul()相同。
  3. torch.mm()      矩阵乘法,(a, b)* (b, c) = (a, c)
  4. torch.mv()       矩阵和向量相乘,同mm(), 但只能是一个二维矩阵与一个一维向量相乘。
  5. torch.matmul() 同mm()的高维情况。

三、维度操作

1. torch.cat

即concatnate,将张量组合,拼接。

outputs = torch.cat(inputs, dim=?) → Tensor

>>> import torch
>>> A=torch.ones(2,3) #2x3的张量(矩阵)
>>> A
tensor([[ 1.,  1.,  1.],[ 1.,  1.,  1.]])
>>> B=2*torch.ones(4,3)#4x3的张量(矩阵)
>>> B
tensor([[ 2.,  2.,  2.],[ 2.,  2.,  2.],[ 2.,  2.,  2.],[ 2.,  2.,  2.]])
>>> C=torch.cat((A,B),0)#按维数0(行)拼接
>>> C
tensor([[ 1.,  1.,  1.],[ 1.,  1.,  1.],[ 2.,  2.,  2.],[ 2.,  2.,  2.],[ 2.,  2.,  2.],[ 2.,  2.,  2.]])
>>> C.size()
torch.Size([6, 3])
>>> D=2*torch.ones(2,4) #2x4的张量(矩阵)
>>> C=torch.cat((A,D),1)#按维数1(列)拼接
>>> C
tensor([[ 1.,  1.,  1.,  2.,  2.,  2.,  2.],[ 1.,  1.,  1.,  2.,  2.,  2.,  2.]])
>>> C.size()
torch.Size([2, 7])

2. torch.chunk

与cat相反,将张量拆分

torch.chunk(tensor, chunk_num, dim)

将tensor按dim(行或列)分割成chunk_num个tensor块,返回的是一个元组。

c = torch.tensor([[1., 2., 4.],[4., 5., 7.],[3., 9., 8.],[9., 6., 7.]])#在dim=1这一个维度进行拆分, chunk_num是拆分的块数,当其大于等于dim=1中元#素的个数n, 则拆成n块,小于则平分。torch.chunk(c,4,dim = 1)结果:(tensor([[1.],[4.],[3.],[9.]]),tensor([[2.],[5.],[9.],[6.]]),tensor([[4.],[7.],[8.],[7.]]))
torch.chunk(c,3,dim = 1)
结果:
(tensor([[1.],[4.],[3.],[9.]]),tensor([[2.],[5.],[9.],[6.]]),tensor([[4.],[7.],[8.],[7.]]))
torch.chunk(c,2,dim = 1)
结果:
(tensor([[1., 2.],[4., 5.],[3., 9.],[9., 6.]]),tensor([[4.],[7.],[8.],[7.]]))

3. torch.squeeze和unqueeze

对维度进行压缩与扩充。

1)a.squeeze(N) 就是在a中指定位置N加上一个维数为1的维度。

2)b=torch.squeeze(a,N) a就是在a中指定位置N加上一个维数为1的维度

c = torch.tensor([[[1., 2., 4.],[4., 5., 7.],[3., 9., 8.],[9., 6., 7.]]])
c.shape
#torch.Size([1, 4, 3])
b = c.squeeze(0)
print(b, b.shape)
tensor([[1., 2., 4.],[4., 5., 7.],[3., 9., 8.],[9., 6., 7.]]) torch.Size([4, 3])

4. A.view(a, b)

同A.reshape. a, b 为-1时可动态调整。

pytorch常用函数总结(更新中)相关推荐

  1. pandas常用函数(更新中)

    Series()    #创建序列,类似一维数组,是pandas的基本数据结构 s = pd.Series([1, 2, 3], index=['a', 'b', 'c'])    #创建一个序列s, ...

  2. scipy常用函数(更新中)

    from scipy.optimize import fsolve def f(x):    #定义要求解的方程组     x1 = x[0]     x2 = x[1]     return [2* ...

  3. statsmodels常用函数(更新中)

    from statsmodels.tsa.stattools import adfuller as ADF 导入ADF检验 import numpy as np print(ADF(np.random ...

  4. sklearn常用函数(更新中)

    from sklearn.linear_model import LinearRegression     #导入线性回归模型 model = LinearRegression() print(mod ...

  5. matplotlib常用函数(更新中)

    pyplot: import matplotlib.pyplot as plt plt.figure(figsize=(8, 3))    #设置图像大小 plt.plot(x, y, 'b--', ...

  6. numpy常用函数(更新中)

    array() np.array([1, 2, 3]): 创建一维数组,可执行切片.取最小值.排序等 [2 0 1 5] np.array([[2, 0, 1, 5], [1, 2, 3, 4]]): ...

  7. 全新开源,《Pytorch常用函数函数手册》开放下载!内含200余个函数!

    近期有很多小伙伴在后台咨询有没有关于Pytorch函数使用的学习资料.Pytorch是目前常用的深度学习框架之一,深受学生党的喜爱,小白本人也是使用的Pytorch框架.为了帮助更多小伙伴,小白学视觉 ...

  8. 哈工大博士历时半年整理的《Pytorch常用函数函数手册》开放下载!内含200余个函数!...

    近期有很多小伙伴在公众号后台咨询有没有关于Pytorch函数使用的学习资料.Pytorch是目前常用的深度学习框架之一,深受学生党的喜爱,小白本人也是使用的Pytorch框架.为了帮助更多小伙伴,小白 ...

  9. python 基础(数据类型、运算符、流程控制、推导式、函数等...更新中)

    python基础 一.认识Python 1.python起源 Python 的创始人为吉多·范罗苏姆(Guido van Rossum),江湖人称"龟叔". 1991年,第一个Py ...

  10. oracle tabe unlock_oracle数据库管理常用语句(不断更新中)

    1.删除用户及其用户下面的所有对象 drop user branch cascade; 2.删除表空间及其表空间里的所有内容 drop tablespace center INCLUDING CONT ...

最新文章

  1. Scrum立会报告+燃尽图(十一月十五日总第二十三次):代码规范与技术交流
  2. OpenCV为轮廓创建边界旋转框和椭圆
  3. HTTP协议通信原理
  4. 网页里面的下拉框与数据库交互
  5. hdoj-3342-Legal or Not(拓扑排序)
  6. python flask高级编程之restful_flask-restful使用总结
  7. 《网络攻防实践》 课程教学
  8. vs:严重性代码说明项目文件行错误LNK1168无法打开testes.exe进行写入
  9. vscode开发ExtJs安装插件以及破解方法
  10. anylogic和java,基于Anylogic的Java代码入门教程
  11. UBLOX配置/GPS配置设置/u-center使用
  12. iframe背景色透明
  13. 为什么要学编写通达信指标公式
  14. 基于模型的约束排序,并探究OTUs对pH的响应特征——单峰or线性?
  15. 8.2.1-elasticsearch内置分词器之standard/simple
  16. Python基础教程 | 第三章 字符串
  17. 大恒水星相机+opencv4.0.1保存视频
  18. 毕业设计-基于深度学习的图像隐写分析
  19. Tkinter学习笔记之Entry
  20. Struct复杂数据类型的UDF编写、GenericUDF编写

热门文章

  1. 记录Caused by: com.mysql.cj.exceptions.CJCommunicationsException
  2. 纤亿通浅谈FTTH和光分路器
  3. Maxwell-生产环境问题集锦
  4. Chrome 谷歌浏览器,如何安装合适的浏览器驱动?
  5. 【前端系列教程之CSS3】01_CSS概述、引入规则和三大机制
  6. [实战]利用RTMP实现直播系统
  7. linux下终端命令快捷键
  8. 8.17 拼拼图的小杉 1536
  9. Python 爬取B站视频信息 弹幕信息 生成词云统计
  10. tensorflow的卸载与重装