iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python torch.flatten()函数案例详解
  • 792
分享到

Python torch.flatten()函数案例详解

2024-04-02 19:04:59 792人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

先看函数参数: torch.flatten(input, start_dim=0, end_dim=-1) input: 一个 tensor,即要被“推平”的 tensor。

先看函数参数:


torch.flatten(input, start_dim=0, end_dim=-1)

input: 一个 tensor,即要被“推平”的 tensor。

start_dim: “推平”的起始维度。

end_dim: “推平”的结束维度。

首先如果按照 start_dim 和 end_dim 的默认值,那么这个函数会把 input 推平成一个 shape 为 [n][n] 的tensor,其中 nn 即 input 中元素个数。

如果我们要自己设定起始维度和结束维度呢?

我们要先来看一下 tensor 中的 shape 是怎么样的:


t = torch.tensor([[[1, 2, 2, 1],
                   [3, 4, 4, 3],
                   [1, 2, 3, 4]],
                  [[5, 6, 6, 5],
                   [7, 8, 8, 7],
                   [5, 6, 7, 8]]])
print(t, t.shape)
 
运行结果:
 
tensor([[[1, 2, 2, 1],
         [3, 4, 4, 3],
         [1, 2, 3, 4]],
 
        [[5, 6, 6, 5],
         [7, 8, 8, 7],
         [5, 6, 7, 8]]])
torch.Size([2, 3, 4])

我们可以看到,最外层的方括号内含两个元素,因此 shape 的第一个值是 2;类似地,第二层方括号里面含三个元素,shape 的第二个值就是 3;最内层方括号里含四个元素,shape 的第二个值就是 4。

示例代码:


x = torch.flatten(t, start_dim=1)
print(x, x.shape)
 
y = torch.flatten(t, start_dim=0, end_dim=1)
print(y, y.shape)
 
 
运行结果:
 
tensor([[1, 2, 2, 1, 3, 4, 4, 3, 1, 2, 3, 4],
        [5, 6, 6, 5, 7, 8, 8, 7, 5, 6, 7, 8]]) 
torch.Size([2, 12])
 
tensor([[1, 2, 2, 1],
        [3, 4, 4, 3],
        [1, 2, 3, 4],
        [5, 6, 6, 5],
        [7, 8, 8, 7],
        [5, 6, 7, 8]]) 
torch.Size([6, 4])

可以看到,当 start_dim = 11 而 end_dim = −1−1 时,它把第 11 个维度到最后一个维度全部推平合并了。而当 start_dim = 00 而 end_dim = 11 时,它把第 00 个维度到第 11 个维度全部推平合并了。PyTorch中的 torch.nn.Flatten 类和 torch.Tensor.flatten 方法其实都是基于上面的 torch.flatten 函数实现的。

到此这篇关于python torch.flatten()函数案例详解的文章就介绍到这了,更多相关Python torch.flatten()函数内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Python torch.flatten()函数案例详解

本文链接: https://www.lsjlt.com/news/133968.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作