栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

torch cheatsheet

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

torch cheatsheet

目录

参考网站:

tensor相关常用的函数:

loss func中的参数:

reducation替代reduce、size_average


参考网站:
  •    主页 - PyTorch中文文档

tensor相关常用的函数:
torch.eye(n_train)单位矩阵
torch.rand()、torch.randn()
torch.matmul()矩阵相乘的函数,参考:torch.matmul()用法介绍_杂文集-CSDN博客_torch.matmul
torch.sort()

repeat_interleave(

self: Tensor,

repeats: _int,

dim: Optional[_int]=None)

指定维度repeat tensor。

self: 传入的数据为tensor

repeats: 复制的份数

dim: 要复制的self的维度,可设定为0/1/2.....

  • tensor.unsqueeze(dim),在第dim维度上增加一个维度
    • 返回新的tensor对象
    • dim为负数时,类似数组切割,即在最后添加维度,比如-2,倒数第二个维度
weights = torch.ones((2, 4)) * 0.1
print(weights.shape)
weights)
# -----------output-------------
torch.Size([2, 4])
tensor([[0.1000, 0.1000, 0.1000, 0.1000],
        [0.1000, 0.1000, 0.1000, 0.1000]])

# return new tensor
weights_1 = weights.unsqueeze(1)
print(weights_1.shape)
print(weights_1)
# -------output----------
torch.Size([2, 1, 4])
tensor([[[0.1000, 0.1000, 0.1000, 0.1000]],

        [[0.1000, 0.1000, 0.1000, 0.1000]]])


weights_2 = weights.unsqueeze(2)
print(weights_2.shape)
print(weights_2)
# ----------outout--------------
torch.Size([2, 4, 1])
tensor([[[0.1000],
         [0.1000],
         [0.1000],
         [0.1000]],

        [[0.1000],
         [0.1000],
         [0.1000],
         [0.1000]]])

# dim为负数
weights_2 = weights.unsqueeze(-2) # 这里类似于unnsqueeze(1),结果为 torch.Size([2, 1, 4])
weights_2 = weights.unsqueeze(-1) # 这里类似于unnsqueeze(2),结果为 torch.Size([2, 4, 1])

loss func中的参数:
  • reducation替代reduce、size_average

        很多loss的函数都有reduce和size_average这两个参数,一般loss function的计算都是按batch去计算,每个batch都会有自己的loss结果,这两个参数就是用来控制最终返回的是batch loss矩阵,还是这些loss的某种计算。

  • reduce=True, 表示最后batch loss要合并,最后返回的是个标量,如何计算根据size_average来设置。
    • size_average=True,返回的是loss的avg
    • size_average=False, 返回的是loss的sum
  • reduce=False,表示最后batch loss不合并,直接返回向量形式的loss,当然size_average此时不起作用,失效。
  • reduce和size_average 将被deprecated废弃,用reduction替代:
    • reduce=True, size_average=True 用 reduction='mean‘替代
    • reduce=True, size_average=False 用 reduction='sum'替代
    • reduce=False, 用 reduction='none' 替代
  • 比如
# loss_func = torch.nn.MSELoss(reduce=True, size_average=True)
loss_func = torch.nn.MSELoss(reduction='mean')
input_tensor = torch.from_numpy(np.array([[1, 2], [3, 4]]))
target_tensor = torch.from_numpy(np.array([[2, 3], [3, 5]]))
loss = loss_func(torch.autograd.Variable(input_tensor).float(),
                 torch.autograd.Variable(target_tensor).float())
print(loss)
output: tensor(0.7500)

如果
loss_func = torch.nn.MSELoss(reduction='none')
output:
tensor([[1., 1.],
        [0., 1.]])

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/302316.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号