Pytorch张量操作

Pytorch

1. 数据操作

  1. 创建张量
torch.arange()
torch.zeros()
torch.ones()
torch.randn()
torch.tensor()
torch.Tensor()
  1. 查看张量属性
x.shape / x.size()   # 张量形状
x.numel()  # 张量元素个数
x.dtype   # 张量类型
  1. 改变张量形状
x.view()   # 不生成副本
x.reshape()  # 生成原数据副本
  1. 交换维度
# 交换 dim0 和 dim1
torch.transpose(input, dim0, dim1) -> Tensor
x.transpose(dim0, dim1)
# 交换 dims
x.permute(dims) -> Tensor  
  1. 压缩维度
x.flatten(dim)        # 从 dim 维度开始压缩 
x.squeeze()          # 压缩维数为1的维度,可指定维数
x.unsqueeze(dim = a)    # 扩充指定维度
  1. 降维
A.sum(axis = 0)  # 沿指定维度 0 求和
# 
A.mean() 
A.sum()/A.numel()
# 
A.mean(dim = 0)
A.sum(aixs = 0) / A.shape[0]
  1. 非降维求和
sum_A = A.sum(axis = 0, keepdims = True)
A / sum_A
# 沿着某轴计算累积和
A.comsum(axis = 0)
import torch
x = torch.ones(12).reshape(3, -1)
y = torch.zeros(12).reshape(3, -1)
x = x.unsqueeze(0)       # (3,4) -> (1. 3. 4)
x = x.transpose(-1, -2)  # (1, 3, 4) -> (1, 4, 3)
x = x.permute(1,2,0)     #  (1, 4, 3) -> (4, 3, 1)
x = x.flatten(1)         # (4, 3, 1) -> (4,3)
x = x.reshape(3,-1)      # (4, 3\) -> (3, 4)
x.size()
torch.Size([3, 4])

2. 运算符

  1. 基本运算
x + y, x - y, x * y, x / y, x ** y
  1. 求幂
torch.exp(x)
  1. concatenate:
torch.cat((x,y),dim = 0)   # 在现有维度拼接
torch.stack((x,y),dim =  )  # 在一个新维度拼接
  1. 逻辑判断
x == y
  1. 元素求和:
x.sum()
  • t o r c h . c a t ( ) torch.cat() torch.cat()
z_0 = torch.cat((x, y), dim = 0)
z_1 = torch.cat((x,y), dim = 1)

x.shape, z_0.size(), z_1.size()
(torch.Size([3, 4]), torch.Size([6, 4]), torch.Size([3, 8]))
  • t o r c h . s t a c k ( ) torch.stack() torch.stack()
z0 = torch.stack((x, y), dim = 0)
z1 = torch.stack((x, y), dim = 1)
z2 = torch.stack((x, y), dim = 2)

z0.size(), z1.size(), z2.size()
(torch.Size([2, 3, 4]), torch.Size([3, 2, 4]), torch.Size([3, 4, 2]))

3. 广播机制

4. 索引 & 切片

5. 转换类型

  1. torch.tensor -> numpy.ndarray
a = x.numpy()
  1. numpy.ndarray -> torch.tensor
b= torch.from_numpy(a)
b = torch.Tensor(a)
b = torch.tensor(a)

6. 张量运算

  1. Hadamard 积
A * B
  1. 点积(Dot Product)
x.dot(y)
torch.sum(x * y)
  1. 矩阵-向量积
torch.mv(A, x)
  1. 矩阵乘法
torch.mm(A, B)
# 常见
torch.mm(A, A.transpose(-1, -2))
  1. 范数
torch.norm(input, p, dim, out=None,keepdim=False) → Tensor # 求指定维的L2范数
torch.abs(x)sum() # 求L1范数
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值