Pytorch的常用操作
前言
也是研一时候写的,后来又整理了一些,现在还是放到网上吧。
一、tensor创建
1. 常规
tensor(data,) | 类似np.array的构造函数 |
---|---|
ones(*sizes) | 全1Tensor |
zeros(*sizes) | 全0Tensor |
eye(*sizes) | 对角线为1,其他为0 |
arange(s,e,step) | 从s到e,步长为step |
linspace(s,e,steps) | 从s到e,均匀切分成steps份 |
rand/randn(*sizes) | 均匀/标准正态分布 |
比如,torch.ones([1,6,17,17])
关于随机数的生成,详见numpy和Pytorch中的random
2. 与list和numpy的转换
a=torch.ones([1,2,3])
#转换成ndarray
b=a.numpy()
# 转换成list
d=a.tolist()
#从numpy创建
c=torch.from_numpy(b)
3. 数据类型与转换
- 查看数据类型
tensor.dtype
- 数据类型的种类
一般来说只需要考虑torch.float
,torch.double
和torch.uint8
- 类型转换
(1)直接使用后缀转换tensor.int()
,tensor.float()
,tensor.double()
(2)使用tensor.type(torch.FloatTensor)
- 在实际使用中通常还涉及到cpu()和cuda()之间的转换
tensor.detach().cpu()
tensor.cuda()
- 关于tensor的属性分析,详见[Pytorch]tensor属性的学习笔记
4. 索引问题
因为pytorch支持花式索引,如果掌握,会极大提高编程效率。
详见python、numpy、Pytorch中的索引方式
二、基础操作
1. 针对单个元素的数学操作
- ceil/round/floor/trunc 上取整/四舍五入/下取整/只保留整数部分
如torch.ceil(input, out=None)
- clamp(input, min, max) 超过min和max部分截断
torch.clamp(input, min, max, out=None)
- torch.abs(input, out=None) 求绝对值
- torch.sqrt(input, out=None) 开方
- torch.exp(input, out=None) e指数,注意只支持浮点型
- torch.log(input, out=None) 以e为底
2. 矩阵乘法A乘B
torch.mm(matA, matB, out=None)
3. 比较操作
-
torch.max(tensor):返回tensor中最大的一个数
-
torch.max(tensor,dim):指定维上最大的数,返回tensor和下标
>>> c = torch.rand([2,10]) >>> torch.max(c,1) torch.return_types.max( values=tensor([0.9944, 0.9023]), indices=tensor([3, 6]))
-
torch.max(tensor1, tensor2): 比较两个tensor相比较大的元素
三、维度变化相关
1. 维度调整
- 查看维度
torch.shape
- 变换维度
torch.reshape([d0,d1,d2])
按照最内侧维度的数据变化最快的方式,和numpy默认的reshape相同,都是以“C”的方式。实际上是先按最内侧维度展开成一维数组,然后再向其中填充。
2. unsqueeze和squeeze
b=a.squeeze(a)
去掉维度值为1的维度b=a.unsqueeze(n)
增加一个维度在shape的第n个>>>c = c.unsqueeze(1) >>>c.shape [2,1,10]
3. 两个tensor合并
(1) torch.cat(tensors, dim=0, out=None)
(2) torch.stack(tensors)
合并时候新建一个维度
看示例就明白了
a = torch.rand([10,12])
b = torch.rand([10,12])
c = torch.cat([a,b],dim=1) # [10,24]
d = torch.stack([a,b]) #[2,10,12]
四、神经网络相关
这部分其实是主要内容。但不是一篇博客可以写的下的。所以,这里只列出一个以前写的博客列表
文章评论